@calimero-network/mero-js 25.0.6 → 25.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- function Hn(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function qn(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Qs=new Set(["token_reuse","token_revoked"]);function Ys(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var D=class extends Error{constructor(n,r,o,i,s){let a=Ys(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:lo(this.headers),bodyText:this.bodyText}}},re=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function lo(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Xs(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var ze=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:lo(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=this.buildUrl(e),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((A,C)=>{d[C]=A})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let A=n?.body;if(A!==void 0&&typeof A!="string"&&!(A instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:new URL(s).pathname,body:A}))}let m={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(m.body=n.body);let v;if(r>0&&o!==void 0){let A=n?.timeoutMs||this.transport.timeoutMs;if(A){let C=Date.now()-a,P=Math.max(0,A-C);v=this.createAbortSignal({...n,timeoutMs:P})}else v=this.createAbortSignal(n)}else v=c;if(v&&(m.signal=v),this.transport.credentials!==void 0&&(m.credentials=this.transport.credentials),n?.mode!==void 0&&(m.mode=n.mode),n?.cache!==void 0&&(m.cache=n.cache),n?.redirect!==void 0&&(m.redirect=n.redirect),n?.referrer!==void 0&&(m.referrer=n.referrer),n?.referrerPolicy!==void 0&&(m.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(m.integrity=n.integrity),n?.keepalive!==void 0&&(m.keepalive=n.keepalive),this.transport.getProof){let A=await this.transport.getProof({method:m.method??"GET",path:Xs(s),body:m.body});A&&(d["X-Calimero-Proof"]=A)}try{let A=await this.transport.fetch(s,m);if(!A.ok){let C=await this.getBodyText(A),P=new D(A.status,A.statusText,s,A.headers,C),T=A.headers.get("x-auth-error");if((A.status===401||A.status===403)&&T&&Qs.has(T)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new re(T,A.status,A.statusText,s,A.headers,C)}let j=n?.signal?.aborted===!0;if(A.status===401&&this.transport.refreshToken&&T==="token_expired"&&r<1&&!x&&!j)try{let _=this.refreshTokenPromise;_||(_=this.transport.refreshToken(),this.refreshTokenPromise=_);let f=await _;if(!f||f.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let b=this.onTokenRefreshPromise;b||(b=this.transport.onTokenRefresh(f),this.onTokenRefreshPromise=b),await b,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let k=n?.timeoutMs||this.transport.timeoutMs;if(k&&o!==void 0){let U=Date.now()-a;if(k-U<=0)throw P}return this.makeRequest(e,n,r+1,a)}catch(_){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,_ instanceof Error&&_.message.includes("onTokenRefresh")?_:P}throw P}return this.parseResponse(A,n?.parse)}catch(A){throw A instanceof D||A instanceof Error&&A.message.includes("onTokenRefresh")?A:new D(0,"Network Error",s,new Headers,A instanceof Error?A.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(qn(r)),n.length>0?Hn(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function Qe(t){return new ze(t)}function Re(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return Qe(e)}function vt(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return Qe(r)}function Bn(t){return typeof window<"u"?Re(t):vt(t)}function Zs(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function ea(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Rt(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!Zs(r,n-o))throw r;let s=ea(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let m=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(m,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function ta(t,e={}){return async(...n)=>Rt(()=>t(...n),e)}function p(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var ue=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${p(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${p(e)}/clients/${p(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${p(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${p(e)}/permissions`,{add:n.add,remove:n.remove})}};var Ye=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function Ku(t){let e=new Ye;return new ue(e)}function Lu(t){let e=new Ye;return new ue(e)}function Hu(t){let e=new Ye;return new ue(e)}function uo(t,e){return new ue(t)}var M={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},Bu={NONE:0,JOIN_ONLY:M.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:M.CAN_CREATE_CONTEXT|M.CAN_INVITE_MEMBERS|M.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:M.CAN_CREATE_CONTEXT|M.CAN_INVITE_MEMBERS|M.CAN_JOIN_OPEN_SUBGROUPS|M.CAN_CREATE_SUBGROUP|M.CAN_DELETE_SUBGROUP|M.CAN_MANAGE_VISIBILITY};function ju(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(M,n))e|=M[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Fu(t){return Object.keys(M).filter(e=>de(t,M[e]))}function de(t,e){let n=e>>>0;return(t&n)>>>0===n}function jn(t,e){return(t|e)>>>0}function Vu(t,e){return(t&~e)>>>0}var na={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function ra(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function oa(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function Fn(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function Vn(t){let e=oa(t),n;return e!==void 0?n=ra(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:na[n],message:Fn(t)}}function ia(t){return t.status!=="failed"||!t.retryable}function Qu(t){return!ia(t)}function sa(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function aa(t,e){let{kind:n,status:r}=Vn(t),o=sa(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function po(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=Fn(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=aa(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var Ct=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function Wn(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function go(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:Wn(t,n,"highWaterNonce"),windowWidth:Wn(t,n,"windowWidth")??0n},o=Wn(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function w(t){return t?.data}function ca(t,e){let[n,r]=mo(t),[o,i]=mo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let m=0;m<c;m++){let x=ho(s[m]??"0",a[m]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let m=0;m<l;m++){if(m>=u.length)return-1;if(m>=d.length)return 1;let x=ho(u[m],d[m]);if(x!==0)return x}return 0}function mo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function ho(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function la(t,e,n){return Rt(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var pe=class{constructor(e){this.httpClient=e}async healthCheck(){return w(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return w(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return w(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await la(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>ca(a,s))}async installDevApplication(e){return w(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return w(await this.httpClient.delete(`/admin-api/applications/${p(e)}`))}async listApplications(){return w(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}`))}async listApplicationVersions(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return w(await this.httpClient.get(`/admin-api/applications/${p(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${p(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${p(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return w(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return w(await this.httpClient.delete(`/admin-api/contexts/${p(e)}`))}async getContexts(){return w(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}`))}async getContextsForApplication(e){return w(await this.httpClient.get(`/admin-api/contexts/for-application/${p(e)}`))}async generateContextIdentity(){return w(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities`))}async getContextIdentitiesOwned(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities-owned`))}async joinContext(e){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/join`,{}))}async getContextGroup(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/group`))}async getContextStorage(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${p(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${p(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return w(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${p(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${p(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=w(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${p(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:w(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${p(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${p(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/context/${p(e)}`,{}))}async lookupApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/application/${p(e)}`,{}))}async deleteContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/context/${p(e)}`,{}))}async deleteApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/application/${p(e)}`,{}))}async listContextAliases(){return w(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return w(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/device/${p(e)}`,{}))}async deleteDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/device/${p(e)}`,{}))}async listDeviceAliases(){return w(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return w(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}`))}async getNodeIdentity(){return w(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/intents`,n))}async queryContext(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/query`,n))}async getIntentRelay(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/intents`))}async listNamespacesForApplication(e){return w(await this.httpClient.get(`/admin-api/namespaces/for-application/${p(e)}`))}async createNamespace(e){return w(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return w(await this.httpClient.request(`/admin-api/namespaces/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/invite`,n??{}))}async admitJoin(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return po({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/groups`,n??{}))}async listNamespaceGroups(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}/groups`))}async initAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/account/devices/${p(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(e)}/scope`,n))}async signWithAccountRoot(e){return w(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/link-device`,n))}async getGroupInfo(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return w(await this.httpClient.request(`/admin-api/groups/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${p(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce/${p(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Ct(r,i):i}return go(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Ct(r,i):i}return go(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${p(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/accounts/${p(n)}/seal`,r))}async listGroupContexts(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/role`,r)}async getMemberCapabilities(e,n){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(de(n,M.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=jn(n,M.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(de(r,M.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=jn(r,M.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${p(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${p(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`))?.data??null}async syncGroup(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/sync`,{}))}async upgradeGroup(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${p(e)}/migration-status`)}async getCascadeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/cascade-status`))}async retryGroupUpgrade(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${p(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/contexts/${p(n)}/remove`,{})}async createGroupInvitation(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/invite`,n??{}))}async joinGroup(e){return w(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return w(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return w(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return w(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return w(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${p(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${p(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${p(e)}/migration/abort`,{})}};function od(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function ld(t){return new pe(Re(t))}function ud(t){return new pe(vt(t))}function fo(t){return new pe(Bn(t))}function St(t,e){return new pe(t)}function Jn(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function zn(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}var yo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function g(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function F(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function S(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function h(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function E(t,e){let n=[S(t.length),t];for(let r of e)n.push(S(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",h(...n)))}async function oe(t){let e=g(t,"deviceSecret",32),n=h(yo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function bo(t,e,n){let r=await crypto.subtle.importKey("raw",g(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function ie(t){let e=g(t,"deviceSecret",32),n=h(yo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var ua=new TextEncoder().encode("calimero.auth.request.v1"),da=new TextEncoder().encode("calimero.auth.request.body.v1");function wo(t){let e=new TextEncoder().encode(t);return h(R(e.length),e)}async function Qn(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(da,[e])}async function kt(t){let e=await oe(t.signerSecret),n=await Qn(t.body),r=S(t.issuedAt),o=S(t.expiresAt),i=new TextEncoder,s=await E(ua,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(h(wo(t.method),wo(t.path),n,r,o,a))}function Et(t){let e=F(t.credential,"credential"),n=F(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):h(new Uint8Array([1]),F(t.session,"session statement"));return y(h(e,r,n))}function pa(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function It(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Et({credential:t.credential,session:t.session,request:await kt({method:r.method,path:r.path,body:pa(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Pt=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Yn(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Pt(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var Xe=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Yn(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var ga=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Ao(t){return t.type!==void 0&&ga.has(t.type)}var ma=new Set(["token_reuse","token_revoked"]),ha=new Set([401,403]),fa=1e4;function xo(t){let e=t.headers.get("x-auth-error");return!e||!ha.has(t.status)?null:ma.has(e)?e:null}var q=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{Ao(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n=await this.fetchImpl(e,{headers:{...await this.authorize({method:"GET",path:new URL(e).pathname}),Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=xo(n),o=await n.text().catch(()=>{});throw r?new re(r,n.status,n.statusText,e,n.headers,o):new D(n.status,n.statusText,e,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let o=r instanceof Error?r:new Error(String(r));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof re)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
2
- `);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),fa);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c=await this.fetchImpl(s,{method:"POST",headers:{...await this.authorize({method:"POST",path:new URL(s).pathname,body:a}),"Content-Type":"application/json"},body:a,signal:r.signal});if(!c.ok){let u=xo(c),d=await c.text().catch(()=>{});return u?new re(u,c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d):new D(c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Tt=class Tt{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),Tt.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};Tt.MAX_BACKOFF_MS=3e4;var se=Tt;function ae(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var Ze=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=ae()){await Yn(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=ae()){return Dt(this.sse,e,n,r)}};function Dt(t,e,n,r=ae()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var ya=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function vo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function Ce(t,e="secret"){let n=g(t,e,32),r=h(ya,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw vo(s)}return Co(o,i)}async function Ro(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")g(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return Co(t,n)}function Co(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw vo(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return Ce(t,n);throw new Error(`${n} or signer is required`)}var ba=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),wa=6e4,So=5*6e4,ko=1024,Io="mdma:enable-ha-namespace",Po="mdma:enable-ha-namespace-as-account";function Eo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Xn=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function To(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=ko))throw new Error(`relayUrl must be a non-empty string of at most ${ko} characters`);let o=t.ttlMs??wa;if(!(o>0&&o<=So))throw new Error(`ttlMs must be in (0, ${So}]`);let i=Xn(t.namespaceId,"namespaceId"),s=Xn(t.accountId,"accountId"),a=Xn(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),m=await c.sign(h(ba,l));return{kind:"account",credential:t.credential,signed_payload:Eo(l),signature:Eo(m)}}async function Aa(t){if(!t.subject)throw new Error("subject must be the cloud login email");return To(t,Io,t.subject)}async function Zn(t){return To(t,Po,void 0,t.relayUrl)}var xa=new TextEncoder().encode("calimero.device.cert.v1"),va=new TextEncoder().encode("calimero.account.genesis.v1"),Ra=new TextEncoder().encode("calimero.device.id.v1"),Se=2,Ca=237;async function er(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=g(t,"account",32),r=await E(Ra,[n,e]);return y(h(e,r.subarray(0,16)))}async function Nt(t){return E(xa,[g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function Do(t){return h(new Uint8Array([Se]),t.rootPublicKey,R(0),g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function No(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await V(e.publicKey),o=0,i=await Nt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=Do({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function tr(t){let e=g(t,"credential",Ca);if(e[0]!==Se)throw new Error(`this credential has account genesis version ${e[0]}, not ${Se} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>y(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function Ot(t){let e=tr(t),n=await V(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=g(e.device,"device",32).subarray(0,16);if(await er(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await bo(e.rootPublicKey,g(e.signature,"signature",64),await Nt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Ut(t){return V(y(await ie(t)))}async function V(t){return y(await E(va,[h(new Uint8Array([Se]),g(t,"rootPublicKey",32))]))}var Sa=new TextEncoder().encode("calimero.device.scope.v1");async function nr(t){return E(Sa,[g(t.account,"account",32),g(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>g(e,`applications[${n}]`,32))])}async function Oo(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await V(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await nr({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(h(new Uint8Array([Se]),n,R(0),g(r,"account",32),g(t.device,"device",32),R(o.length),...o.map((u,d)=>g(u,`applications[${d}]`,32)),R(i),R(s),c))}var rr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var ka=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Ea=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),ke=256,Uo=ke/32,or=(ke+Uo)/11;async function Mo(){let t=crypto.getRandomValues(new Uint8Array(ke/8));return Ho(y(t),await Bo(t))}async function _o(t){let e=qo(t);return Ho(y(await jo(e)),e.join(" "))}async function ir(t){return g(t,"secret",32),{secret:t,publicKey:y(await ie(t)),accountId:await Ut(t)}}async function Go(){let t=crypto.getRandomValues(new Uint8Array(ke/8)),e=await Bo(t);return{...await Ko(t),phrase:e}}async function $o(t){return Ko(await jo(qo(t)))}async function Ko(t){let e=await Ce(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function Q(t){let e=typeof t=="string"?await Ce(t,"rootSecret"):t;return Lo(e)}async function Mt(t,e){return Lo(await I(t,e,"rootSecret"))}async function Lo(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function et(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(h(ka,new TextEncoder().encode(t.nonce)));return Wo(n)}async function _t(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(h(Ea,new TextEncoder().encode(t.nonce)));return Wo(n)}async function Ho(t,e){return{...await ir(t),phrase:e}}function qo(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==or)throw new Error(`recovery phrase must be ${or} words, got ${n}`);return e}async function Bo(t){let e=Vo(t)+await Fo(t),n=[];for(let r=0;r<or;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(rr[o])}return n.join(" ")}async function jo(t){let e="";for(let r of t){let o=rr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(ke/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(ke)!==await Fo(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function Fo(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Vo(e).slice(0,Uo)}function Vo(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Wo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Ia=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),Gt=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Pa=568;function Ta(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function sr(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Da(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Na(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function $t(t){let e=await crypto.subtle.digest("SHA-256",Ta(Ia,new Uint8Array(32),t));return new Uint8Array(e)}function ar(t){let e=t.length>=Gt.length&&sr(t.subarray(0,Gt.length),Gt),n=e?Gt.length:Pa;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function Kt(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:y(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let m=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${m?`: ${m}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=Na(a.boundPublicKey,"boundPublicKey"),u=Da(a.quoteB64),{reportData:d,mock:l}=ar(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await $t(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!sr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!sr(d.subarray(32,64),await $t(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var Oa="Noise_NK_25519_AESGCM_SHA256",cr=32,Ua=16,Ma=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),ur=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Oa),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Ga(h(this.h,e))}async mixKey(e){let[n,r]=await Qo(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:zo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:zo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Qo(this.ck,new Uint8Array)}};async function Yo(t,e,n){let r=await ur.initialize();await r.mixHash(e),await r.mixHash(t);let o=await _a(n);return await r.mixHash(o.publicKey),await r.mixKey(await Jo(o.privateKey,t)),{message1:h(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<cr+Ua)throw new Error("Noise: message 2 is too short");let a=s.slice(0,cr);return await r.mixHash(a),await r.mixKey(await Jo(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(cr)),split:await r.split()}}}}async function _a(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",h(Ma,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:$a(n.x)}}async function Jo(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function zo(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Ga(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function lr(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function Qo(t,e){let n=await lr(t,e),r=await lr(n,new Uint8Array([1])),o=await lr(n,h(r,new Uint8Array([2])));return[r,o]}function $a(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var ti="/sealed/v2/handshake",ni="/sealed/v2",nt="application/vnd.calimero.sealed",dr=2,Ka=new TextEncoder().encode("calimero/sealed-http/v2"),tt=16,La=1+tt+8,Ha=0,qa=1,Ba=2,ja=1+64*1024+16,Fa=1024,Va=6e4,Wa="calimero.tee-attest.transport-key.v1",Ja=[101,204,205,304],ri=new TextEncoder,rt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Ee=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function oi(t,e){let n=await crypto.subtle.digest("SHA-256",h(ri.encode(Wa),t,e));return new Uint8Array(n)}async function ii(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=g(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?g(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await oi(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function ge(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return si({baseUrl:t.baseUrl,transportPublicKey:()=>ii(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function si(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,m)=>fetch(l,m)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await Zo(o,r,await Xo(s))}catch(l){if(!(l instanceof rt)||!i)throw l;return s=Promise.resolve().then(i),Zo(o,r,await Xo(s))}},u=async()=>{let l=a??d(void 0),m=await l;if(Date.now()<m.renewAt)return[m,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let m=c();a=m,m.catch(()=>{a===m&&(a=void 0)})}return a};return async(l,m)=>{let x=new Request(l,m),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let A=[];x.headers.forEach((f,b)=>A.push([b,f]));let C={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:A},P=new Uint8Array(await x.arrayBuffer()),T=async f=>{let{requestId:b,header:k,envelope:U}=await Qa(f,C,P),H=await o(`${r}${ni}`,{method:"POST",headers:{"content-type":nt},body:U,signal:x.signal});if(H.headers.get("content-type")!==nt)throw await ci(H);return Xa(H,f.responseKey,k,b)},[j,_]=await u();try{return await T(j)}catch(f){if(!(f instanceof Ee)||f.code!=="unknown_session")throw f;return T(await d(_))}}}async function Xo(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Zo(t,e,n){try{return await ei(t,e,n)}catch(r){if(!(r instanceof Ee)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),ei(t,e,n)}}async function ei(t,e,n){let r=await Yo(n,Ka),o=await t(`${e}${ti}`,{method:"POST",headers:{"content-type":nt},body:h(new Uint8Array([dr]),n,r.message1)});if(o.headers.get("content-type")!==nt)throw await ci(o);let i=await ec(o,Fa);return za(r,i)}async function za(t,e){if(e[0]!==dr)throw new Error("The handshake reply is malformed");let n;try{n=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:r,split:o}=n;if(r.length!==tt+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,tt),s=new DataView(r.buffer,r.byteOffset).getUint32(tt,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-Va,header(u){let d=new Uint8Array(La);return d[0]=dr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+tt,BigInt(u),!1),d}}}async function Qa(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:ai(r,0),additionalData:o},t.requestKey,Ya(e,n));return{requestId:r,header:o,envelope:h(o,new Uint8Array(i))}}function ai(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function Ya(t,e){let n=ri.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),h(r,n,e)}async function Xa(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Za(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:ai(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==Ha)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Ja.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===qa?d.enqueue(l.data):l.kind===Ba?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function Za(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=h(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>ja)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function ec(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=h(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function ci(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new rt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Ee(t.status,e,n,o)}var tc=/^[0-9a-f]{96}$/,nc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function gr(t){let e=Ie(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return nc.map(d=>Ie([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ie(t.allowedRtmr0??[],"allowedRtmr0"),Ie(t.allowedRtmr1??[],"allowedRtmr1"),Ie(t.allowedRtmr2??[],"allowedRtmr2"),Ie(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=oc(a),m=d??await t.fetchCollateral?.(l);if(!m)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,m,Math.floor(i()/1e3))}catch(P){throw new Error(`The quote did not verify: ${P?.message??String(P)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=rc(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let A=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(P=>y(P));if(n.length>0&&!n.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((P,T)=>{let j=r[T];if(j.length>0&&!j.includes(y(P)))throw new Error(`RTMR${T} ${y(P)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Ie(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!tc.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function rc(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function oc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var ic=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],pr="locked-read-only";function mr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==pr&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(pr)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>sc(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function sc(t,e){let n=ic.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var li=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],ui=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var ac="1.2.840.10045.2.1",cc={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},lc={"P-256":32,"P-384":48},uc={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function di(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function Te(t){let e=di(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=di(t.bytes,n,t.end);e.push(r),n=r.end}return e}function O(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ce(t){return t.bytes.slice(t.start,t.end)}function Lt(t){return t.bytes.slice(t.offset,t.end)}function Pe(t){let e=ce(O(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function dc(t){let e=new TextDecoder().decode(ce(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function hr(t){try{let[e,n,r,...o]=G(O(Te(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(O(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,m,...x]=i.slice(s);O(a,2,"The serial number");let v=Pe(G(O(n,48,"The signature algorithm"))[0]);if(Pe(G(O(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let C=uc[v];if(!C)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[P,T]=G(O(d,48,"The validity")).map(dc);if(T===void 0)throw new Error("its validity is incomplete");let[j,_]=G(O(m,48,"The public key"));O(_,3,"The public key");let[f,b]=G(O(j,48,"The key algorithm"));if(Pe(f)!==ac)throw new Error("its key is not an elliptic-curve key");let k=cc[Pe(b)];if(!k)throw new Error("its key is on a curve other than P-256 or P-384");let U=new Map,H=x.find(te=>te.tag===163);if(H){let[te]=G(H);for(let ne of G(O(te,48,"The extensions"))){let ve=G(O(ne,48,"An extension"));if(ve.length===3)O(ve[1],1,"An extension's critical flag");else if(ve.length!==2)throw new Error("it has a malformed extension");let Ln=Pe(ve[0]);if(U.has(Ln))throw new Error(`it has extension ${Ln} twice`);U.set(Ln,ce(O(ve[ve.length-1],4,"An extension value")))}}let ee=ce(O(r,3,"The signature"));if(ee[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:Lt(e),signatureHash:C,signature:ee.slice(1),issuer:Lt(O(u,48,"The issuer")),subject:Lt(O(l,48,"The subject")),notBefore:P,notAfter:T,spki:Lt(m),curve:k,extensions:U}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function pi(t){return G(O(Te(t),48,"The list")).map(Pe)}function pc(t,e){let n=lc[e],r=G(O(Te(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ce(O(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function Ht(t,e,n,r,o){let i;try{i=pc(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function W(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function fr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return W(n[0][1],e)}var gc="2.5.29.17",mc="2.5.29.37",hc="1.3.6.1.5.5.7.3.3",fc="1.3.6.1.4.1.57264.1.8",yc="1.3.6.1.4.1.57264.1.1",bc=134,wc=12,Ac=48,xc=new TextEncoder,De=t=>new TextDecoder().decode(t);async function gi(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=Sc(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=W(o,"The bundle signature"),u=fr(De(W(i,"The bundle certificate")),"The bundle certificate"),d=hr(u),l=ui.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let m=xc.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Ht(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(s.SignedEntryTimestamp,"The signed entry timestamp"),m))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let v=a.integratedTime*1e3;if(!fi(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${ot(v)}, when the entry says it was logged`);let A=kc(a.body),C=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(A.hash!==C)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!yr(W(A.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let P=fr(De(W(A.publicKey,"The logged certificate")),"The logged certificate");if(!yr(P,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Ht(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await vc(d,v),Cc(d,n),{integratedTime:a.integratedTime}}async function vc(t,e){if(!hi(t,e))throw new Error(`The signing certificate was valid ${ot(t.notBefore)} to ${ot(t.notAfter)}, not at ${ot(e)} when Rekor logged it`);let n=[];for(let r of li){let o=r.certChain.map(s=>hr(W(s,"A Fulcio certificate")));if(!await mi(t,o[0]))continue;let i=await Rc(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${ot(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Rc(t,e,n){if(!fi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!hi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await mi(o,i))return`its certificate ${r} is not signed by the next`}}async function mi(t,e){return yr(t.issuer,e.subject)?Ht(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function Cc(t,e){let n=t.extensions.get(gc);if(!n)throw new Error("The signing certificate names no identity");let r=G(O(Te(n),Ac,"The subject alternative name")),o=r.filter(u=>u.tag===bc).map(u=>De(ce(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(fc),s=t.extensions.get(yc),a=i?De(ce(O(Te(i),wc,"The OIDC issuer"))):s?De(s):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(mc);if(!c||!pi(c).includes(hc))throw new Error("The signing certificate is not for code signing")}function Sc(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function kc(t){let e;try{e=JSON.parse(De(W(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function hi(t,e){return t.notBefore<=e&&e<=t.notAfter}function fi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function ot(t){return new Date(t).toISOString()}function yr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var br=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),Ec=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],qt="https://cloud.calimero.network";async function bi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await gi(r,e,{identity:n.identity??br.identity,issuer:n.issuer??br.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>Ec.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function Bt(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function wi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function jt(t,e={}){let n=await xi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Ai(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function Ai(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function xi(t,e){let n=Ai(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return wi(o)}function Ft(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${it(e,"version")}`}async function vi(t){let e=it(t.minReleaseVersion,"minReleaseVersion"),n=it(t.release?.version,"The release version"),r=await bi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Pc(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return mr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function Vt(t){return it(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await vi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return gr({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Ic(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&it(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return ge({baseUrl:e,verify:Vt({...a,release:async()=>{let d=r===void 0?await jt(e,{fetch:c}):await xi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):Bt(Ft(n??qt,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Ri=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function it(t,e){let n=typeof t=="string"?Ri.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Pc(t,e){let[n,r]=yi(t),[o,i]=yi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,m]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&m?Math.sign(Number(u)-Number(d)):l!==m?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function yi(t){let e=Ri.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Tc=new TextEncoder().encode("calimero.warrant.v2"),Dc=new TextEncoder().encode("calimero.warrant.intent.v1"),Ci=64,Si=256;async function wr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(Dc,[new TextEncoder().encode(t),n])}async function Wt(t){let e=g(t.context,"context",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=g(t.releaseBytecodeId,"releaseBytecodeId",32),s=Ar(t.releaseVersion??""),a=le(t.accountHeads,"accountHeads"),c=le(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=g(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),m=await wr(t.method,t.argsJson),x=S(t.nonce),v=S(t.notAfter),A=await E(Tc,[e,n,d,r,o,i,s,l,m,S(a.length),...a,S(c.length),...c,x,v]),C=st(await u.sign(A));return y(h(e,n,d,r,o,i,R(s.length),s,R(l.length),l,m,R(a.length),...a,R(c.length),...c,x,v,C))}function st(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function Ar(t){let e=new TextEncoder().encode(t);return Nc(e.length),e}function Nc(t){if(t>Si)throw new Error(`releaseVersion is ${t} bytes, over the ${Si} a node accepts`)}function le(t,e){let n=t??[];if(n.length>Ci)throw new Error(`${e} cites ${n.length} heads, over the ${Ci} a node accepts`);return n.map((r,o)=>g(r,`${e}[${o}]`,32))}var Oc=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Uc=new TextEncoder().encode("calimero.context-creation.init.v1"),Jt=256;async function xr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E(Uc,[e])}async function Mc(t){return E(Oc,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function zt(t){let e=g(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):g(t.seed,"seed",32),r=g(t.authorAccount,"authorAccount",32),o=g(t.executor,"executor",32),i=g(t.executorKey,"executorKey",32),s=g(t.applicationId,"applicationId",32),a=ki(t.serviceName,"serviceName"),c=ki(t.name,"name"),u=le(t.accountHeads,"accountHeads"),d=le(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),m=g(l.publicKey,"signer.publicKey",32),x=await xr(t.initArgs),v=await Mc({group:e,seed:n,authorAccount:r,deviceKey:m,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),A=st(await l.sign(v));return{warrant:y(h(e,n,r,m,o,i,s,Ei(a),Ei(c),x,R(u.length),...u,R(d.length),...d,S(t.nonce),S(t.notAfter),A)),seed:y(n)}}function Ii(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,m)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${m} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let m=i(1,l)[0];if(m===0)return null;if(m!==1)throw new Error(`${l} has option tag ${m}, expected 0 or 1`);let x=s(l);if(x>Jt)throw new Error(`${l} is ${x} bytes, over the ${Jt} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function ki(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>Jt)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${Jt} a node accepts`);return n}function Ei(t){return t===null?new Uint8Array([0]):h(new Uint8Array([1]),R(t.length),t)}var _c=new TextEncoder().encode("calimero.governance-warrant.v1"),Gc=new TextEncoder().encode("calimero.governance-warrant.op.v1"),$c={group:0,root:1};async function vr(t){return E(Gc,[new Uint8Array([Rr(t.kind)]),t.bytes])}async function Kc(t){return E(_c,[t.scope,new Uint8Array([Rr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function at(t){let e=g(t.scope,"scope",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=le(t.accountHeads,"accountHeads"),s=le(t.governanceFloor,"governanceFloor"),a=Rr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=g(c.publicKey,"signer.publicKey",32),d=await vr(t.op),l=await Kc({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),m=st(await c.sign(l));return y(h(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,S(t.nonce),S(t.notAfter),m))}function Pi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,m)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${m} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Rr(t){let e=$c[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Lc={Admin:0,Member:1,ReadOnly:2},$={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},ct={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Hc=new TextEncoder().encode("calimero.namespace.id.v1"),Sr=new Uint8Array(32),Qt=R(0);function Di(t){let e=Lc[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Ne(t,e){return{kind:"group",bytes:h(N($.MemberAdded),g(t,"member",32),Di(e))}}function Yt(t){return{kind:"group",bytes:h(N($.MemberRemoved),g(t,"member",32),Sr,Qt)}}function lt(t){return{kind:"group",bytes:h(N($.MemberLeft),g(t,"member",32),Sr,Qt)}}function Xt(t,e){return{kind:"group",bytes:h(N($.MemberRoleSet),g(t,"member",32),Di(e))}}var qc=new TextEncoder().encode("calimero.subgroup.id.v1");async function kr(t,e,n,r){return y(await E(qc,[g(t,"admin",32),g(e,"parentId",32),new Uint8Array([n?1:0]),g(r,"salt",32)]))}function Ti(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return h(R(n.length),n)}function Zt(t){return{kind:"group",bytes:h(N($.TargetApplicationSet),Sr,g(t.applicationId,"applicationId",32),Ti(t.package,"package"),Ti(t.version,"version"))}}function Oe(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(de(t,M.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:h(N($.DefaultCapabilitiesSet),R(t))}}function Er(t){return{kind:"root",bytes:h(N(ct.GroupCreated),g(t.groupId,"groupId",32),g(t.parentId,"parentId",32),N(t.restricted?1:0),g(t.admin,"admin",32),g(t.salt,"salt",32))}}async function Ue(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await kr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Er({...t,groupId:n,salt:e})}}function en(t,e){return{kind:"root",bytes:h(N(ct.GroupReparented),g(t,"childGroupId",32),g(e,"newParentId",32))}}function tn(t){return{kind:"root",bytes:h(N(ct.GroupDeleted),g(t,"rootGroupId",32),Qt,Qt)}}async function nn(t,e){return y(await E(Hc,[g(t,"founder",32),g(e,"salt",32)]))}function rn(t){let e=F(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:h(N(ct.NamespaceCreatedV2),g(t.founder,"founder",32),e,g(t.salt,"salt",32))}}function Cr(t){let e=new TextEncoder().encode(t);return h(R(e.length),e)}function Ir(t){return t===void 0?N(0):h(N(1),Cr(t))}function Pr(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return h(R(n.length),...n.flatMap(([,r,o])=>[Cr(o),Cr(r)]))}function Bc(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(de(t,M.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function on(t,e){return{kind:"group",bytes:h(N($.MemberCapabilitySet),g(t,"member",32),R(Bc(e,"capabilities")))}}function sn(t){return{kind:"group",bytes:h(N($.ContextDetached),g(t,"contextId",32))}}function an(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:h(N($.SubgroupVisibilitySet),N(t==="open"?0:1))}}function Me(t={}){return{kind:"group",bytes:h(N($.GroupMetadataSet),Ir(t.name),Pr(t.data))}}function cn(t,e={}){return{kind:"group",bytes:h(N($.MemberMetadataSet),g(t,"member",32),Ir(e.name),Pr(e.data))}}function ln(t,e={}){return{kind:"group",bytes:h(N($.ContextMetadataSet),g(t,"contextId",32),Ir(e.name),Pr(e.data))}}function Ni(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function Oi(t,e,n){return{kind:"group",bytes:h(N($.ContextCapabilityGranted),g(t,"contextId",32),g(e,"member",32),Ni(n))}}function Ui(t,e,n){return{kind:"group",bytes:h(N($.ContextCapabilityRevoked),g(t,"contextId",32),g(e,"member",32),Ni(n))}}function un(t){return{kind:"root",bytes:h(N(ct.MemberJoinedOpen),g(t.member,"member",32),g(t.groupId,"groupId",32),F(t.credential,"credential"))}}var dn=300,me=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},jc=t=>new Promise(e=>setTimeout(e,t));function Fc(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var J=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${p(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(g(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";Ar(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??dn,l=await Wt({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),m=await this.json("POST",`/admin-api/contexts/${p(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:m.data.rootHash,returns:m.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${p(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${p(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new me(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new me(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??dn,{warrant:c}=await zt({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${p(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${p(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new me(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??dn,a=await at({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?y(g(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await nn(this.config.authorAccount,r),i=rn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:Oe(e.defaultCapabilities),a=e.application?Zt(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??dn,l=await at({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),m=await this.postGovernance(o,i,l),x={namespaceId:m.groupId,salt:r,teeEnabled:m.teeEnabled??!1,...m.teeError?{teeError:m.teeError}:{}},v=x,A=C=>C instanceof Error?C.message:String(C);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(C){v={...v,applicationSet:!1,applicationError:A(C)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(C){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:A(C)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${p(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(g(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(g(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Fc(s.headers);await jc(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Vc(c);throw new me(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Vc(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var he=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Wc=new TextEncoder().encode("calimero.auth.login.v1"),Mi={webOrigin:0,codeSigningId:1,cli:2};function _i(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Jc(t){return h(Uint8Array.from([Mi[t.kind]]),_i(t))}function zc(t){let e=Uint8Array.from([Mi[t.kind]]);if(t.kind==="cli")return e;let n=_i(t);return h(e,R(n.length),n)}async function pn(t){let e=g(t.node,"node",32),n=g(t.challenge,"challenge",32),r=g(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=g(o.publicKey,"signer.publicKey",32),s=S(t.issuedAt),a=S(t.expiresAt),c=await E(Wc,[e,Jc(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(h(e,zc(t.audience),n,r,i,s,a,u))}var Qc=300;async function Tr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await ie(t)),secret:t}}async function _e(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(m,x)=>{let v=new AbortController,A=setTimeout(()=>v.abort(),n),C;try{let T={...x,signal:v.signal};C=t.fetch?await t.fetch(`${e}${m}`,T):await globalThis.fetch(`${e}${m}`,T)}catch(T){throw new D(0,T instanceof Error?T.name:"NetworkError",`${e}${m}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(A)}let P=await C.text().catch(()=>"");if(!C.ok)throw new D(C.status,C.statusText,`${e}${m}`,C.headers,P);return P?JSON.parse(P):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await Tr(),a=Math.floor(Date.now()/1e3),c=await pn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Qc),signer:await I(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var Yc=3e4;function $e(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Xc(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var Ge=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-Yc>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await _e({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=Xc(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new q({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new se({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var Y=t=>new TextEncoder().encode(t),Zc=Y("calimero.auth.request.v1"),el=Y("calimero.auth.request.body.v1"),Dr="X-Calimero-Proof",tl=300;async function Nr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);if(n.includes("?"))throw new Error(`the path must carry no query string, got ${JSON.stringify(n)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`);let o=t.body===void 0?new Uint8Array:typeof t.body=="string"?Y(t.body):t.body,i=await E(el,[o]),s=Math.floor(t.now??Date.now()/1e3),a=s+(t.validForSeconds??tl),c=await E(Zc,[Y(e),Y(n),i,S(s),S(a)]),u=await nl(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=h(R(Y(e).length),Y(e),R(Y(n).length),Y(n),i,S(s),S(a),u),l=rl(r,"credential");return y(h(l,new Uint8Array([0]),d))}async function nl(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await oe(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function rl(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return g(n,e,n.length/2)}function Or(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await Nr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Dr]:o}}}function ol(t){return new URL(t).pathname}var Gi=new TextEncoder().encode("calimero/presence/1");async function $i(t){let e=t===null?new Uint8Array([0]):h(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function Ur(t){return h(Gi,g(t.contextId,"contextId",32),g(t.author,"author",32),S(t.seq),S(t.sentAtMs),await $i(t.state))}var il=2500,ut=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??il,this.now=e.now??Date.now}async set(e,n,r=ae()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=ae()){return Dt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await Ur({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function Ki(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function Li(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function sl(t,e,n){let r=e?.nodeKey;return r?new Ge({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??$e(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var fe=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof J?e.relay:new J({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=sl(i,e.observe,o),this.rpcTransport=new he(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Or(e.proof)),e.session){let s=e.session;this.relayAdmin=fo({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=St(Qe({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new Ke(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw Ki("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof he))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new q({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw Li("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):Li("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new ut({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw Ki("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function gn(t){return new fe(t)}var Gr="calimero.delegated.connection",$r="calimero.delegated.credential";function Kr(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Gr);return t?JSON.parse(t):null}catch{return null}}function qi(t){try{sessionStorage.setItem(Gr,JSON.stringify(t))}catch{}}function Bi(){try{sessionStorage.removeItem(Gr)}catch{}}function ji(){let t=Kr();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem($r);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function Fi(t){try{sessionStorage.setItem($r,JSON.stringify(t))}catch{}}function Vi(){try{sessionStorage.removeItem($r)}catch{}}function Lr(t){let e=hn(t);return{next:async()=>{let n=0n;try{n=Wi(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function hn(t){return`calimero.nonce.${t}`}function Wi(t){let e=localStorage.getItem(hn(t));if(e!==null)return BigInt(e);let n=`${hn(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function yn(t,e,n){try{Wi(t)<=n&&localStorage.setItem(hn(t),String(n+1n))}catch{}}var Ji="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function Hr(t,e){localStorage.setItem(Ji+X(t),e.trim().toLowerCase())}function bn(t){try{let e=localStorage.getItem(Ji+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function qr(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var al="locked-read-only",cl="2.3.99",Mr;function ll(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var Le=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function Hi(t,e){try{return await e()}catch(n){throw n instanceof Le?n:new Le(t,n)}}function ul(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Le(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function zi(t,e){return Object.assign(async r=>{let o=await Hi("loading the quote verifier",()=>(Mr??(Mr=import("@phala/dcap-qvl").then(i=>ll(i),i=>{throw Mr=void 0,i})),Mr));return Vt({dcapVerify:o,release:()=>Hi("fetching the release the relay runs",async()=>Bt(Ft(qt,await jt(t,{fetch:e})))),profile:al,minReleaseVersion:cl})(r)},{includeCollateral:!0})}async function He(t,e={}){let n=e.fresh?null:bn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=ul(r);try{let i=qr(t),{nodeKey:s}=await Kt({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:zi(t,o)}});return Hr(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Le||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function wn(t){let e=await He(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var fn=[1e3,2e3,5e3,1e4,3e4];function dl(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function Qi(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await He(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=fn[Math.min(r,fn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await dl(i,n)}return null}function pl(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var _r=new Map;function Yi(){_r.clear()}async function gl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function ml(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function hl(t){let e=(o,i)=>globalThis.fetch(o,i),n=ge({baseUrl:t,verify:zi(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&ml(s))return e(s);let a=await n(s.clone());return await gl(a)?(r||(r=!0,console.warn(`[mero-js] ${X(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function qe(t){if(qr(t))return;let e=X(t),n=_r.get(e);return n||(n=hl(t),_r.set(e,n)),n}function fl(t,e){let n=null,r=null;return async()=>{let o=n?pl(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=_e({nodeUrl:t.relayUrl,fetch:qe(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:$e()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var mn=new Map;function Xi(){mn.clear()}function yl(t){return typeof t=="object"&&t!==null&&t.status===409}function bl(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(mn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return mn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){yl(a)&&mn.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function wl(t){return new q({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function Al(t,e){let n=e.session?bl(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=wl(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function An(t,e){if(!t.relayUrl)return null;let n=bn(t.relayUrl),r=gn({transport:"relay",fetch:qe(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:Lr(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?fl({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return Al(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||qr(t.relayUrl)})}var Zi="calimero.delegated.relays.";function B(t){try{let e=localStorage.getItem(Zi+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function Br(t,e){try{localStorage.setItem(Zi+t,JSON.stringify(e))}catch{}}function ye(t,e,n){let r=B(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),Br(t,r)}function es(t,e){return B(t).contexts[e]??null}function xn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Be(t){let e=B(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(X);return[...new Set(n)]}async function ts(t){let e=[],n=B(t.account);for(let r of Be(t))try{if(!await wn(r))continue;let o=An({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return Br(t.account,n),e}async function ns(t){var o,i;let e=[],n=new Set,r=B(t.account);for(let s of Be(t))try{if(!await wn(s))continue;let a=An({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return Br(t.account,r),e}function Rn(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function dt(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}function xl(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var vn=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function vl(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Rn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new vn(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(m=>m.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function rs(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=new K({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=Cl(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=jr(i);if(!s)throw new Error(Sl(o,i));let a=new J({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??kl(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?ge({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new fe({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function Rl(t){let{root:e,authorAccount:n,...r}=t,o=await I(r.deviceSecret,r.signer,"deviceSecret"),i=await Q(e),a=await new K({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return rs({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function Cl(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function Sl(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function kl(t){let e=`mero-js:warrant-nonce:${t}`;try{return dt(e)}catch{return Rn(1)}}var El=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function os(t,e){g(e,"deviceSecret",32);let n=await oe(e),r=h(El,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return Il(o)}async function Cn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await os(t.nonce,e.deviceSecret)}}function Il(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var is="calimero.cloud.link.pending",Fr="link_state";var Vr=/^[0-9a-f]{64}$/;function ss(t){try{let e=localStorage.getItem(is),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function as(t){try{localStorage.setItem(is,JSON.stringify(t))}catch{}}function Sn(t,e){if(!Vr.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=ss(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},as(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(Fr,s),n.toString()}function je(t){let e=new URLSearchParams(t).get(Fr),n=ss(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],as(n),r}function cs(t){let e=new URLSearchParams(t);e.delete(Fr);let n=e.toString();return n?`?${n}`:""}var Pl="https://cloud.calimero.network";function ls(t){let e=new URL(t.cloudWebUrl??Pl);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Sn(t.accountId,t.returnTo)),e.toString()}function Tl(t){throw window.location.assign(ls(t)),new Error("redirecting to the cloud to authorise this link")}function Dl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw je(t.search??""),Wr(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;if(je(t.search??"")?.account!==o)throw Wr(),new Error("this account link answers a request this browser did not make - start the link again from here");return Wr(),{grant:r,account:o}}function Wr(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+cs(location.search))}async function Nl(t){let e=await Q(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new K({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var Ol="enrol-device",Ul="enrol-kem",Ml="callback-url",_l="state";function ps(t){ds(t.devicePublicKey,"devicePublicKey"),ds(t.kemPublicKey,"kemPublicKey"),Hl(t.returnTo),Ll(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Ol,t.devicePublicKey),e.searchParams.set(Ul,t.kemPublicKey),e.searchParams.set(Ml,t.returnTo),t.state&&e.searchParams.set(_l,t.state),e.toString()}function Gl(t){throw window.location.assign(ps(t)),new Error("redirecting to the wallet to approve this device")}function $l(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw us(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;us();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function us(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Kl(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Ot(t.credential);if(e.signPublicKey!==be(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${be(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==be(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==be(t.account))throw new Error(`the wallet reported account ${be(t.account)}, but the credential names ${e.account}`);if(e.device!==be(t.device))throw new Error(`the wallet reported device ${be(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function ds(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function be(t){return t.trim().toLowerCase()}function gs(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Ll(t){gs(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Hl(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function kn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function Bl(t,e){if(e.size===0)return!0;let n=kn(t.account);return n!==null&&e.has(n)}async function En(t){let e=t.cloud??new K({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let m=await e.getNamespaceRouting(t.namespaceId);n=m.nodes,r=m.servable}catch(m){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${m instanceof Error?m.message:String(m)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(kn).filter(m=>m!==null)),i=n.filter(m=>Bl(m,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(m=>m.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(m=>typeof m.relayUrl=="string"&&m.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(m=>m.canExecute)??u.find(m=>m.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${p(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var In=1440*60,zr={Admin:0,Member:1,ReadOnly:2};function ft(t){let e=t.admitters??[];return h(Jr(t.inviter_identity,"inviter_identity"),Jr(t.group_id,"group_id"),S(t.expiration_timestamp),Jr(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>g(n,`admitters[${r}]`,32)))}async function Qr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",ft(t)))}function Yr(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Pn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=g(e.publicKey,"signer.publicKey",32),r=g(t.groupId,"groupId",32);g(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(m=>m.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Yr(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((m,x)=>g(m,`admitters[${x}]`,32));let i=t.invitedRole??zr.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??In,In);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await Qr(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(g(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(g(t.appKey,"appKey",32))),l}function Jr(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var Xr=24,jl=new TextEncoder().encode("calimero.namespace.v1"),Fl=0,ms={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function hs(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return h(new Uint8Array([1]),new Uint8Array(t))}function fs(t){let e=new TextEncoder().encode(t);return h(R(e.length),e)}function Tn(t){let e=t.invitation,n=t.admitter_addrs??[];return h(ft(e),fs(t.inviter_signature),t.inviter_account?h(new Uint8Array([1]),g(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(fs),hs(t.application_id,"application_id"),hs(t.app_key,"app_key"))}async function Dn(t){let e=t.parentOpHashes??[],n=g(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?h(new Uint8Array([ms.MemberJoinedAt]),g(t.member,"member",32),Tn(t.invitation),S(o),n):h(new Uint8Array([ms.MemberJoined]),g(t.member,"member",32),Tn(t.invitation),n),s=h(new Uint8Array([Fl]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=g(a.publicKey,"signer.publicKey",32),u=h(new Uint8Array([Xr]),g(t.namespaceId,"namespaceId",32),R(e.length),...e.map((m,x)=>g(m,`parentOpHashes[${x}]`,32)),c,S(t.nonce),s),d=await a.sign(h(jl,u)),l=new Uint8Array([0]);return y(h(u,d,l))}function Vl(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function Wl(t){let e=dt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function ys(t){return t.replace(/\/+$/,"")}async function Nn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Dn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Wl(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${ys(t.nodeUrl)}/admin-api/namespaces/${p(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Vl(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:ys(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function On(t){let e=t.deps?.resolve??En,n=t.deps?.join??Nn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function bs(t,e,n,r){let i=await(r.bootstrap??On)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&ye(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(xn(t,i.session)),{namespaceId:e}}function ws(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function Zr(t,e){let n=ws(t),r=ws(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function Jl(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function yt(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Jl(n.appVersion,e.appVersion)?n:e,void 0)}async function bt(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function As(t,e,n={}){let o=(await bt(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=yt(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await Zr(e,a),signerId:a,version:s.appVersion}}function vs(t,e){return{next:async()=>zl(t,e)}}function zl(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function Rs(t,e){let n=B(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Ql(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Mn(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??qe(e)})}async function wt(t,e,n={}){let r=Rs(t,e.namespaceId),o=0n,i=await Mn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ql(e.initializationParams),name:e.name});return yn(r,i.contextId,o),ye(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function Ae(t,e,n={}){let r=Rs(t,e.namespaceId);return Mn(t,r,vs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Cs(t,e,n={}){let{groupId:r}=await Ae(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Ue({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await Ae(t,{namespaceId:e.namespaceId,group:r,op:Ne(i,"Member")},n);let{contextId:o}=await wt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function _n(t,e={},n={}){let o=Be(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await Yl(t,o,n.fetch),s=BigInt(Date.now()),a=await Mn(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(ye(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await Zl(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function Yl(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await xs(e)};let o=Object.entries(B(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await xs(e),s=await Mn(t,e,vs(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function xs(t){let e=await He(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var Gn="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Un={account_not_linked:Gn,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Xl(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function Zl(t,e,n,r,o){try{return await new K({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof we)return{haEnabled:!1,haError:Gn};if(i instanceof z&&Un[i.code]){let s=i.code==="ha_request_pending"?Xl(i):null,a=Un[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Fe(t,e,n=globalThis.fetch){let r=yt(await bt(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Ss="calimero.delegated.group-namespace.",eo=new Map;function ks(t){let e={};try{e=JSON.parse(localStorage.getItem(Ss+t)??"{}")}catch{}return{...e,...eo.get(t)}}function At(t,e,n){eo.set(t,{...eo.get(t),[e]:n});try{let r=ks(t);r[e]=n,localStorage.setItem(Ss+t,JSON.stringify(r))}catch{}}function xt(t,e){return B(t.account).namespaces[e]?e:ks(t.account)[e]}function Es(t,e){let n=xt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function $n(t,e,n){return Ae(t,{namespaceId:Es(t,e),group:e,op:n})}async function Kn(t,e,n){let r=Es(t,e);return Ae(t,{namespaceId:r,group:r,op:n})}var xe=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Ve=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},We=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},Is={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},eu=new Set(["upgradeGroup","retryGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function tu(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function Ps(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??$n,s=e.govern?.root??Kn,a=e.createContext??wt,c=e.found??_n,u=e.latestVersion??Fe,d=e.signInvitation??Pn,l=e.join,m=e.routing;async function x(f,b){if(!l)throw new xe("joinNamespace without a join handler");return l(f,b.invitation)}let v=()=>{if(r===null)throw new Ve("this call");return r};async function A(f){if(xt(n,f))return;let b=await v().getGroupInfo(f);At(n.account,f,b.namespaceId??f)}let C=async(f,b,k)=>(await A(b),i(f,b,k)),P=async(f,b,k)=>(await A(b),s(f,b,k));async function T(f){try{return await P(n,f,un({member:n.account,groupId:f,credential:n.credential})),!0}catch(b){if(tu(b))return!1;throw b}}async function j(f,b){let k=b??String(await v().getContextGroup(f)),{members:U}=await v().listGroupMembers(k);return U.some(H=>H.identity.toLowerCase()===n.account.toLowerCase())}let _={async listNamespacesForApplication(f){return(await v().listNamespaces()).filter(b=>b.targetApplicationId===f)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(f){if(!o.packageName)throw new xe("createNamespace without a packageName");let b=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:k,haEnabled:U,haError:H}=await c(n,{defaultCapabilities:231,application:{applicationId:f.applicationId,package:o.packageName,version:b}});return f.name&&await C(n,k,Me({name:f.name})),{namespaceId:k,haEnabled:U,...H!==void 0?{haError:H}:{}}},async createGroupInNamespace(f,b={}){let{op:k}=await Ue({parentId:f,restricted:b.visibility==="restricted",admin:n.account}),{groupId:U}=await P(n,f,k);return At(n.account,U,f),b.groupName&&await C(n,U,Me({name:b.groupName})),{groupId:U}},async addGroupMembers(f,b){for(let k of b.members)await C(n,f,Ne(k.identity,k.role??"Member"))},async removeGroupMembers(f,b){for(let k of b.members)await C(n,f,Yt(k))},async setGroupMetadata(f,b){await C(n,f,Me(b))},async setMemberMetadata(f,b,k){await C(n,f,cn(b,k))},async setContextMetadata(f,b,k){await C(n,f,ln(b,k))},async setDefaultCapabilities(f,b){await C(n,f,Oe(b.defaultCapabilities))},async setSubgroupVisibility(f,b){await C(n,f,an(b.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(f,b,k){await C(n,f,on(b,k.capabilities))},async deleteGroup(f){return await P(n,f,tn(f)),{isDeleted:!0}},async reparentGroup(f,b){return await P(n,f,en(f,b.newParentId)),{reparented:!0}},async leaveGroup(f){await C(n,f,lt(n.account))},async leaveNamespace(f){await C(n,f,lt(n.account))},async getContextIdentitiesOwned(f){return{identities:await j(f)?[n.account]:[]}},async joinContext(f){return await T(String(await v().getContextGroup(f))),{contextId:f,memberPublicKey:n.account}},async createContext(f){let k=(await v().getGroupInfo(f.groupId)).namespaceId??f.groupId,{contextId:U}=await a(n,{namespaceId:k,groupId:f.groupId,applicationId:f.applicationId,serviceName:f.serviceName,contextSeed:f.contextSeed,name:f.name,initializationParams:f.initializationParams});return{contextId:U,memberPublicKey:n.account,groupId:f.groupId}},async createNamespaceInvitation(f){let[{members:b},k]=await Promise.all([v().listGroupMembers(f),v().getGroupInfo(f)]),U=b.filter(ee=>ee.role==="RelayTee").map(ee=>ee.identity.toLowerCase());if(m){let ee=new Set(U.length>0?U:b.filter(ne=>ne.role==="Admin").map(ne=>ne.identity.toLowerCase())),te=null;try{te=(await m(f)).nodes}catch{}if(te!==null){if(te.length===0)throw new We(f,"not-hosted");if(!te.some(ne=>ne.account!==null&&ee.has(ne.account.toLowerCase())))throw new We(f,"no-named-node")}}return{invitation:await d({groupId:f,inviterAccount:n.account,deviceSecret:n.deviceSecret,...U.length>0?{admitters:U}:{},members:b,applicationId:k.targetApplicationId,appKey:k.appKey})}},async syncGroup(f){return{groupId:f,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(f,b,k){await C(n,f,Xt(b,k.role))},async joinSubgroupInheritance(f){return{groupId:f,memberPublicKey:n.account,wasInherited:await T(f)}},async detachContextFromGroup(f,b){await C(n,f,sn(b))}};return r===null?new Proxy({},{get(f,b){if(typeof b=="string")return b==="getNodeIdentity"?_.getNodeIdentity:b==="joinNamespace"?x:b in Is?Is[b]:async()=>{throw new Ve(b)}}}):new Proxy(r,{get(f,b,k){return typeof b=="string"&&b in _?_[b]:typeof b=="string"&&eu.has(b)?async()=>{throw new xe(b)}:Reflect.get(f,b,k)}})}function Ts(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Fe;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var nu="https://manager.cloud.calimero.network";function to(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function no(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function jr(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function ru(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function ou(t){return typeof t=="string"&&Vr.test(t)?t:null}var z=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},we=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};we.CODE="account_not_linked";var pt=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};pt.CODE="account_linked_to_several_users";var gt=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};gt.CODE="ha_request_pending";var mt=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};mt.CODE="unknown_relay";var ht=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};ht.CODE="relay_not_dialable";var Ds={409:[we,pt,gt],422:[mt,ht]};function iu(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var su="x-mdma-session-refresh",au="x-mdma-session-expires",K=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||nu).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await Q(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await _t({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${p(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:no(r),canExecute:to(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:ru(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return jr(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${p(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:no(r),canExecute:to(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${p(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Cn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${p(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${p(e)}/relays`,{anonymous:!0,headers:await Cn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:ou(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:no(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:to(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${p(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${p(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Zn({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${p(r)}/namespaces/${p(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof D&&Ds[i.status]){let s=iu(i.bodyText),a=Ds[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${p(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await Q(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await et({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":Sn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};return c&&je(o),s&&je(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Mt(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await et({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(su);if(!n||!this.session)return;let r=e.headers.get(au),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function ql(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function cu(t){if(t)return typeof t=="function"?t:It(t)}var lu="mero-js:token-refresh";function uu(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function ro(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var Ke=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.tokenStore&&(this.tokenData=this.tokenStore.getTokens(),this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=cu(this.config.requestProof);this.httpClient=Re({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=uo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=St(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new Xe({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new q({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new Ze({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new K(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new se({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:ro(i,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(e){this.tokenStore&&(this.tokenStore.setTokens(e),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=uu();return n?n.request(lu,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.tokenStore?.getTokens()??null;if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:ro(a,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||ro(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return Jn(e)}static buildAuthLoginUrl(e,n){return zn(e,n)}};function du(t){return new Ke(t)}var oo=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},pu="mero-tokens",io=class{constructor(e=pu){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var gu=new TextEncoder().encode("calimero.account.owner-op.v1"),mu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),hu=new TextEncoder().encode("calimero.account.genesis.v1"),fu=2,so={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Je={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},Os={AdminChanged:3,RootGuarded:12},yu={replica:0,relay:1},bu=new TextEncoder;function L(t){return new Uint8Array([t])}function Us(t){let e=bu.encode(t);return h(R(e.length),e)}function Z(t){return h(R(t.length),...t.map(Us))}function Ms(t){return L(t?1:0)}function _s(t){let e=yu[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function Gs(t){return{kind:"transferOwnership",plane:"group",bytes:h(L(Je.TransferOwnership),g(t,"newOwner",32))}}function $s(){return{kind:"groupDelete",plane:"group",bytes:L(Je.GroupDelete)}}function Ks(t){return{kind:"adminChanged",plane:"root",bytes:h(L(Os.AdminChanged),g(t,"newAdmin",32))}}function Ls(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:h(L(Je.TeeAuthoringPolicySet),Z(t))}}function Hs(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:h(L(Je.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),Ms(t.acceptMock),_s(t.mode))}}function qs(t){let e=t.minReleaseVersion===void 0?L(0):h(L(1),Us(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:h(L(Je.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),Ms(t.acceptMock),_s(t.mode))}}async function ao(t){return E(mu,[t])}async function co(t){return E(gu,[g(t.account,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(Bs(t.kind)),t.opDigest,S(t.counter),R(t.keyEpoch)])}function Bs(t){let e=so[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var Ns=132;async function js(t){let e=await ie(t.rootSecret),n=h(L(fu),e),r=y(await E(hu,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let m=F(d,`chain[${l}]`);if(m.length!==Ns)throw new Error(`chain[${l}] must be a ${Ns}-byte RootKeyHandoff, got ${m.length}`);return m});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await ao(t.op.bytes),a=await co({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await oe(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(h(n,R(i.length),...i,g(r,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(Bs(t.op.kind)),s,S(t.counter),R(o),u))}function Fs(t,e){let n=t.plane==="group"?Je.RootGuarded:Os.RootGuarded;return h(L(n),t.bytes,F(e,"rootProof"))}var Vs=[2428,2429,2528,2529],wu="localhost",Au=2e3;function Ws(t){return`http://${wu}:${t}`}function Js(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function zs(t,e={}){let{timeoutMs:n=Au,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=Js(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function xu(t={}){let{ports:e=Vs,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=Ws(i);return await zs(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}export{Po as ACCOUNT_HA_AUDIENCE,Io as ACCOUNT_OWNERSHIP_AUDIENCE,z as AccountHaRefusedError,pt as AccountLinkedToSeveralUsersError,we as AccountNotLinkedError,pe as AdminApiClient,ue as AuthApiClient,re as AuthRevokedError,M as CAPABILITIES,Bu as CAPABILITY_PRESETS,K as CloudClient,Vs as DEFAULT_LOCAL_NODE_PORTS,qt as DEFAULT_RELEASE_MIRROR,Ze as EphemeralClient,ti as HANDSHAKE_PATH,Gn as HA_ACCOUNT_NOT_LINKED_MESSAGE,Un as HA_REFUSAL_MESSAGES,D as HTTPError,gt as HaRequestPendingError,zr as INVITED_ROLE,me as IntentRefusedError,We as InvitationNotClaimableError,io as LocalStorageTokenStore,In as MAX_INVITATION_VALIDITY_SECS,oo as MemoryTokenStore,fe as MeroClient,Ke as MeroJs,br as NODE_RELEASE_SIGNER,Ve as NoRelayError,xe as NotForAccountError,so as OWNER_OP_KIND,Gi as PRESENCE_DOMAIN,pr as PRODUCTION_PROFILE,fn as RELAY_NODE_KEY_RETRY_MS,Dr as REQUEST_PROOF_HEADER,J as RelayClient,ht as RelayNotDialableError,Ge as RelayObserver,ut as RelayPresenceClient,he as RelayTransport,Xe as RpcClient,Pt as RpcError,nt as SEALED_CONTENT_TYPE,ni as SEALED_PATH,Xr as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Ee as SealedTransportError,q as SseClient,rt as StaleTransportKeyError,mt as UnknownRelayError,vn as WarrantNonceExhaustedError,Ct as WarrantNonceRouteUnavailableError,ze as WebHttpClient,se as WsClient,Ut as accountForRoot,V as accountForRootPublicKey,_o as accountRootFromPhrase,ir as accountRootFromSecret,$o as accountRootSignerFromPhrase,Ks as adminChangedOp,ql as admitterAddrsFromNetworkStatus,Zr as applicationIdForBundle,He as attemptRelayNodeKey,$t as attestKeyBinding,Kt as attestRelayNodeKey,xl as authorNonceLookup,Tl as beginCloudLink,Gl as beginDeviceEnrolment,On as bootstrapFromInvitation,zn as buildAuthLoginUrl,An as buildDelegatedClient,gs as callbackIsForeign,Et as callerProof,ju as capMask,Fu as capNames,xn as carryExecutorAccount,Vn as classifyError,Vi as clearDelegatedCredential,Bi as clearDelegatedSession,ls as cloudLinkUrl,Ft as cloudNodeReleaseUrl,Hn as combineSignals,ca as compareSemver,Nl as completeCloudLink,Kl as completeDeviceEnrolment,rs as connectCloud,Rl as connectCloudWithAccount,Oi as contextCapabilityGrantedOp,Ui as contextCapabilityRevokedOp,sn as contextDetachedOp,ln as contextMetadataSetOp,Ps as createAccountAdmin,Go as createAccountRootSigner,fo as createAdminApiClient,St as createAdminApiClientFromHttpClient,ge as createAttestedSealedFetch,Hu as createAuthApiClient,uo as createAuthApiClientFromHttpClient,ld as createBrowserAdminApiClient,Ku as createBrowserAuthApiClient,Re as createBrowserHttpClient,wt as createDelegatedContext,Cs as createDelegatedPrivateContext,Qe as createHttpClient,dt as createLocalStorageNonceSource,Rn as createMemoryNonceSource,gn as createMeroClient,du as createMeroJs,Ts as createNodeAdmin,ud as createNodeAdminApiClient,Lu as createNodeAuthApiClient,vt as createNodeHttpClient,Or as createProofAuthorizer,It as createProofSigner,gr as createQuoteVerifier,vl as createRecoveringNonceSource,ta as createRetryableMethod,si as createSealedFetch,Ic as createSignedReleaseSealedFetch,Vt as createSignedReleaseVerifier,qn as createTimeoutSignal,Bn as createUniversalHttpClient,kr as createdSubgroupId,xr as creationInitHash,Yr as defaultAdmitters,$e as defaultAudience,Oe as defaultCapabilitiesSetOp,Ae as delegatedGovernance,Nt as deviceCertPayload,ps as deviceEnrolmentUrl,nr as deviceScopePayload,xu as discoverLocalNodes,ft as encodeGroupInvitation,Tn as encodeSignedInvitation,ii as fetchAttestedTransportKey,Bt as fetchNodeRelease,jt as fetchNodeReleaseVersion,bt as fetchRegistryBundles,Xi as forgetMethodKinds,Yi as forgetRelaySealing,_n as foundDelegatedNamespace,nn as foundedNamespaceId,Mo as generateAccountRoot,Tr as generateSessionKey,$n as governGroup,Kn as governRoot,vr as governanceOpHash,Er as groupCreatedOp,$s as groupDeleteOp,tn as groupDeletedOp,Qr as groupInvitationHash,Me as groupMetadataSetOp,en as groupReparentedOp,de as hasCap,od as hexEncodeUtf8,wr as intentHash,ia as isSettled,bs as joinAsAccount,Nn as joinWithNode,ae as jsonCodec,Be as knownRelays,Fe as latestPublishedVersion,Qi as learnRelayNodeKey,ts as listDelegatedContexts,ns as listDelegatedNamespaces,Ws as localNodeUrl,_e as login,yn as markContextNonceSpent,Ne as memberAddedOp,on as memberCapabilitySetOp,un as memberJoinedOpenOp,lt as memberLeftOp,cn as memberMetadataSetOp,Yt as memberRemovedOp,Xt as memberRoleSetOp,er as mintDeviceId,rn as namespaceCreatedOp,xt as namespaceOfGroup,Js as nodeEndpoint,wi as nodeReleaseVersionFromImage,kn as normaliseAccount,ao as ownerOpDigest,co as ownerOpSigningPayload,Jn as parseAuthCallback,Ii as parseCreationWarrant,tr as parseDeviceCredential,Pi as parseGovernanceWarrant,go as parseWarrantNonce,Lr as persistedNonces,Hr as pinRelayNodeKey,Ur as presenceStatementBytes,zs as probeNodeHealth,Dl as readCloudLinkCallback,ji as readDelegatedCredential,Kr as readDelegatedSession,$l as readEnrolmentCallback,bn as readPinnedRelayNodeKey,B as readRelayMap,po as redeemInvitation,es as relayForContext,qe as relayTransportFetch,At as rememberGroupNamespace,ye as rememberRelay,ar as reportDataOf,Qn as requestBodyHash,As as resolveApplicationIdFromRegistry,En as resolveRelayFromInvitation,wn as resolveRelayNodeKey,Q as resolveRoot,Mt as resolveRootPair,Fs as rootGuardedOpBytes,Cn as routingProofHeaders,Fi as saveDelegatedCredential,qi as saveDelegatedSession,yt as selectLatestBundle,Qu as shouldRetain,Zn as signAccountHaClaim,et as signAccountLink,_t as signAccountLogin,Aa as signAccountOwnershipClaim,zt as signCreationWarrant,No as signDeviceCert,Oo as signDeviceScope,at as signGovernanceWarrant,Pn as signGroupInvitation,pn as signLoginStatement,Dn as signMemberJoinOp,js as signOwnerOpProof,kt as signRequest,Nr as signRequestProof,os as signRoutingChallenge,Wt as signWarrant,ol as signedPath,Ro as signerFromCryptoKey,Ce as signerFromSecret,$i as stateHash,Ue as subgroupCreation,an as subgroupVisibilitySetOp,Dt as subscribePresence,Zt as targetApplicationSetOp,Hs as teeAdmissionPolicyOp,Ls as teeAuthoringPolicyOp,qs as teeReleaseAdmissionPolicyOp,Gs as transferOwnershipOp,oi as transportKeyBinding,vi as trustSignedRelease,mr as trustedMeasurementsFromReleases,Ot as verifyDeviceCredential,bi as verifySignedNodeRelease,jn as withCap,Rt as withRetry,Vu as withoutCap};
1
+ function or(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function ir(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var _a=new Set(["token_reuse","token_revoked"]);function Ma(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var D=class extends Error{constructor(n,r,o,i,s){let a=Ma(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Po(this.headers),bodyText:this.bodyText}}},re=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function Po(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Ka(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var et=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:Po(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=this.buildUrl(e),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((A,C)=>{d[C]=A})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let A=n?.body;if(A!==void 0&&typeof A!="string"&&!(A instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:new URL(s).pathname,body:A}))}let m={method:l,headers:d},x=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!x||n?.body!==void 0&&x&&r===0)&&(m.body=n.body);let v;if(r>0&&o!==void 0){let A=n?.timeoutMs||this.transport.timeoutMs;if(A){let C=Date.now()-a,P=Math.max(0,A-C);v=this.createAbortSignal({...n,timeoutMs:P})}else v=this.createAbortSignal(n)}else v=c;if(v&&(m.signal=v),this.transport.credentials!==void 0&&(m.credentials=this.transport.credentials),n?.mode!==void 0&&(m.mode=n.mode),n?.cache!==void 0&&(m.cache=n.cache),n?.redirect!==void 0&&(m.redirect=n.redirect),n?.referrer!==void 0&&(m.referrer=n.referrer),n?.referrerPolicy!==void 0&&(m.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(m.integrity=n.integrity),n?.keepalive!==void 0&&(m.keepalive=n.keepalive),this.transport.getProof){let A=await this.transport.getProof({method:m.method??"GET",path:Ka(s),body:m.body});A&&(d["X-Calimero-Proof"]=A)}try{let A=await this.transport.fetch(s,m);if(!A.ok){let C=await this.getBodyText(A),P=new D(A.status,A.statusText,s,A.headers,C),T=A.headers.get("x-auth-error");if((A.status===401||A.status===403)&&T&&_a.has(T)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new re(T,A.status,A.statusText,s,A.headers,C)}let j=n?.signal?.aborted===!0;if(A.status===401&&this.transport.refreshToken&&T==="token_expired"&&r<1&&!x&&!j)try{let M=this.refreshTokenPromise;M||(M=this.transport.refreshToken(),this.refreshTokenPromise=M);let h=await M;if(!h||h.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let b=this.onTokenRefreshPromise;b||(b=this.transport.onTokenRefresh(h),this.onTokenRefreshPromise=b),await b,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let E=n?.timeoutMs||this.transport.timeoutMs;if(E&&o!==void 0){let O=Date.now()-a;if(E-O<=0)throw P}return this.makeRequest(e,n,r+1,a)}catch(M){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,M instanceof Error&&M.message.includes("onTokenRefresh")?M:P}throw P}return this.parseResponse(A,n?.parse)}catch(A){throw A instanceof D||A instanceof Error&&A.message.includes("onTokenRefresh")?A:new D(0,"Network Error",s,new Headers,A instanceof Error?A.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(ir(r)),n.length>0?or(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function tt(t){return new et(t)}function Ee(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return tt(e)}function Ot(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return tt(r)}function sr(t){return typeof window<"u"?Ee(t):Ot(t)}function Ga(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function $a(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function _t(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!Ga(r,n-o))throw r;let s=$a(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let m=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(m,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function La(t,e={}){return async(...n)=>_t(()=>t(...n),e)}function p(t){if(t===""||t==="."||t==="..")throw new TypeError(`invalid request path segment: ${JSON.stringify(t)}`);return encodeURIComponent(t)}var pe=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${p(e)}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${p(e)}/clients/${p(n)}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${p(e)}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${p(e)}/permissions`,{add:n.add,remove:n.remove})}};var nt=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function zd(t){let e=new nt;return new pe(e)}function Qd(t){let e=new nt;return new pe(e)}function Yd(t){let e=new nt;return new pe(e)}function To(t,e){return new pe(t)}var _={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},Zd={NONE:0,JOIN_ONLY:_.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:_.CAN_CREATE_CONTEXT|_.CAN_INVITE_MEMBERS|_.CAN_JOIN_OPEN_SUBGROUPS|_.CAN_CREATE_SUBGROUP|_.CAN_DELETE_SUBGROUP|_.CAN_MANAGE_VISIBILITY};function ep(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(_,n))e|=_[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function tp(t){return Object.keys(_).filter(e=>ge(t,_[e]))}function ge(t,e){let n=e>>>0;return(t&n)>>>0===n}function ar(t,e){return(t|e)>>>0}function np(t,e){return(t&~e)>>>0}var Ha={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function Ba(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function qa(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function cr(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function lr(t){let e=qa(t),n;return e!==void 0?n=Ba(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:Ha[n],message:cr(t)}}function ja(t){return t.status!=="failed"||!t.retryable}function sp(t){return!ja(t)}function Fa(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function Va(t,e){let{kind:n,status:r}=lr(t),o=Fa(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Do(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=cr(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=Va(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var Mt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function ur(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function No(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:ur(t,n,"highWaterNonce"),windowWidth:ur(t,n,"windowWidth")??0n},o=ur(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function w(t){return t?.data}function Wa(t,e){let[n,r]=Uo(t),[o,i]=Uo(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let m=0;m<c;m++){let x=Oo(s[m]??"0",a[m]??"0");if(x!==0)return x}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let m=0;m<l;m++){if(m>=u.length)return-1;if(m>=d.length)return 1;let x=Oo(u[m],d[m]);if(x!==0)return x}return 0}function Uo(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function Oo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function Ja(t,e,n){return _t(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var me=class{constructor(e){this.httpClient=e}async healthCheck(){return w(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return w(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return w(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await Ja(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>Wa(a,s))}async installDevApplication(e){return w(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return w(await this.httpClient.delete(`/admin-api/applications/${p(e)}`))}async listApplications(){return w(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}`))}async listApplicationVersions(e){return w(await this.httpClient.get(`/admin-api/applications/${p(e)}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return w(await this.httpClient.get(`/admin-api/applications/${p(e)}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${p(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${p(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return w(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return w(await this.httpClient.delete(`/admin-api/contexts/${p(e)}`))}async getContexts(){return w(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}`))}async getContextsForApplication(e){return w(await this.httpClient.get(`/admin-api/contexts/for-application/${p(e)}`))}async generateContextIdentity(){return w(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities`))}async getContextIdentitiesOwned(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/identities-owned`))}async joinContext(e){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/join`,{}))}async getContextGroup(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/group`))}async getContextStorage(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${p(e)}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${p(e)}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return w(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${p(e)}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${p(e)}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=w(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${p(e)}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:w(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${p(e)}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${p(e)}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/context/${p(e)}`,{}))}async lookupApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/application/${p(e)}`,{}))}async deleteContextAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/context/${p(e)}`,{}))}async deleteApplicationAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/application/${p(e)}`,{}))}async listContextAliases(){return w(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return w(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return w(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/lookup/device/${p(e)}`,{}))}async deleteDeviceAlias(e){return w(await this.httpClient.post(`/admin-api/alias/delete/device/${p(e)}`,{}))}async listDeviceAliases(){return w(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return w(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}`))}async getNodeIdentity(){return w(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/intents`,n))}async queryContext(e,n){return w(await this.httpClient.post(`/admin-api/contexts/${p(e)}/query`,n))}async getIntentRelay(e){return w(await this.httpClient.get(`/admin-api/contexts/${p(e)}/intents`))}async listNamespacesForApplication(e){return w(await this.httpClient.get(`/admin-api/namespaces/for-application/${p(e)}`))}async createNamespace(e){return w(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return w(await this.httpClient.request(`/admin-api/namespaces/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/invite`,n??{}))}async admitJoin(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return Do({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/groups`,n??{}))}async listNamespaceGroups(e){return w(await this.httpClient.get(`/admin-api/namespaces/${p(e)}/groups`))}async initAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return w(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/account/devices/${p(e)}/relink`,n??{}))}async rescopeAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(e)}/scope`,n))}async signWithAccountRoot(e){return w(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return w(await this.httpClient.put(`/admin-api/account/devices/${p(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/revoke`,n))}async linkAccountDevice(e,n){return w(await this.httpClient.post(`/admin-api/namespaces/${p(e)}/account/link-device`,n))}async getGroupInfo(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return w(await this.httpClient.request(`/admin-api/groups/${p(e)}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${p(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce/${p(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Mt(r,i):i}return No(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${p(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof D&&i.status===404?new Mt(r,i):i}return No(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${p(e)}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/accounts/${p(n)}/seal`,r))}async listGroupContexts(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/role`,r)}async getMemberCapabilities(e,n){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ge(n,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=ar(n,_.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ge(r,_.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=ar(r,_.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${p(e)}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${p(e)}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${p(e)}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/members/${p(n)}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${p(e)}/contexts/${p(n)}/metadata`))?.data??null}async syncGroup(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/sync`,{}))}async upgradeGroup(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade`,n))}async getGroupUpgradeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/upgrade/status`))}async getMigrationStatus(e){return this.httpClient.get(`/admin-api/groups/${p(e)}/migration-status`)}async getCascadeStatus(e){return w(await this.httpClient.get(`/admin-api/groups/${p(e)}/cascade-status`))}async retryGroupUpgrade(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${p(e)}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${p(e)}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${p(e)}/contexts/${p(n)}/remove`,{})}async createGroupInvitation(e,n){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/invite`,n??{}))}async joinGroup(e){return w(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return w(await this.httpClient.post(`/admin-api/groups/${p(e)}/join-via-inheritance`,{}))}async getTeeInfo(){return w(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return w(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return w(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return w(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${p(e)}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${p(e)}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${p(e)}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${p(e)}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${p(e)}/members/${p(n)}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${p(e)}/migration/abort`,{})}};function mp(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function wp(t){return new me(Ee(t))}function Ap(t){return new me(Ot(t))}function _o(t){return new me(sr(t))}function Kt(t,e){return new me(t)}function dr(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function pr(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}var Mo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function y(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function g(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function F(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function S(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function f(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function k(t,e){let n=[S(t.length),t];for(let r of e)n.push(S(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...n)))}async function oe(t){let e=g(t,"deviceSecret",32),n=f(Mo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function Ko(t,e,n){let r=await crypto.subtle.importKey("raw",g(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function ie(t){let e=g(t,"deviceSecret",32),n=f(Mo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var za=new TextEncoder().encode("calimero.auth.request.v1"),Qa=new TextEncoder().encode("calimero.auth.request.body.v1");function Go(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}async function gr(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k(Qa,[e])}async function Gt(t){let e=await oe(t.signerSecret),n=await gr(t.body),r=S(t.issuedAt),o=S(t.expiresAt),i=new TextEncoder,s=await k(za,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return y(f(Go(t.method),Go(t.path),n,r,o,a))}function $t(t){let e=F(t.credential,"credential"),n=F(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):f(new Uint8Array([1]),F(t.session,"session statement"));return y(f(e,r,n))}function Ya(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function Lt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return $t({credential:t.credential,session:t.session,request:await Gt({method:r.method,path:r.path,body:Ya(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Ht=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function mr(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Ht(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var rt=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await mr(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Xa=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function $o(t){return t.type!==void 0&&Xa.has(t.type)}var Za=new Set(["token_reuse","token_revoked"]),ec=new Set([401,403]),tc=1e4;function Lo(t){let e=t.headers.get("x-auth-error");return!e||!ec.has(t.status)?null:Za.has(e)?e:null}var B=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{$o(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n=await this.fetchImpl(e,{headers:{...await this.authorize({method:"GET",path:new URL(e).pathname}),Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=Lo(n),o=await n.text().catch(()=>{});throw r?new re(r,n.status,n.statusText,e,n.headers,o):new D(n.status,n.statusText,e,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let o=r instanceof Error?r:new Error(String(r));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof re)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
2
+ `);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),tc);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c=await this.fetchImpl(s,{method:"POST",headers:{...await this.authorize({method:"POST",path:new URL(s).pathname,body:a}),"Content-Type":"application/json"},body:a,signal:r.signal});if(!c.ok){let u=Lo(c),d=await c.text().catch(()=>{});return u?new re(u,c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d):new D(c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Bt=class Bt{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),Bt.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};Bt.MAX_BACKOFF_MS=3e4;var se=Bt;function ae(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var ot=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=ae()){await mr(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=ae()){return qt(this.sse,e,n,r)}};function qt(t,e,n,r=ae()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var nc=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Ho(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function ke(t,e="secret"){let n=g(t,e,32),r=f(nc,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=y(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw Ho(s)}return qo(o,i)}async function Bo(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")g(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=y(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return qo(t,n)}function qo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw Ho(r)}}}}async function I(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return ke(t,n);throw new Error(`${n} or signer is required`)}var rc=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),oc=6e4,jo=5*6e4,Fo=1024,Wo="mdma:enable-ha-namespace",Jo="mdma:enable-ha-namespace-as-account";function Vo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var fr=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function zo(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=Fo))throw new Error(`relayUrl must be a non-empty string of at most ${Fo} characters`);let o=t.ttlMs??oc;if(!(o>0&&o<=jo))throw new Error(`ttlMs must be in (0, ${jo}]`);let i=fr(t.namespaceId,"namespaceId"),s=fr(t.accountId,"accountId"),a=fr(t.salt,"salt"),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),x=>x.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),m=await c.sign(f(rc,l));return{kind:"account",credential:t.credential,signed_payload:Vo(l),signature:Vo(m)}}async function ic(t){if(!t.subject)throw new Error("subject must be the cloud login email");return zo(t,Wo,t.subject)}async function hr(t){return zo(t,Jo,void 0,t.relayUrl)}var sc=new TextEncoder().encode("calimero.device.cert.v1"),ac=new TextEncoder().encode("calimero.account.genesis.v1"),cc=new TextEncoder().encode("calimero.device.id.v1"),Ie=2,lc=237;async function yr(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=g(t,"account",32),r=await k(cc,[n,e]);return y(f(e,r.subarray(0,16)))}async function jt(t){return k(sc,[g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function Qo(t){return f(new Uint8Array([Ie]),t.rootPublicKey,R(0),g(t.account,"account",32),g(t.device,"device",32),g(t.signPublicKey,"signPublicKey",32),g(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function Yo(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await V(e.publicKey),o=0,i=await jt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=Qo({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return y(a)}function br(t){let e=g(t,"credential",lc);if(e[0]!==Ie)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ie} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>y(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function Ft(t){let e=br(t),n=await V(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=g(e.device,"device",32).subarray(0,16);if(await yr(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await Ko(e.rootPublicKey,g(e.signature,"signature",64),await jt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Vt(t){return V(y(await ie(t)))}async function V(t){return y(await k(ac,[f(new Uint8Array([Ie]),g(t,"rootPublicKey",32))]))}var uc=new TextEncoder().encode("calimero.device.scope.v1");async function wr(t){return k(uc,[g(t.account,"account",32),g(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>g(e,`applications[${n}]`,32))])}async function Xo(t){let e=await I(t.rootSecret,t.signer,"rootSecret"),n=g(e.publicKey,"signer.publicKey",32),r=await V(y(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await wr({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return y(f(new Uint8Array([Ie]),n,R(0),g(r,"account",32),g(t.device,"device",32),R(o.length),...o.map((u,d)=>g(u,`applications[${d}]`,32)),R(i),R(s),c))}var Ar=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var dc=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),pc=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Pe=256,Zo=Pe/32,xr=(Pe+Zo)/11;async function ei(){let t=crypto.getRandomValues(new Uint8Array(Pe/8));return si(y(t),await ci(t))}async function ti(t){let e=ai(t);return si(y(await li(e)),e.join(" "))}async function vr(t){return g(t,"secret",32),{secret:t,publicKey:y(await ie(t)),accountId:await Vt(t)}}async function ni(){let t=crypto.getRandomValues(new Uint8Array(Pe/8)),e=await ci(t);return{...await oi(t),phrase:e}}async function ri(t){return oi(await li(ai(t)))}async function oi(t){let e=await ke(y(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function Q(t){let e=typeof t=="string"?await ke(t,"rootSecret"):t;return ii(e)}async function Wt(t,e){return ii(await I(t,e,"rootSecret"))}async function ii(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function it(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(dc,new TextEncoder().encode(t.nonce)));return pi(n)}async function Jt(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await I(t.rootSecret,t.signer,"rootSecret")).sign(f(pc,new TextEncoder().encode(t.nonce)));return pi(n)}async function si(t,e){return{...await vr(t),phrase:e}}function ai(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==xr)throw new Error(`recovery phrase must be ${xr} words, got ${n}`);return e}async function ci(t){let e=di(t)+await ui(t),n=[];for(let r=0;r<xr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Ar[o])}return n.join(" ")}async function li(t){let e="";for(let r of t){let o=Ar.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Pe/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(Pe)!==await ui(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function ui(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return di(e).slice(0,Zo)}function di(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function pi(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var gc=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),zt=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),mc=568;function fc(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function Rr(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function hc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function yc(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function Qt(t){let e=await crypto.subtle.digest("SHA-256",fc(gc,new Uint8Array(32),t));return new Uint8Array(e)}function Cr(t){let e=t.length>=zt.length&&Rr(t.subarray(0,zt.length),zt),n=e?zt.length:mc;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function Yt(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:y(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let m=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${m?`: ${m}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=yc(a.boundPublicKey,"boundPublicKey"),u=hc(a.quoteB64),{reportData:d,mock:l}=Cr(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:y(e),reportDataSuffix:y(await Qt(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!Rr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!Rr(d.subarray(32,64),await Qt(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:y(c),mock:l}}var bc="Noise_NK_25519_AESGCM_SHA256",Sr=32,wc=16,Ac=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),kr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(bc),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await xc(f(this.h,e))}async mixKey(e){let[n,r]=await mi(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:gi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:gi(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return mi(this.ck,new Uint8Array)}};async function fi(t,e,n){let r=await kr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Te(n);return await r.mixHash(o.publicKey),await r.mixKey(await st(o.privateKey,t)),{message1:f(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<Sr+wc)throw new Error("Noise: message 2 is too short");let a=s.slice(0,Sr);return await r.mixHash(a),await r.mixKey(await st(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(Sr)),split:await r.split()}}}}async function Te(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",f(Ac,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:vc(n.x)}}async function st(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function gi(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function xc(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function Er(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function mi(t,e){let n=await Er(t,e),r=await Er(n,new Uint8Array([1])),o=await Er(n,f(r,new Uint8Array([2])));return[r,o]}function vc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var wi="/sealed/v2/handshake",Ai="/sealed/v2",ct="application/vnd.calimero.sealed",Ir=2,Rc=new TextEncoder().encode("calimero/sealed-http/v2"),at=16,Cc=1+at+8,Sc=0,Ec=1,kc=2,Ic=1+64*1024+16,Pc=1024,Tc=6e4,Dc="calimero.tee-attest.transport-key.v1",Nc=[101,204,205,304],xi=new TextEncoder,lt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},De=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function vi(t,e){let n=await crypto.subtle.digest("SHA-256",f(xi.encode(Dc),t,e));return new Uint8Array(n)}async function Ri(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=y(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=g(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?g(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=y(await vi(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function fe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return Ci({baseUrl:t.baseUrl,transportPublicKey:()=>Ri(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Ci(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,m)=>fetch(l,m)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await yi(o,r,await hi(s))}catch(l){if(!(l instanceof lt)||!i)throw l;return s=Promise.resolve().then(i),yi(o,r,await hi(s))}},u=async()=>{let l=a??d(void 0),m=await l;if(Date.now()<m.renewAt)return[m,l];let x=d(l);return[await x,x]},d=l=>{if(a===l){let m=c();a=m,m.catch(()=>{a===m&&(a=void 0)})}return a};return async(l,m)=>{let x=new Request(l,m),v=new URL(x.url);if(v.origin!==e.origin||!v.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${v.href} outside the sealed node at ${t.baseUrl}`);let A=[];x.headers.forEach((h,b)=>A.push([b,h]));let C={method:x.method,path:v.pathname.slice(n.length)+v.search,headers:A},P=new Uint8Array(await x.arrayBuffer()),T=async h=>{let{requestId:b,header:E,envelope:O}=await Oc(h,C,P),H=await o(`${r}${Ai}`,{method:"POST",headers:{"content-type":ct},body:O,signal:x.signal});if(H.headers.get("content-type")!==ct)throw await Ei(H);return Mc(H,h.responseKey,E,b)},[j,M]=await u();try{return await T(j)}catch(h){if(!(h instanceof De)||h.code!=="unknown_session")throw h;return T(await d(M))}}}async function hi(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function yi(t,e,n){try{return await bi(t,e,n)}catch(r){if(!(r instanceof De)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),bi(t,e,n)}}async function bi(t,e,n){let r=await fi(n,Rc),o=await t(`${e}${wi}`,{method:"POST",headers:{"content-type":ct},body:f(new Uint8Array([Ir]),n,r.message1)});if(o.headers.get("content-type")!==ct)throw await Ei(o);let i=await Gc(o,Pc);return Uc(r,i)}async function Uc(t,e){if(e[0]!==Ir)throw new Error("The handshake reply is malformed");let n;try{n=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:r,split:o}=n;if(r.length!==at+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,at),s=new DataView(r.buffer,r.byteOffset).getUint32(at,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-Tc,header(u){let d=new Uint8Array(Cc);return d[0]=Ir,d.set(i,1),new DataView(d.buffer).setBigUint64(1+at,BigInt(u),!1),d}}}async function Oc(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Si(r,0),additionalData:o},t.requestKey,_c(e,n));return{requestId:r,header:o,envelope:f(o,new Uint8Array(i))}}function Si(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function _c(t,e){let n=xi.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),f(r,n,e)}async function Mc(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Kc(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Si(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==Sc)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Nc.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===Ec?d.enqueue(l.data):l.kind===kc?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function Kc(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=f(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Ic)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function Gc(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=f(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Ei(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new lt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new De(t.status,e,n,o)}var $c=/^[0-9a-f]{96}$/,Lc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function dt(t){let e=Ne(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return Lc.map(d=>Ne([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ne(t.allowedRtmr0??[],"allowedRtmr0"),Ne(t.allowedRtmr1??[],"allowedRtmr1"),Ne(t.allowedRtmr2??[],"allowedRtmr2"),Ne(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=Bc(a),m=d??await t.fetchCollateral?.(l);if(!m)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let x;try{x=t.dcapVerify(l,m,Math.floor(i()/1e3))}catch(P){throw new Error(`The quote did not verify: ${P?.message??String(P)}`)}if(x.status==="Revoked"||!o.includes(x.status))throw new Error(`The platform's TCB status is ${x.status}, which is not accepted`);let v=Hc(x.report);if(v.tdAttributes?.length!==8||(v.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let A=[v.mrTd,v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].map(P=>y(P));if(n.length>0&&!n.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([v.rtMr0,v.rtMr1,v.rtMr2,v.rtMr3].forEach((P,T)=>{let j=r[T];if(j.length>0&&!j.includes(y(P)))throw new Error(`RTMR${T} ${y(P)} is not one this verifier trusts`)}),y(v.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Ne(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!$c.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Hc(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function Bc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var qc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],ut="locked-read-only";function Pr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==ut&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(ut)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>jc(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function jc(t,e){let n=qc.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var ki=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],Ii=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Fc="1.2.840.10045.2.1",Vc={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Wc={"P-256":32,"P-384":48},Jc={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Pi(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function Oe(t){let e=Pi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function K(t){let e=[];for(let n=t.start;n<t.end;){let r=Pi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function U(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ce(t){return t.bytes.slice(t.start,t.end)}function Xt(t){return t.bytes.slice(t.offset,t.end)}function Ue(t){let e=ce(U(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function zc(t){let e=new TextDecoder().decode(ce(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function Tr(t){try{let[e,n,r,...o]=K(U(Oe(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=K(U(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,m,...x]=i.slice(s);U(a,2,"The serial number");let v=Ue(K(U(n,48,"The signature algorithm"))[0]);if(Ue(K(U(c,48,"The signature algorithm"))[0])!==v)throw new Error("it names two different signature algorithms");let C=Jc[v];if(!C)throw new Error(`it is signed with ${v}, not ECDSA with SHA-256 or SHA-384`);let[P,T]=K(U(d,48,"The validity")).map(zc);if(T===void 0)throw new Error("its validity is incomplete");let[j,M]=K(U(m,48,"The public key"));U(M,3,"The public key");let[h,b]=K(U(j,48,"The key algorithm"));if(Ue(h)!==Fc)throw new Error("its key is not an elliptic-curve key");let E=Vc[Ue(b)];if(!E)throw new Error("its key is on a curve other than P-256 or P-384");let O=new Map,H=x.find(te=>te.tag===163);if(H){let[te]=K(H);for(let ne of K(U(te,48,"The extensions"))){let Se=K(U(ne,48,"An extension"));if(Se.length===3)U(Se[1],1,"An extension's critical flag");else if(Se.length!==2)throw new Error("it has a malformed extension");let rr=Ue(Se[0]);if(O.has(rr))throw new Error(`it has extension ${rr} twice`);O.set(rr,ce(U(Se[Se.length-1],4,"An extension value")))}}let ee=ce(U(r,3,"The signature"));if(ee[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:Xt(e),signatureHash:C,signature:ee.slice(1),issuer:Xt(U(u,48,"The issuer")),subject:Xt(U(l,48,"The subject")),notBefore:P,notAfter:T,spki:Xt(m),curve:E,extensions:O}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Ti(t){return K(U(Oe(t),48,"The list")).map(Ue)}function Qc(t,e){let n=Wc[e],r=K(U(Oe(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ce(U(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function Zt(t,e,n,r,o){let i;try{i=Qc(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function W(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function Dr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return W(n[0][1],e)}var Yc="2.5.29.17",Xc="2.5.29.37",Zc="1.3.6.1.5.5.7.3.3",el="1.3.6.1.4.1.57264.1.8",tl="1.3.6.1.4.1.57264.1.1",nl=134,rl=12,ol=48,il=new TextEncoder,_e=t=>new TextDecoder().decode(t);async function en(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=ll(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=W(o,"The bundle signature"),u=Dr(_e(W(i,"The bundle certificate")),"The bundle certificate"),d=Tr(u),l=Ii.find(T=>T.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let m=il.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Zt(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(s.SignedEntryTimestamp,"The signed entry timestamp"),m))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let v=a.integratedTime*1e3;if(!Ui(v,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${pt(v)}, when the entry says it was logged`);let A=ul(a.body),C=y(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(A.hash!==C)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!Nr(W(A.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let P=Dr(_e(W(A.publicKey,"The logged certificate")),"The logged certificate");if(!Nr(P,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Zt(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await sl(d,v),cl(d,n),{integratedTime:a.integratedTime}}async function sl(t,e){if(!Ni(t,e))throw new Error(`The signing certificate was valid ${pt(t.notBefore)} to ${pt(t.notAfter)}, not at ${pt(e)} when Rekor logged it`);let n=[];for(let r of ki){let o=r.certChain.map(s=>Tr(W(s,"A Fulcio certificate")));if(!await Di(t,o[0]))continue;let i=await al(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${pt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function al(t,e,n){if(!Ui(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!Ni(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await Di(o,i))return`its certificate ${r} is not signed by the next`}}async function Di(t,e){return Nr(t.issuer,e.subject)?Zt(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function cl(t,e){let n=t.extensions.get(Yc);if(!n)throw new Error("The signing certificate names no identity");let r=K(U(Oe(n),ol,"The subject alternative name")),o=r.filter(u=>u.tag===nl).map(u=>_e(ce(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(el),s=t.extensions.get(tl),a=i?_e(ce(U(Oe(i),rl,"The OIDC issuer"))):s?_e(s):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(Xc);if(!c||!Ti(c).includes(Zc))throw new Error("The signing certificate is not for code signing")}function ll(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function ul(t){let e;try{e=JSON.parse(_e(W(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function Ni(t,e){return t.notBefore<=e&&e<=t.notAfter}function Ui(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function pt(t){return new Date(t).toISOString()}function Nr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Ur=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),dl=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],tn="https://cloud.calimero.network";async function _i(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await en(r,e,{identity:n.identity??Ur.identity,issuer:n.issuer??Ur.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>dl.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function nn(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Mi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function rn(t,e={}){let n=await Gi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${Ki(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function Ki(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Gi(t,e){let n=Ki(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return Mi(o)}function on(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${gt(e,"version")}`}async function $i(t){let e=gt(t.minReleaseVersion,"minReleaseVersion"),n=gt(t.release?.version,"The release version"),r=await _i(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(gl(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return Pr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function sn(t){return gt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await $i({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return dt({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function pl(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&gt(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return fe({baseUrl:e,verify:sn({...a,release:async()=>{let d=r===void 0?await rn(e,{fetch:c}):await Gi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):nn(on(n??tn,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Li=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function gt(t,e){let n=typeof t=="string"?Li.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function gl(t,e){let[n,r]=Oi(t),[o,i]=Oi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,m]=[/^\d+$/.test(u),/^\d+$/.test(d)],x=l&&m?Math.sign(Number(u)-Number(d)):l!==m?l?-1:1:u<d?-1:u>d?1:0;if(x!==0)return x}return 0}function Oi(t){let e=Li.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var ml=new TextEncoder().encode("calimero.warrant.v2"),fl=new TextEncoder().encode("calimero.warrant.intent.v1"),Hi=64,Bi=256;async function Or(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(fl,[new TextEncoder().encode(t),n])}async function an(t){let e=g(t.context,"context",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=g(t.releaseBytecodeId,"releaseBytecodeId",32),s=_r(t.releaseVersion??""),a=le(t.accountHeads,"accountHeads"),c=le(t.governanceFloor,"governanceFloor"),u=await I(t.deviceSecret,t.signer,"deviceSecret"),d=g(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),m=await Or(t.method,t.argsJson),x=S(t.nonce),v=S(t.notAfter),A=await k(ml,[e,n,d,r,o,i,s,l,m,S(a.length),...a,S(c.length),...c,x,v]),C=mt(await u.sign(A));return y(f(e,n,d,r,o,i,R(s.length),s,R(l.length),l,m,R(a.length),...a,R(c.length),...c,x,v,C))}function mt(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function _r(t){let e=new TextEncoder().encode(t);return hl(e.length),e}function hl(t){if(t>Bi)throw new Error(`releaseVersion is ${t} bytes, over the ${Bi} a node accepts`)}function le(t,e){let n=t??[];if(n.length>Hi)throw new Error(`${e} cites ${n.length} heads, over the ${Hi} a node accepts`);return n.map((r,o)=>g(r,`${e}[${o}]`,32))}var yl=new TextEncoder().encode("calimero.context-creation-warrant.v1"),bl=new TextEncoder().encode("calimero.context-creation.init.v1"),cn=256;async function Mr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(bl,[e])}async function wl(t){return k(yl,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function ln(t){let e=g(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):g(t.seed,"seed",32),r=g(t.authorAccount,"authorAccount",32),o=g(t.executor,"executor",32),i=g(t.executorKey,"executorKey",32),s=g(t.applicationId,"applicationId",32),a=qi(t.serviceName,"serviceName"),c=qi(t.name,"name"),u=le(t.accountHeads,"accountHeads"),d=le(t.governanceFloor,"governanceFloor"),l=await I(t.deviceSecret,t.signer,"deviceSecret"),m=g(l.publicKey,"signer.publicKey",32),x=await Mr(t.initArgs),v=await wl({group:e,seed:n,authorAccount:r,deviceKey:m,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:x,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),A=mt(await l.sign(v));return{warrant:y(f(e,n,r,m,o,i,s,ji(a),ji(c),x,R(u.length),...u,R(d.length),...d,S(t.nonce),S(t.notAfter),A)),seed:y(n)}}function Fi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,m)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${m} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let m=i(1,l)[0];if(m===0)return null;if(m!==1)throw new Error(`${l} has option tag ${m}, expected 0 or 1`);let x=s(l);if(x>cn)throw new Error(`${l} is ${x} bytes, over the ${cn} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(x,l))},u=l=>{let m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>y(i(32,l)))},d={group:y(i(32,"group")),seed:y(i(32,"seed")),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),applicationId:y(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function qi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>cn)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${cn} a node accepts`);return n}function ji(t){return t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t)}var Al=new TextEncoder().encode("calimero.governance-warrant.v1"),xl=new TextEncoder().encode("calimero.governance-warrant.op.v1"),vl={group:0,root:1};async function Kr(t){return k(xl,[new Uint8Array([Gr(t.kind)]),t.bytes])}async function Rl(t){return k(Al,[t.scope,new Uint8Array([Gr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,S(t.accountHeads.length),...t.accountHeads,S(t.governanceFloor.length),...t.governanceFloor,S(t.nonce),S(t.notAfter)])}async function ft(t){let e=g(t.scope,"scope",32),n=g(t.authorAccount,"authorAccount",32),r=g(t.executor,"executor",32),o=g(t.executorKey,"executorKey",32),i=le(t.accountHeads,"accountHeads"),s=le(t.governanceFloor,"governanceFloor"),a=Gr(t.op.kind),c=await I(t.deviceSecret,t.signer,"deviceSecret"),u=g(c.publicKey,"signer.publicKey",32),d=await Kr(t.op),l=await Rl({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),m=mt(await c.sign(l));return y(f(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,S(t.nonce),S(t.notAfter),m))}function Vi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,m)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${m} (${n.length} bytes)`);let x=n.subarray(o,o+l);return o+=l,x},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let m=s(l);if(m>64)throw new Error(`${l} cites ${m} heads, over the 64 a node accepts`);return Array.from({length:m},()=>y(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:y(i(32,"scope")),kind:u(),authorAccount:y(i(32,"authorAccount")),deviceKey:y(i(32,"deviceKey")),executor:y(i(32,"executor")),executorKey:y(i(32,"executorKey")),opHash:y(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:y(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Gr(t){let e=vl[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Cl={Admin:0,Member:1,ReadOnly:2},G={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},ht={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Sl=new TextEncoder().encode("calimero.namespace.id.v1"),Lr=new Uint8Array(32),un=R(0);function Ji(t){let e=Cl[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function N(t){return new Uint8Array([t])}function Me(t,e){return{kind:"group",bytes:f(N(G.MemberAdded),g(t,"member",32),Ji(e))}}function dn(t){return{kind:"group",bytes:f(N(G.MemberRemoved),g(t,"member",32),Lr,un)}}function yt(t){return{kind:"group",bytes:f(N(G.MemberLeft),g(t,"member",32),Lr,un)}}function pn(t,e){return{kind:"group",bytes:f(N(G.MemberRoleSet),g(t,"member",32),Ji(e))}}var El=new TextEncoder().encode("calimero.subgroup.id.v1");async function Hr(t,e,n,r){return y(await k(El,[g(t,"admin",32),g(e,"parentId",32),new Uint8Array([n?1:0]),g(r,"salt",32)]))}function Wi(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return f(R(n.length),n)}function gn(t){return{kind:"group",bytes:f(N(G.TargetApplicationSet),Lr,g(t.applicationId,"applicationId",32),Wi(t.package,"package"),Wi(t.version,"version"))}}function Ke(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:f(N(G.DefaultCapabilitiesSet),R(t))}}function Br(t){return{kind:"root",bytes:f(N(ht.GroupCreated),g(t.groupId,"groupId",32),g(t.parentId,"parentId",32),N(t.restricted?1:0),g(t.admin,"admin",32),g(t.salt,"salt",32))}}async function Ge(t){let e=t.salt??y(crypto.getRandomValues(new Uint8Array(32))),n=await Hr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Br({...t,groupId:n,salt:e})}}function mn(t,e){return{kind:"root",bytes:f(N(ht.GroupReparented),g(t,"childGroupId",32),g(e,"newParentId",32))}}function fn(t){return{kind:"root",bytes:f(N(ht.GroupDeleted),g(t,"rootGroupId",32),un,un)}}async function hn(t,e){return y(await k(Sl,[g(t,"founder",32),g(e,"salt",32)]))}function yn(t){let e=F(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:f(N(ht.NamespaceCreatedV2),g(t.founder,"founder",32),e,g(t.salt,"salt",32))}}function $r(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function qr(t){return t===void 0?N(0):f(N(1),$r(t))}function jr(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return f(R(n.length),...n.flatMap(([,r,o])=>[$r(o),$r(r)]))}function kl(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ge(t,_.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function bn(t,e){return{kind:"group",bytes:f(N(G.MemberCapabilitySet),g(t,"member",32),R(kl(e,"capabilities")))}}function wn(t){return{kind:"group",bytes:f(N(G.ContextDetached),g(t,"contextId",32))}}function An(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:f(N(G.SubgroupVisibilitySet),N(t==="open"?0:1))}}function $e(t={}){return{kind:"group",bytes:f(N(G.GroupMetadataSet),qr(t.name),jr(t.data))}}function xn(t,e={}){return{kind:"group",bytes:f(N(G.MemberMetadataSet),g(t,"member",32),qr(e.name),jr(e.data))}}function vn(t,e={}){return{kind:"group",bytes:f(N(G.ContextMetadataSet),g(t,"contextId",32),qr(e.name),jr(e.data))}}function zi(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return N(t)}function Qi(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityGranted),g(t,"contextId",32),g(e,"member",32),zi(n))}}function Yi(t,e,n){return{kind:"group",bytes:f(N(G.ContextCapabilityRevoked),g(t,"contextId",32),g(e,"member",32),zi(n))}}function Rn(t){return{kind:"root",bytes:f(N(ht.MemberJoinedOpen),g(t.member,"member",32),g(t.groupId,"groupId",32),F(t.credential,"credential"))}}var Cn=300,he=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},Il=t=>new Promise(e=>setTimeout(e,t));function Pl(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var J=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return I(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${p(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=y(g(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";_r(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Cn,l=await an({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),m=await this.json("POST",`/admin-api/contexts/${p(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:m.data.rootHash,returns:m.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${p(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${p(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new he(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??Cn,{warrant:c}=await ln({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${p(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${p(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new he(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??Cn,a=await ft({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?y(g(e.salt,"salt",32)):y(crypto.getRandomValues(new Uint8Array(32))),o=await hn(this.config.authorAccount,r),i=yn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:Ke(e.defaultCapabilities),a=e.application?gn(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??Cn,l=await ft({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),m=await this.postGovernance(o,i,l),x={namespaceId:m.groupId,salt:r,teeEnabled:m.teeEnabled??!1,...m.teeError?{teeError:m.teeError}:{}},v=x,A=C=>C instanceof Error?C.message:String(C);if(a)try{await this.govern({groupId:x.namespaceId,op:a}),v={...v,applicationSet:!0}}catch(C){v={...v,applicationSet:!1,applicationError:A(C)}}if(s)try{await this.govern({groupId:x.namespaceId,op:s}),v={...v,defaultCapabilitiesSet:!0}}catch(C){v={...v,defaultCapabilitiesSet:!1,defaultCapabilitiesError:A(C)}}return v}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${p(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:y(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:y(g(e.executorAccount??"","the relay's executorAccount",32)),executorKey:y(g(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof D&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=Pl(s.headers);await Il(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Tl(c);throw new he(u,/nonce/i.test(u),a.status)}throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Tl(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var ye=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Dl=new TextEncoder().encode("calimero.auth.login.v1"),Xi={webOrigin:0,codeSigningId:1,cli:2};function Zi(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Nl(t){return f(Uint8Array.from([Xi[t.kind]]),Zi(t))}function Ul(t){let e=Uint8Array.from([Xi[t.kind]]);if(t.kind==="cli")return e;let n=Zi(t);return f(e,R(n.length),n)}async function Sn(t){let e=g(t.node,"node",32),n=g(t.challenge,"challenge",32),r=g(t.sessionKey,"sessionKey",32),o=await I(t.deviceSecret,t.signer,"deviceSecret"),i=g(o.publicKey,"signer.publicKey",32),s=S(t.issuedAt),a=S(t.expiresAt),c=await k(Dl,[e,Nl(t.audience),n,r,i,s,a]),u=await o.sign(c);return y(f(e,Ul(t.audience),n,r,i,s,a,u))}var Ol=300;async function Fr(){let t=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await ie(t)),secret:t}}async function Le(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(m,x)=>{let v=new AbortController,A=setTimeout(()=>v.abort(),n),C;try{let T={...x,signal:v.signal};C=t.fetch?await t.fetch(`${e}${m}`,T):await globalThis.fetch(`${e}${m}`,T)}catch(T){throw new D(0,T instanceof Error?T.name:"NetworkError",`${e}${m}`,new Headers,T instanceof Error?T.message:String(T))}finally{clearTimeout(A)}let P=await C.text().catch(()=>"");if(!C.ok)throw new D(C.status,C.statusText,`${e}${m}`,C.headers,P);return P?JSON.parse(P):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await Fr(),a=Math.floor(Date.now()/1e3),c=await Sn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??Ol),signer:await I(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var _l=3e4;function Be(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Ml(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var He=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-_l>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Le({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=Ml(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new se({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var Y=t=>new TextEncoder().encode(t),Kl=Y("calimero.auth.request.v1"),Gl=Y("calimero.auth.request.body.v1"),Vr="X-Calimero-Proof",$l=300;async function Wr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);if(n.includes("?"))throw new Error(`the path must carry no query string, got ${JSON.stringify(n)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`);let o=t.body===void 0?new Uint8Array:typeof t.body=="string"?Y(t.body):t.body,i=await k(Gl,[o]),s=Math.floor(t.now??Date.now()/1e3),a=s+(t.validForSeconds??$l),c=await k(Kl,[Y(e),Y(n),i,S(s),S(a)]),u=await Ll(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=f(R(Y(e).length),Y(e),R(Y(n).length),Y(n),i,S(s),S(a),u),l=Hl(r,"credential");return y(f(l,new Uint8Array([0]),d))}async function Ll(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await oe(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Hl(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return g(n,e,n.length/2)}function Jr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await Wr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Vr]:o}}}function Bl(t){return new URL(t).pathname}var es=new TextEncoder().encode("calimero/presence/1");async function ts(t){let e=t===null?new Uint8Array([0]):f(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function zr(t){return f(es,g(t.contextId,"contextId",32),g(t.author,"author",32),S(t.seq),S(t.sentAtMs),await ts(t.state))}var ql=2500,bt=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??ql,this.now=e.now??Date.now}async set(e,n,r=ae()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=ae()){return qt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await zr({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=y(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:y(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function ns(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function rs(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function jl(t,e,n){let r=e?.nodeKey;return r?new He({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Be(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var be=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof J?e.relay:new J({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=jl(i,e.observe,o),this.rpcTransport=new ye(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Jr(e.proof)),e.session){let s=e.session;this.relayAdmin=_o({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=Kt(tt({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new qe(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw ns("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof ye))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new B({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw rs("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):rs("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new bt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw ns("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function En(t){return new be(t)}var Xr="calimero.delegated.connection",Zr="calimero.delegated.credential";function eo(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Xr);return t?JSON.parse(t):null}catch{return null}}function is(t){try{sessionStorage.setItem(Xr,JSON.stringify(t))}catch{}}function ss(){try{sessionStorage.removeItem(Xr)}catch{}}function as(){let t=eo();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(Zr);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function cs(t){try{sessionStorage.setItem(Zr,JSON.stringify(t))}catch{}}function ls(){try{sessionStorage.removeItem(Zr)}catch{}}function to(t){let e=In(t);return{next:async()=>{let n=0n;try{n=us(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function In(t){return`calimero.nonce.${t}`}function us(t){let e=localStorage.getItem(In(t));if(e!==null)return BigInt(e);let n=`${In(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function Tn(t,e,n){try{us(t)<=n&&localStorage.setItem(In(t),String(n+1n))}catch{}}var ds="calimero.delegated.relay-node-key.";function X(t){return t.replace(/\/+$/,"")}function no(t,e){localStorage.setItem(ds+X(t),e.trim().toLowerCase())}function Dn(t){try{let e=localStorage.getItem(ds+X(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function ro(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Fl="locked-read-only",Vl="2.3.99",Qr;function Wl(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var je=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function os(t,e){try{return await e()}catch(n){throw n instanceof je?n:new je(t,n)}}function Jl(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new je(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function ps(t,e){return Object.assign(async r=>{let o=await os("loading the quote verifier",()=>(Qr??(Qr=import("@phala/dcap-qvl").then(i=>Wl(i),i=>{throw Qr=void 0,i})),Qr));return sn({dcapVerify:o,release:()=>os("fetching the release the relay runs",async()=>nn(on(tn,await rn(t,{fetch:e})))),profile:Fl,minReleaseVersion:Vl})(r)},{includeCollateral:!0})}async function Fe(t,e={}){let n=e.fresh?null:Dn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=Jl(r);try{let i=ro(t),{nodeKey:s}=await Yt({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:ps(t,o)}});return no(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof je||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function Nn(t){let e=await Fe(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var Pn=[1e3,2e3,5e3,1e4,3e4];function zl(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function gs(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await Fe(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=Pn[Math.min(r,Pn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await zl(i,n)}return null}function Ql(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var Yr=new Map;function ms(){Yr.clear()}async function Yl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function Xl(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function Zl(t){let e=(o,i)=>globalThis.fetch(o,i),n=fe({baseUrl:t,verify:ps(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&Xl(s))return e(s);let a=await n(s.clone());return await Yl(a)?(r||(r=!0,console.warn(`[mero-js] ${X(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function Ve(t){if(ro(t))return;let e=X(t),n=Yr.get(e);return n||(n=Zl(t),Yr.set(e,n)),n}function eu(t,e){let n=null,r=null;return async()=>{let o=n?Ql(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Le({nodeUrl:t.relayUrl,fetch:Ve(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Be()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var kn=new Map;function fs(){kn.clear()}function tu(t){return typeof t=="object"&&t!==null&&t.status===409}function nu(t,e){let n=t.rpc,r=X(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(kn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return kn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){tu(a)&&kn.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function ru(t){return new B({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function ou(t,e){let n=e.session?nu(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=ru(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function Un(t,e){if(!t.relayUrl)return null;let n=Dn(t.relayUrl),r=En({transport:"relay",fetch:Ve(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:to(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?eu({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ou(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||ro(t.relayUrl)})}var hs="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(hs+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function oo(t,e){try{localStorage.setItem(hs+t,JSON.stringify(e))}catch{}}function we(t,e,n){let r=q(t),o=X(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),oo(t,r)}function ys(t,e){return q(t).contexts[e]??null}function On(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||X(t.relayUrl)!==X(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function We(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(X);return[...new Set(n)]}async function bs(t){let e=[],n=q(t.account);for(let r of We(t))try{if(!await Nn(r))continue;let o=Un({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return oo(t.account,n),e}async function ws(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of We(t))try{if(!await Nn(s))continue;let a=Un({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return oo(t.account,r),e}function Mn(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function wt(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}function iu(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var _n=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function su(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Mn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new _n(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(m=>m.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function As(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=cu(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=io(i);if(!s)throw new Error(lu(o,i));let a=new J({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??uu(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?fe({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new be({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function au(t){let{root:e,authorAccount:n,...r}=t,o=await I(r.deviceSecret,r.signer,"deviceSecret"),i=await Q(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return As({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function cu(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function lu(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function uu(t){let e=`mero-js:warrant-nonce:${t}`;try{return wt(e)}catch{return Mn(1)}}var du=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function xs(t,e){g(e,"deviceSecret",32);let n=await oe(e),r=f(du,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return pu(o)}async function Kn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await xs(t.nonce,e.deviceSecret)}}function pu(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var vs="calimero.cloud.link.pending",so="link_state";var ao=/^[0-9a-f]{64}$/;function Rs(t){try{let e=localStorage.getItem(vs),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function Cs(t){try{localStorage.setItem(vs,JSON.stringify(t))}catch{}}function Gn(t,e){if(!ao.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=Rs(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},Cs(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(so,s),n.toString()}function Je(t){let e=new URLSearchParams(t).get(so),n=Rs(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],Cs(n),r}function Ss(t){let e=new URLSearchParams(t);e.delete(so);let n=e.toString();return n?`?${n}`:""}var gu="https://cloud.calimero.network";function Es(t){let e=new URL(t.cloudWebUrl??gu);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Gn(t.accountId,t.returnTo)),e.toString()}function mu(t){throw window.location.assign(Es(t)),new Error("redirecting to the cloud to authorise this link")}function fu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Je(t.search??""),co(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;if(Je(t.search??"")?.account!==o)throw co(),new Error("this account link answers a request this browser did not make - start the link again from here");return co(),{grant:r,account:o}}function co(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+Ss(location.search))}async function hu(t){let e=await Q(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var yu="enrol-device",bu="enrol-kem",wu="callback-url",Au="state";function Ps(t){Is(t.devicePublicKey,"devicePublicKey"),Is(t.kemPublicKey,"kemPublicKey"),Su(t.returnTo),Cu(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(yu,t.devicePublicKey),e.searchParams.set(bu,t.kemPublicKey),e.searchParams.set(wu,t.returnTo),t.state&&e.searchParams.set(Au,t.state),e.toString()}function xu(t){throw window.location.assign(Ps(t)),new Error("redirecting to the wallet to approve this device")}function vu(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw ks(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;ks();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function ks(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Ru(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Ft(t.credential);if(e.signPublicKey!==Ae(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${Ae(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==Ae(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==Ae(t.account))throw new Error(`the wallet reported account ${Ae(t.account)}, but the credential names ${e.account}`);if(e.device!==Ae(t.device))throw new Error(`the wallet reported device ${Ae(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Is(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function Ae(t){return t.trim().toLowerCase()}function Ts(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Cu(t){Ts(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Su(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function $n(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function ku(t,e){if(e.size===0)return!0;let n=$n(t.account);return n!==null&&e.has(n)}async function Ln(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let m=await e.getNamespaceRouting(t.namespaceId);n=m.nodes,r=m.servable}catch(m){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${m instanceof Error?m.message:String(m)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map($n).filter(m=>m!==null)),i=n.filter(m=>ku(m,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(m=>m.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(m=>typeof m.relayUrl=="string"&&m.relayUrl.length>0),[d]=u;if(d===void 0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let l=u.find(m=>m.canExecute)??u.find(m=>m.fresh)??d;return{ok:!0,relayUrl:l.relayUrl,admitUrl:l.admitUrl??`${l.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${p(t.namespaceId)}/admit`,admitterAccount:l.account,peerId:l.peerId,writable:l.canExecute,stale:!l.fresh||c}}var Hn=1440*60,uo={Admin:0,Member:1,ReadOnly:2};function Ct(t){let e=t.admitters??[];return f(lo(t.inviter_identity,"inviter_identity"),lo(t.group_id,"group_id"),S(t.expiration_timestamp),lo(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>g(n,`admitters[${r}]`,32)))}async function po(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",Ct(t)))}function go(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Bn(t){let e=await I(t.deviceSecret,t.signer,"deviceSecret"),n=g(e.publicKey,"signer.publicKey",32),r=g(t.groupId,"groupId",32);g(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(m=>m.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=go(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((m,x)=>g(m,`admitters[${x}]`,32));let i=t.invitedRole??uo.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??Hn,Hn);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await po(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:y(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(g(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(g(t.appKey,"appKey",32))),l}function lo(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var mo=24,Iu=new TextEncoder().encode("calimero.namespace.v1"),Pu=0,Ds={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Ns(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return f(new Uint8Array([1]),new Uint8Array(t))}function Us(t){let e=new TextEncoder().encode(t);return f(R(e.length),e)}function qn(t){let e=t.invitation,n=t.admitter_addrs??[];return f(Ct(e),Us(t.inviter_signature),t.inviter_account?f(new Uint8Array([1]),g(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(Us),Ns(t.application_id,"application_id"),Ns(t.app_key,"app_key"))}async function jn(t){let e=t.parentOpHashes??[],n=g(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?f(new Uint8Array([Ds.MemberJoinedAt]),g(t.member,"member",32),qn(t.invitation),S(o),n):f(new Uint8Array([Ds.MemberJoined]),g(t.member,"member",32),qn(t.invitation),n),s=f(new Uint8Array([Pu]),i),a=await I(t.deviceSecret,t.signer,"deviceSecret"),c=g(a.publicKey,"signer.publicKey",32),u=f(new Uint8Array([mo]),g(t.namespaceId,"namespaceId",32),R(e.length),...e.map((m,x)=>g(m,`parentOpHashes[${x}]`,32)),c,S(t.nonce),s),d=await a.sign(f(Iu,u)),l=new Uint8Array([0]);return y(f(u,d,l))}function Tu(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function Du(t){let e=wt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function Os(t){return t.replace(/\/+$/,"")}async function Fn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await jn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Du(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${Os(t.nodeUrl)}/admin-api/namespaces/${p(t.namespaceId)}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Tu(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:Os(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Vn(t){let e=t.deps?.resolve??Ln,n=t.deps?.join??Fn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function _s(t,e,n,r){let i=await(r.bootstrap??Vn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&we(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(On(t,i.session)),{namespaceId:e}}function Ms(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function fo(t,e){let n=Ms(t),r=Ms(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function Nu(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function St(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Nu(n.appVersion,e.appVersion)?n:e,void 0)}async function Et(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function Ks(t,e,n={}){let o=(await Et(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=St(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await fo(e,a),signerId:a,version:s.appVersion}}function $s(t,e){return{next:async()=>Uu(t,e)}}function Uu(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function Ls(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Ou(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Jn(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Ve(e)})}async function kt(t,e,n={}){let r=Ls(t,e.namespaceId),o=0n,i=await Jn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ou(e.initializationParams),name:e.name});return Tn(r,i.contextId,o),we(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function ve(t,e,n={}){let r=Ls(t,e.namespaceId);return Jn(t,r,$s(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function Hs(t,e,n={}){let{groupId:r}=await ve(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Ge({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await ve(t,{namespaceId:e.namespaceId,group:r,op:Me(i,"Member")},n);let{contextId:o}=await kt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function zn(t,e={},n={}){let o=We(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await _u(t,o,n.fetch),s=BigInt(Date.now()),a=await Jn(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(we(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await Ku(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function _u(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await Gs(e)};let o=Object.entries(q(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await Gs(e),s=await Jn(t,e,$s(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function Gs(t){let e=await Fe(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var Qn="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Wn={account_not_linked:Qn,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Mu(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function Ku(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof xe)return{haEnabled:!1,haError:Qn};if(i instanceof z&&Wn[i.code]){let s=i.code==="ha_request_pending"?Mu(i):null,a=Wn[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function ze(t,e,n=globalThis.fetch){let r=St(await Et(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Bs="calimero.delegated.group-namespace.",ho=new Map;function qs(t){let e={};try{e=JSON.parse(localStorage.getItem(Bs+t)??"{}")}catch{}return{...e,...ho.get(t)}}function It(t,e,n){ho.set(t,{...ho.get(t),[e]:n});try{let r=qs(t);r[e]=n,localStorage.setItem(Bs+t,JSON.stringify(r))}catch{}}function Pt(t,e){return q(t.account).namespaces[e]?e:qs(t.account)[e]}function js(t,e){let n=Pt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function Yn(t,e,n){return ve(t,{namespaceId:js(t,e),group:e,op:n})}async function Xn(t,e,n){let r=js(t,e);return ve(t,{namespaceId:r,group:r,op:n})}var Re=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Qe=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},Ye=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},Fs={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Gu=new Set(["upgradeGroup","retryGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function $u(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function Vs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??Yn,s=e.govern?.root??Xn,a=e.createContext??kt,c=e.found??zn,u=e.latestVersion??ze,d=e.signInvitation??Bn,l=e.join,m=e.routing;async function x(h,b){if(!l)throw new Re("joinNamespace without a join handler");return l(h,b.invitation)}let v=()=>{if(r===null)throw new Qe("this call");return r};async function A(h){if(Pt(n,h))return;let b=await v().getGroupInfo(h);It(n.account,h,b.namespaceId??h)}let C=async(h,b,E)=>(await A(b),i(h,b,E)),P=async(h,b,E)=>(await A(b),s(h,b,E));async function T(h){try{return await P(n,h,Rn({member:n.account,groupId:h,credential:n.credential})),!0}catch(b){if($u(b))return!1;throw b}}async function j(h,b){let E=b??String(await v().getContextGroup(h)),{members:O}=await v().listGroupMembers(E);return O.some(H=>H.identity.toLowerCase()===n.account.toLowerCase())}let M={async listNamespacesForApplication(h){return(await v().listNamespaces()).filter(b=>b.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Re("createNamespace without a packageName");let b=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:E,haEnabled:O,haError:H}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:b}});return h.name&&await C(n,E,$e({name:h.name})),{namespaceId:E,haEnabled:O,...H!==void 0?{haError:H}:{}}},async createGroupInNamespace(h,b={}){let{op:E}=await Ge({parentId:h,restricted:b.visibility==="restricted",admin:n.account}),{groupId:O}=await P(n,h,E);return It(n.account,O,h),b.groupName&&await C(n,O,$e({name:b.groupName})),{groupId:O}},async addGroupMembers(h,b){for(let E of b.members)await C(n,h,Me(E.identity,E.role??"Member"))},async removeGroupMembers(h,b){for(let E of b.members)await C(n,h,dn(E))},async setGroupMetadata(h,b){await C(n,h,$e(b))},async setMemberMetadata(h,b,E){await C(n,h,xn(b,E))},async setContextMetadata(h,b,E){await C(n,h,vn(b,E))},async setDefaultCapabilities(h,b){await C(n,h,Ke(b.defaultCapabilities))},async setSubgroupVisibility(h,b){await C(n,h,An(b.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,b,E){await C(n,h,bn(b,E.capabilities))},async deleteGroup(h){return await P(n,h,fn(h)),{isDeleted:!0}},async reparentGroup(h,b){return await P(n,h,mn(h,b.newParentId)),{reparented:!0}},async leaveGroup(h){await C(n,h,yt(n.account))},async leaveNamespace(h){await C(n,h,yt(n.account))},async getContextIdentitiesOwned(h){return{identities:await j(h)?[n.account]:[]}},async joinContext(h){return await T(String(await v().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let E=(await v().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:O}=await a(n,{namespaceId:E,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:O,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:b},E]=await Promise.all([v().listGroupMembers(h),v().getGroupInfo(h)]),O=b.filter(ee=>ee.role==="RelayTee").map(ee=>ee.identity.toLowerCase());if(m){let ee=new Set(O.length>0?O:b.filter(ne=>ne.role==="Admin").map(ne=>ne.identity.toLowerCase())),te=null;try{te=(await m(h)).nodes}catch{}if(te!==null){if(te.length===0)throw new Ye(h,"not-hosted");if(!te.some(ne=>ne.account!==null&&ee.has(ne.account.toLowerCase())))throw new Ye(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...O.length>0?{admitters:O}:{},members:b,applicationId:E.targetApplicationId,appKey:E.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:x,async updateMemberRole(h,b,E){await C(n,h,pn(b,E.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await T(h)}},async detachContextFromGroup(h,b){await C(n,h,wn(b))}};return r===null?new Proxy({},{get(h,b){if(typeof b=="string")return b==="getNodeIdentity"?M.getNodeIdentity:b==="joinNamespace"?x:b in Fs?Fs[b]:async()=>{throw new Qe(b)}}}):new Proxy(r,{get(h,b,E){return typeof b=="string"&&b in M?M[b]:typeof b=="string"&&Gu.has(b)?async()=>{throw new Re(b)}:Reflect.get(h,b,E)}})}function Ws(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??ze;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var Lu="https://manager.cloud.calimero.network";function yo(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function bo(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function io(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Hu(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function Bu(t){return typeof t=="string"&&ao.test(t)?t:null}var z=class extends D{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},xe=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};xe.CODE="account_not_linked";var At=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};At.CODE="account_linked_to_several_users";var xt=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};xt.CODE="ha_request_pending";var vt=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};vt.CODE="unknown_relay";var Rt=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};Rt.CODE="relay_not_dialable";var Js={409:[xe,At,xt],422:[vt,Rt]};function qu(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var ju="x-mdma-session-refresh",Fu="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Lu).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await Q(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Jt({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${p(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:bo(r),canExecute:yo(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Hu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return io(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${p(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:bo(r),canExecute:yo(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${p(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Kn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${p(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${p(e)}/relays`,{anonymous:!0,headers:await Kn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Bu(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:bo(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:yo(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${p(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${p(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await hr({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${p(r)}/namespaces/${p(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof D&&Js[i.status]){let s=qu(i.bodyText),a=Js[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${p(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await Q(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await it({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":Gn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};return c&&Je(o),s&&Je(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Wt(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await it({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new D(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new D(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(ju);if(!n||!this.session)return;let r=e.headers.get(Fu),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Eu(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function Vu(t){if(t)return typeof t=="function"?t:Lt(t)}var Wu="mero-js:token-refresh";function Ju(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function zu(t){try{let{origin:e,pathname:n}=new URL(t);return e==="null"?t:e+n.replace(/\/+$/,"")}catch{return t}}function wo(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var qe=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.nodeKey=zu(e.baseUrl),this.tokenData=this.readStoredTokens(),this.tokenStore&&(this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=Vu(this.config.requestProof);this.httpClient=Ee({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens())},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=To(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Kt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new rt({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new B({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new ot({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new se({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:wo(i,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(){!this.tokenStore||!this.tokenData||(this.tokenStore.setTokens({...this.tokenData,node_origin:this.nodeKey}),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}readStoredTokens(){let e=this.tokenStore?.getTokens();return!e||e.node_origin!==this.nodeKey?null:{access_token:e.access_token,refresh_token:e.refresh_token,expires_at:e.expires_at}}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=Ju();return n?n.request(Wu,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.readStoredTokens();if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:wo(a,Date.now()+36e5)},this.persistTokens(),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||wo(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens()}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return dr(e)}static buildAuthLoginUrl(e,n){return pr(e,n)}};function Qu(t){return new qe(t)}var Ao=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Yu="mero-tokens",xo=class{constructor(e=Yu){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5,...typeof n.node_origin=="string"&&{node_origin:n.node_origin}}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var Xu=new TextEncoder().encode("calimero.account.owner-op.v1"),Zu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),ed=new TextEncoder().encode("calimero.account.genesis.v1"),td=2,vo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Xe={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},Qs={AdminChanged:3,RootGuarded:12},nd={replica:0,relay:1},rd=new TextEncoder;function L(t){return new Uint8Array([t])}function Ys(t){let e=rd.encode(t);return f(R(e.length),e)}function Z(t){return f(R(t.length),...t.map(Ys))}function Xs(t){return L(t?1:0)}function Zs(t){let e=nd[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return L(e)}function ea(t){return{kind:"transferOwnership",plane:"group",bytes:f(L(Xe.TransferOwnership),g(t,"newOwner",32))}}function ta(){return{kind:"groupDelete",plane:"group",bytes:L(Xe.GroupDelete)}}function na(t){return{kind:"adminChanged",plane:"root",bytes:f(L(Qs.AdminChanged),g(t,"newAdmin",32))}}function ra(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:f(L(Xe.TeeAuthoringPolicySet),Z(t))}}function oa(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:f(L(Xe.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),Xs(t.acceptMock),Zs(t.mode))}}function ia(t){let e=t.minReleaseVersion===void 0?L(0):f(L(1),Ys(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:f(L(Xe.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),Xs(t.acceptMock),Zs(t.mode))}}async function Ro(t){return k(Zu,[t])}async function Co(t){return k(Xu,[g(t.account,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(sa(t.kind)),t.opDigest,S(t.counter),R(t.keyEpoch)])}function sa(t){let e=vo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var zs=132;async function aa(t){let e=await ie(t.rootSecret),n=f(L(td),e),r=y(await k(ed,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let m=F(d,`chain[${l}]`);if(m.length!==zs)throw new Error(`chain[${l}] must be a ${zs}-byte RootKeyHandoff, got ${m.length}`);return m});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await Ro(t.op.bytes),a=await Co({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await oe(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return y(f(n,R(i.length),...i,g(r,"account",32),g(t.namespaceId,"namespaceId",32),g(t.groupId,"groupId",32),L(sa(t.op.kind)),s,S(t.counter),R(o),u))}function ca(t,e){let n=t.plane==="group"?Xe.RootGuarded:Qs.RootGuarded;return f(L(n),t.bytes,F(e,"rootProof"))}var la=[2428,2429,2528,2529],od="localhost",id=2e3;function ua(t){return`http://${od}:${t}`}function da(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function pa(t,e={}){let{timeoutMs:n=id,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=da(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function sd(t={}){let{ports:e=la,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=ua(i);return await pa(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}function Zn(t,e){return(t<<e|t>>>32-e)>>>0}function ue(t,e,n,r,o){t[e]=t[e]+t[n]>>>0,t[o]=Zn(t[o]^t[e],16),t[r]=t[r]+t[o]>>>0,t[n]=Zn(t[n]^t[r],12),t[e]=t[e]+t[n]>>>0,t[o]=Zn(t[o]^t[e],8),t[r]=t[r]+t[o]>>>0,t[n]=Zn(t[n]^t[r],7)}function ga(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function ha(t,e,n){let r=new Uint32Array(16);r[0]=1634760805,r[1]=857760878,r[2]=2036477234,r[3]=1797285236;for(let s=0;s<8;s+=1)r[4+s]=ga(t,s*4);r[12]=e>>>0;for(let s=0;s<3;s+=1)r[13+s]=ga(n,s*4);let o=r.slice();for(let s=0;s<10;s+=1)ue(o,0,4,8,12),ue(o,1,5,9,13),ue(o,2,6,10,14),ue(o,3,7,11,15),ue(o,0,5,10,15),ue(o,1,6,11,12),ue(o,2,7,8,13),ue(o,3,4,9,14);let i=new Uint8Array(64);for(let s=0;s<16;s+=1){let a=o[s]+r[s]>>>0;i[s*4]=a&255,i[s*4+1]=a>>>8&255,i[s*4+2]=a>>>16&255,i[s*4+3]=a>>>24&255}return i}function ad(t,e,n,r){let o=new Uint8Array(r.length);for(let i=0,s=e;i<r.length;i+=64,s+=1){let a=ha(t,s,n),c=Math.min(i+64,r.length);for(let u=i;u<c;u+=1)o[u]=r[u]^a[u-i]}return o}function So(t){let e=0n;for(let n=t.length-1;n>=0;n-=1)e=e<<8n|BigInt(t[n]);return e}var cd=(1n<<130n)-5n;function ld(t,e){let n=So(t.subarray(0,16))&0x0ffffffc0ffffffc0ffffffc0fffffffn,r=So(t.subarray(16,32)),o=0n;for(let a=0;a<e.length;a+=16){let c=e.subarray(a,Math.min(a+16,e.length)),u=So(c)+(1n<<BigInt(8*c.length));o=(o+u)*n%cd}let i=o+r&(1n<<128n)-1n,s=new Uint8Array(16);for(let a=0;a<16;a+=1)s[a]=Number(i&0xffn),i>>=8n;return s}function ma(t){return new Uint8Array((16-t%16)%16)}function fa(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function ud(t,e){let n=[t,ma(t.length),e,ma(e.length),fa(t.length),fa(e.length)],r=new Uint8Array(n.reduce((i,s)=>i+s.length,0)),o=0;for(let i of n)r.set(i,o),o+=i.length;return r}function dd(t,e){if(t.length!==32)throw new Error("ChaCha20-Poly1305 needs a 32-byte key");if(e.length!==12)throw new Error("ChaCha20-Poly1305 needs a 12-byte nonce")}function ya(t,e,n,r=new Uint8Array(0)){dd(t,e);let o=ha(t,0,e).subarray(0,32),i=ad(t,1,e,n),s=ld(o,ud(r,i)),a=new Uint8Array(i.length+16);return a.set(i),a.set(s,i.length),a}var wa=32,pd=1,gd=3,md=2,fd=32,hd=32,yd=12,Ze=t=>new TextEncoder().encode(t),Dt=t=>new Uint8Array([t>>8&255,t&255]),ba=f(Ze("KEM"),Dt(wa)),Tt=f(Ze("HPKE"),Dt(wa),Dt(pd),Dt(gd));async function Aa(t,e){let n=t.length===0?new Uint8Array(32):t,r=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",r,e))}async function bd(t,e,n){let r=new Uint8Array(n),o=new Uint8Array(0);for(let i=1,s=0;s<n;i+=1)o=await Aa(t,f(o,e,new Uint8Array([i]))),r.set(o.subarray(0,Math.min(o.length,n-s)),s),s+=o.length;return r}function er(t,e,n,r){return Aa(e,f(Ze("HPKE-v1"),t,Ze(n),r))}function Eo(t,e,n,r,o){return bd(e,f(Dt(o),Ze("HPKE-v1"),t,Ze(n),r),o)}async function wd(t,e){let n=await er(ba,new Uint8Array(0),"eae_prk",t);return Eo(ba,n,"shared_secret",e,fd)}async function Ad(t,e){let n=new Uint8Array(0),r=await er(Tt,n,"psk_id_hash",n),o=await er(Tt,n,"info_hash",e),i=f(new Uint8Array([md]),r,o),s=await er(Tt,t,"secret",n);return{key:await Eo(Tt,s,"key",i,hd),nonce:await Eo(Tt,s,"base_nonce",i,yd)}}async function xa(t,e,n,r,o=new Uint8Array(0),i){if(t.length!==32)throw new Error("The recipient key is not 32 bytes of X25519");let s=await Te(i),a=await Te(e),c=f(await st(s.privateKey,t),await st(a.privateKey,t)),u=await wd(c,f(s.publicKey,t,a.publicKey)),{key:d,nonce:l}=await Ad(u,n);return{enc:s.publicKey,ciphertext:ya(d,l,r,o)}}var Ca="mero-agent-gate/attest/v3",Sa="mero-agent-gate/provision/v2",xd=/^[a-z0-9][a-z0-9-]{0,62}$/,vd=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/,va=64,Ra=64*1024,de=class extends Error{constructor(n,r,o){super(n);this.status=r;this.code=o;this.name="AgentGateError"}};function Ea(t){if(!xd.test(t))throw new Error(`Agent id ${JSON.stringify(t)} must match [a-z0-9][a-z0-9-]{0,62}`)}function Nt(t){return new TextEncoder().encode(t)}function ka(t){let e=Nt(t);return f(new Uint8Array([e.length]),e)}function Ce(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}function tr(t,e,n){let r;try{r=Uint8Array.from(atob(t.trim()),o=>o.charCodeAt(0))}catch{throw new Error(`${e} is not base64`)}if(n!==void 0&&r.length!==n)throw new Error(`${e} is not ${n} bytes`);return r}async function Ia(t,e,n,r){let o=new Uint8Array(32),i=f(Nt(Ca),t,ka(e),n??o,r??o);return new Uint8Array(await crypto.subtle.digest("SHA-256",i))}function Pa(t,e){return f(Nt(Sa),t,ka(e))}async function Rd(){let t=crypto.getRandomValues(new Uint8Array(32));return{secret:t,publicKey:await nr(t)}}async function nr(t){if(t.length!==32)throw new Error("An owner key is 32 bytes");return Ce((await Te(t)).publicKey)}function Ta(t,e){return`${t.replace(/\/+$/,"")}${e}`}async function Da(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),o=await r.text(),i;try{i=o?JSON.parse(o):void 0}catch{}if(!r.ok){let s=i;throw new de(`The gate answered ${r.status}${s?.error?` ${s.error}`:""}: ${s?.details??o.slice(0,200)}`,r.status,s?.error)}return i}async function ko(t){let e=t.agentId??"";e&&Ea(e);let n=crypto.getRandomValues(new Uint8Array(32)),r=await Da(t.fetch??fetch,Ta(t.gateUrl,"/attest"),{nonceB64:Ce(n),...e?{agentId:e}:{}});if((r?.agentId??"")!==e)throw new Error(`Asked about agent ${JSON.stringify(e)}, the gate answered for ${JSON.stringify(r?.agentId)}`);let o=tr(r.provisioningPublicKeyB64??"","provisioningPublicKeyB64",32),i=r.signingPublicKeyB64?tr(r.signingPublicKeyB64,"signingPublicKeyB64",32):void 0,s=r.ownerPublicKeyB64?tr(r.ownerPublicKeyB64,"ownerPublicKeyB64",32):void 0;if(!i!=!s)throw new Error("A claimed agent has both a signing key and an owner; the gate named one");let a=await Ia(o,e,i,s);return await t.verifier({quoteB64:r.quoteB64,nonce:y(n),reportDataSuffix:y(a)}),{agentId:e,provisioningPublicKey:Ce(o),...i?{signingPublicKey:Ce(i)}:{},...s?{ownerPublicKey:Ce(s)}:{}}}async function Na(t,e){let n=await nr(e);if(t.ownerPublicKey&&t.ownerPublicKey!==n)throw new de(`This agent is claimed by another key (${t.ownerPublicKey}); it is not yours. Send it nothing and do not authorize its signing key`,void 0,"not_yours");return n}function Cd(t){let e=Object.keys(t);if(e.length===0)throw new Error("There are no secrets to provision");if(e.length>va)throw new Error(`At most ${va} secrets at once`);for(let n of e){if(!vd.test(n))throw new Error(`Secret name ${JSON.stringify(n)} must match [A-Za-z0-9][A-Za-z0-9_.-]{0,63}`);if(typeof t[n]!="string")throw new Error(`Secret ${n} is not a string`);if(Nt(t[n]).length>Ra)throw new Error(`Secret ${n} is over ${Ra} bytes`)}}async function Ua(t,e,n,r,o,i){if(!r.agentId)throw new Error("This quote names no agent; attest with the agent id");let s=await Na(r,o),a=tr(r.provisioningPublicKey,"provisioningPublicKey",32),c=await xa(a,o,Pa(a,r.agentId),Nt(JSON.stringify(i)));return Da(t,Ta(e,n),{agentId:r.agentId,provisioningPublicKeyB64:r.provisioningPublicKey,senderPublicKeyB64:s,encappedKeyB64:Ce(c.enc),ciphertextB64:Ce(c.ciphertext)})}async function Sd(t){Cd(t.secrets);let e=t.fetch??fetch,n=await Ua(e,t.gateUrl,"/provision",t.agent,t.ownerSecret,{secrets:t.secrets}),r=await ko({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e}),o=await nr(t.ownerSecret);if(r.ownerPublicKey!==o||!r.signingPublicKey)throw new de("The gate accepted the secrets, but its quote does not name your key as owner");if(t.agent.signingPublicKey&&t.agent.signingPublicKey!==r.signingPublicKey)throw new de("The agent's signing key changed while provisioning");return{agentId:r.agentId,provisioningPublicKey:r.provisioningPublicKey,signingPublicKey:r.signingPublicKey,ownerPublicKey:o,written:n?.written??[],claimed:n?.claimed===!0}}async function Ed(t){if(!t.agent.ownerPublicKey)throw new Error("This agent is not claimed; there is nothing to release");let e=t.fetch??fetch;if(await Ua(e,t.gateUrl,"/release",t.agent,t.ownerSecret,{release:!0}),(await ko({gateUrl:t.gateUrl,agentId:t.agent.agentId,verifier:t.verifier,fetch:e})).ownerPublicKey)throw new de("The gate says it released the agent, but its quote still names an owner")}var Io=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-kms.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),kd=["allowed_tcb_statuses","allowed_mrtd","allowed_rtmr0","allowed_rtmr1","allowed_rtmr2","allowed_rtmr3"];async function Id(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await en(r,e,{identity:n.identity??Io.identity,issuer:n.issuer??Io.issuer});let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed agent policy is not JSON")}if(o?.role!=="agent")throw new Error(`The signed file is a ${JSON.stringify(o?.role)} policy, not an agent one`);let i=n.profile??ut;if(o.profile!==i)throw new Error(`The signed agent policy is for the ${JSON.stringify(o.profile)} profile, not ${i}`);if(n.expectedVersion!==void 0&&o.version!==n.expectedVersion)throw new Error(`The signed agent policy is release ${JSON.stringify(o.version)}, not ${n.expectedVersion}`);return Oa(o),o}function Oa(t){for(let e of kd)if(!Array.isArray(t?.[e])||t[e].length===0)throw new Error(`The agent policy's ${e} is empty, so no agent would be accepted`)}var Pd=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function Td(t){let e=Pd.find(n=>n.toLowerCase()===t.trim().toLowerCase());if(!e)throw new Error(`The agent policy allows an unknown TCB status ${JSON.stringify(t)}`);return e}var Ut=t=>t.trim().replace(/^0x/i,"");function Dd(t,e){return Oa(t),dt({dcapVerify:e.dcapVerify,fetchCollateral:e.fetchCollateral,now:e.now,allowedTcbStatuses:t.allowed_tcb_statuses.map(Td),allowedMrtd:t.allowed_mrtd.map(Ut),allowedRtmr0:t.allowed_rtmr0.map(Ut),allowedRtmr1:t.allowed_rtmr1.map(Ut),allowedRtmr2:t.allowed_rtmr2.map(Ut),allowedRtmr3:t.allowed_rtmr3.map(Ut)})}export{Jo as ACCOUNT_HA_AUDIENCE,Wo as ACCOUNT_OWNERSHIP_AUDIENCE,Ca as AGENT_ATTEST_DOMAIN,Sa as AGENT_PROVISION_INFO_DOMAIN,z as AccountHaRefusedError,At as AccountLinkedToSeveralUsersError,xe as AccountNotLinkedError,me as AdminApiClient,de as AgentGateError,pe as AuthApiClient,re as AuthRevokedError,_ as CAPABILITIES,Zd as CAPABILITY_PRESETS,$ as CloudClient,la as DEFAULT_LOCAL_NODE_PORTS,tn as DEFAULT_RELEASE_MIRROR,ot as EphemeralClient,wi as HANDSHAKE_PATH,Qn as HA_ACCOUNT_NOT_LINKED_MESSAGE,Wn as HA_REFUSAL_MESSAGES,D as HTTPError,xt as HaRequestPendingError,uo as INVITED_ROLE,he as IntentRefusedError,Ye as InvitationNotClaimableError,Io as KMS_RELEASE_SIGNER,xo as LocalStorageTokenStore,Hn as MAX_INVITATION_VALIDITY_SECS,Ao as MemoryTokenStore,be as MeroClient,qe as MeroJs,Ur as NODE_RELEASE_SIGNER,Qe as NoRelayError,Re as NotForAccountError,vo as OWNER_OP_KIND,es as PRESENCE_DOMAIN,ut as PRODUCTION_PROFILE,Pn as RELAY_NODE_KEY_RETRY_MS,Vr as REQUEST_PROOF_HEADER,J as RelayClient,Rt as RelayNotDialableError,He as RelayObserver,bt as RelayPresenceClient,ye as RelayTransport,rt as RpcClient,Ht as RpcError,ct as SEALED_CONTENT_TYPE,Ai as SEALED_PATH,mo as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,De as SealedTransportError,B as SseClient,lt as StaleTransportKeyError,vt as UnknownRelayError,_n as WarrantNonceExhaustedError,Mt as WarrantNonceRouteUnavailableError,et as WebHttpClient,se as WsClient,Vt as accountForRoot,V as accountForRootPublicKey,ti as accountRootFromPhrase,vr as accountRootFromSecret,ri as accountRootSignerFromPhrase,na as adminChangedOp,Eu as admitterAddrsFromNetworkStatus,Ia as agentKeyBinding,Dd as agentQuoteVerifier,fo as applicationIdForBundle,Fe as attemptRelayNodeKey,ko as attestAgent,Qt as attestKeyBinding,Yt as attestRelayNodeKey,iu as authorNonceLookup,mu as beginCloudLink,xu as beginDeviceEnrolment,Vn as bootstrapFromInvitation,pr as buildAuthLoginUrl,Un as buildDelegatedClient,Ts as callbackIsForeign,$t as callerProof,ep as capMask,tp as capNames,On as carryExecutorAccount,Na as checkOwner,lr as classifyError,ls as clearDelegatedCredential,ss as clearDelegatedSession,Es as cloudLinkUrl,on as cloudNodeReleaseUrl,or as combineSignals,Wa as compareSemver,hu as completeCloudLink,Ru as completeDeviceEnrolment,As as connectCloud,au as connectCloudWithAccount,Qi as contextCapabilityGrantedOp,Yi as contextCapabilityRevokedOp,wn as contextDetachedOp,vn as contextMetadataSetOp,Vs as createAccountAdmin,ni as createAccountRootSigner,_o as createAdminApiClient,Kt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,Yd as createAuthApiClient,To as createAuthApiClientFromHttpClient,wp as createBrowserAdminApiClient,zd as createBrowserAuthApiClient,Ee as createBrowserHttpClient,kt as createDelegatedContext,Hs as createDelegatedPrivateContext,tt as createHttpClient,wt as createLocalStorageNonceSource,Mn as createMemoryNonceSource,En as createMeroClient,Qu as createMeroJs,Ws as createNodeAdmin,Ap as createNodeAdminApiClient,Qd as createNodeAuthApiClient,Ot as createNodeHttpClient,Jr as createProofAuthorizer,Lt as createProofSigner,dt as createQuoteVerifier,su as createRecoveringNonceSource,La as createRetryableMethod,Ci as createSealedFetch,pl as createSignedReleaseSealedFetch,sn as createSignedReleaseVerifier,ir as createTimeoutSignal,sr as createUniversalHttpClient,Hr as createdSubgroupId,Mr as creationInitHash,go as defaultAdmitters,Be as defaultAudience,Ke as defaultCapabilitiesSetOp,ve as delegatedGovernance,jt as deviceCertPayload,Ps as deviceEnrolmentUrl,wr as deviceScopePayload,sd as discoverLocalNodes,Ct as encodeGroupInvitation,qn as encodeSignedInvitation,Ri as fetchAttestedTransportKey,nn as fetchNodeRelease,rn as fetchNodeReleaseVersion,Et as fetchRegistryBundles,fs as forgetMethodKinds,ms as forgetRelaySealing,zn as foundDelegatedNamespace,hn as foundedNamespaceId,ei as generateAccountRoot,Rd as generateOwnerKey,Fr as generateSessionKey,Yn as governGroup,Xn as governRoot,Kr as governanceOpHash,Br as groupCreatedOp,ta as groupDeleteOp,fn as groupDeletedOp,po as groupInvitationHash,$e as groupMetadataSetOp,mn as groupReparentedOp,ge as hasCap,mp as hexEncodeUtf8,Or as intentHash,ja as isSettled,_s as joinAsAccount,Fn as joinWithNode,ae as jsonCodec,We as knownRelays,ze as latestPublishedVersion,gs as learnRelayNodeKey,bs as listDelegatedContexts,ws as listDelegatedNamespaces,ua as localNodeUrl,Le as login,Tn as markContextNonceSpent,Me as memberAddedOp,bn as memberCapabilitySetOp,Rn as memberJoinedOpenOp,yt as memberLeftOp,xn as memberMetadataSetOp,dn as memberRemovedOp,pn as memberRoleSetOp,yr as mintDeviceId,yn as namespaceCreatedOp,Pt as namespaceOfGroup,da as nodeEndpoint,Mi as nodeReleaseVersionFromImage,$n as normaliseAccount,Ro as ownerOpDigest,Co as ownerOpSigningPayload,nr as ownerPublicKey,dr as parseAuthCallback,Fi as parseCreationWarrant,br as parseDeviceCredential,Vi as parseGovernanceWarrant,No as parseWarrantNonce,to as persistedNonces,no as pinRelayNodeKey,zr as presenceStatementBytes,pa as probeNodeHealth,Sd as provisionAgent,Pa as provisionInfo,fu as readCloudLinkCallback,as as readDelegatedCredential,eo as readDelegatedSession,vu as readEnrolmentCallback,Dn as readPinnedRelayNodeKey,q as readRelayMap,Do as redeemInvitation,ys as relayForContext,Ve as relayTransportFetch,Ed as releaseAgent,It as rememberGroupNamespace,we as rememberRelay,Cr as reportDataOf,gr as requestBodyHash,Ks as resolveApplicationIdFromRegistry,Ln as resolveRelayFromInvitation,Nn as resolveRelayNodeKey,Q as resolveRoot,Wt as resolveRootPair,ca as rootGuardedOpBytes,Kn as routingProofHeaders,cs as saveDelegatedCredential,is as saveDelegatedSession,St as selectLatestBundle,sp as shouldRetain,hr as signAccountHaClaim,it as signAccountLink,Jt as signAccountLogin,ic as signAccountOwnershipClaim,ln as signCreationWarrant,Yo as signDeviceCert,Xo as signDeviceScope,ft as signGovernanceWarrant,Bn as signGroupInvitation,Sn as signLoginStatement,jn as signMemberJoinOp,aa as signOwnerOpProof,Gt as signRequest,Wr as signRequestProof,xs as signRoutingChallenge,an as signWarrant,Bl as signedPath,Bo as signerFromCryptoKey,ke as signerFromSecret,ts as stateHash,Ge as subgroupCreation,An as subgroupVisibilitySetOp,qt as subscribePresence,gn as targetApplicationSetOp,oa as teeAdmissionPolicyOp,ra as teeAuthoringPolicyOp,ia as teeReleaseAdmissionPolicyOp,ea as transferOwnershipOp,vi as transportKeyBinding,$i as trustSignedRelease,Pr as trustedMeasurementsFromReleases,Ea as validateAgentId,Ft as verifyDeviceCredential,Id as verifySignedAgentPolicy,_i as verifySignedNodeRelease,ar as withCap,_t as withRetry,np as withoutCap};
3
3
  //# sourceMappingURL=index.browser.mjs.map