@calimero-network/mero-js 22.5.0 → 22.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +144 -19
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/index.mjs +144 -19
- package/dist/index.mjs.map +4 -4
- package/dist/namespace-op/namespace-op.d.ts +5 -1
- package/dist/namespace-op/namespace-op.js +5 -1
- package/dist/relay/relay-client.d.ts +18 -1
- package/dist/relay/relay-client.js +18 -3
- package/dist/signer/index.d.ts +2 -0
- package/dist/signer/index.js +3 -0
- package/dist/signer/signer.d.ts +92 -0
- package/dist/signer/signer.js +147 -0
- package/dist/warrant/creation-warrant.d.ts +17 -3
- package/dist/warrant/creation-warrant.js +6 -5
- package/dist/warrant/governance-warrant.d.ts +17 -3
- package/dist/warrant/governance-warrant.js +6 -5
- package/dist/warrant/warrant.d.ts +20 -1
- package/dist/warrant/warrant.js +19 -4
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function Be(n){let e=n.filter(Boolean);if(e.length===0)return;let t=AbortSignal;if(typeof t.any=="function")try{return t.any(e)}catch{}let r=new AbortController,o=s=>{r.abort(s.target.reason);for(let a of e)a.removeEventListener("abort",o)};for(let s of e){if(s.aborted)return AbortSignal.abort(s.reason);s.addEventListener("abort",o,{once:!0})}return r.signal}function Ke(n){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(n);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},n),e.signal}var cr=new Set(["token_reuse","token_revoked"]);function ur(n){if(n)try{let e=JSON.parse(n),t=e?.error;if(typeof t=="string"&&t.trim()!=="")return t;let r=t?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var S=class extends Error{constructor(t,r,o,s,a){let i=ur(a)??(t===0&&a?.trim()?a.trim():void 0);super(i?`HTTP ${t} ${r}: ${i}`:`HTTP ${t} ${r}`);this.status=t;this.statusText=r;this.url=o;this.headers=s;this.bodyText=a;this.name="HTTPError";this.explanation=i}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Ut(this.headers),bodyText:this.bodyText}}},_=class extends S{constructor(t,r,o,s,a,i){super(r,o,s,a,i);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${r} ${o}`}};function Ut(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}function lr(n){try{return new URL(n).pathname}catch{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)}}var re=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,r){return this.request(e,{...r,method:"POST",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,t,r){return this.request(e,{...r,method:"PUT",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}async patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,t){let r=await this.makeRequest(e,{...t,method:"HEAD",parse:"response"});return{headers:Ut(r.headers),status:r.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,r=0,o){let a=this.buildUrl(e),i=o??Date.now(),c=this.createAbortSignal(t),l=await this.buildHeaders(t?.headers),d;l instanceof Headers?(d={},l.forEach((m,R)=>{d[R]=m})):d=l;let u={method:t?.method||"GET",headers:d},g=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!g||t?.body!==void 0&&g&&r===0)&&(u.body=t.body);let b;if(r>0&&o!==void 0){let m=t?.timeoutMs||this.transport.timeoutMs;if(m){let R=Date.now()-i,k=Math.max(0,m-R);b=this.createAbortSignal({...t,timeoutMs:k})}else b=this.createAbortSignal(t)}else b=c;if(b&&(u.signal=b),this.transport.credentials!==void 0&&(u.credentials=this.transport.credentials),t?.mode!==void 0&&(u.mode=t.mode),t?.cache!==void 0&&(u.cache=t.cache),t?.redirect!==void 0&&(u.redirect=t.redirect),t?.referrer!==void 0&&(u.referrer=t.referrer),t?.referrerPolicy!==void 0&&(u.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(u.integrity=t.integrity),t?.keepalive!==void 0&&(u.keepalive=t.keepalive),this.transport.getProof){let m=await this.transport.getProof({method:u.method??"GET",path:lr(a),body:u.body});m&&(d["X-Calimero-Proof"]=m)}try{let m=await this.transport.fetch(a,u);if(!m.ok){let R=await this.getBodyText(m),k=new S(m.status,m.statusText,a,m.headers,R),v=m.headers.get("x-auth-error");if((m.status===401||m.status===403)&&v&&cr.has(v)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new _(v,m.status,m.statusText,a,m.headers,R)}let C=t?.signal?.aborted===!0;if(m.status===401&&this.transport.refreshToken&&v==="token_expired"&&r<1&&!g&&!C)try{let P=this.refreshTokenPromise;P||(P=this.transport.refreshToken(),this.refreshTokenPromise=P);let $=await P;if(!$||$.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 D=this.onTokenRefreshPromise;D||(D=this.transport.onTokenRefresh($),this.onTokenRefreshPromise=D),await D,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let N=t?.timeoutMs||this.transport.timeoutMs;if(N&&o!==void 0){let V=Date.now()-i;if(N-V<=0)throw k}return this.makeRequest(e,t,r+1,i)}catch(P){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,P instanceof Error&&P.message.includes("onTokenRefresh")?P:k}throw k}return this.parseResponse(m,t?.parse)}catch(m){throw m instanceof S||m instanceof Error&&m.message.includes("onTokenRefresh")?m:new S(0,"Network Error",a,new Headers,m instanceof Error?m.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let t=this.transport.baseUrl;return e.startsWith("/")?`${t.endsWith("/")?t.slice(0,-1):t}${e}`:`${t.endsWith("/")?t:`${t}/`}${e}`}createAbortSignal(e){let t=[];this.transport.defaultAbortSignal&&t.push(this.transport.defaultAbortSignal),e?.signal&&t.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&t.push(Ke(r)),t.length>0?Be(t):void 0}async buildHeaders(e){let t={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(t.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{t[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{t[r]=o}):Object.assign(t,e)),t}async parseResponse(e,t){switch(t){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 t=await e.text();return t.length>65536?t.slice(0,65536)+"...":t}catch{return""}}};function je(n){return new re(n)}function z(n){let e={fetch:(t,r)=>n.fetch?n.fetch(t,r):globalThis.fetch(t,r),baseUrl:n.baseUrl,getAuthToken:n.getAuthToken,getProof:n.getProof,onTokenRefresh:n.onTokenRefresh,refreshToken:n.refreshToken,onAuthRevoked:n.onAuthRevoked,defaultHeaders:n.defaultHeaders,timeoutMs:n.timeoutMs,credentials:n.credentials,defaultAbortSignal:n.defaultAbortSignal};return je(e)}function ye(n){let e=n.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,s)=>globalThis.fetch(o,s):(o,s)=>e(o,s),baseUrl:n.baseUrl,getAuthToken:n.getAuthToken,getProof:n.getProof,onTokenRefresh:n.onTokenRefresh,refreshToken:n.refreshToken,onAuthRevoked:n.onAuthRevoked,defaultHeaders:n.defaultHeaders,timeoutMs:n.timeoutMs,credentials:n.credentials,defaultAbortSignal:n.defaultAbortSignal};return je(r)}function Ve(n){return typeof window<"u"?z(n):ye(n)}function dr(n,e){if(e<=0)return!1;let r=n?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=n;if("status"in o&&typeof o.status=="number"){let s=o.status;return s>=500||s===429}return r==="TypeError"}function pr(n){let t=250*Math.pow(2,n-1),r=(Math.random()-.5)*.4*t;return Math.max(0,t+r)}async function be(n,e={}){let{attempts:t=3}=e,r;for(let o=1;o<=t;o++)try{return await n(o)}catch(s){if(r=s,!dr(r,t-o))throw r;let a=pr(o),l=r.headers?.get?.("Retry-After");if(l){let d=parseInt(l,10);if(!isNaN(d))a=Math.max(a,d*1e3);else{let u=new Date(l);if(!isNaN(u.getTime())){let g=Math.max(0,u.getTime()-Date.now());a=Math.max(a,Math.min(g,6e4))}}}await new Promise(d=>setTimeout(d,a))}throw r||new Error("Retry failed without error")}function gr(n,e={}){return async(...t)=>be(()=>n(...t),e)}var q=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 t=await this.validateTokenGet(e);return{valid:t.status===200,headers:t.headers,status:t.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let t=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:t.status,headers:t.headers}}async revokeTokens(e){let t=await this.httpClient.post("/admin/revoke",e);if(!t.data)throw new Error("Revoke tokens response data is null");return t.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 t=await this.httpClient.post("/admin/keys",e);if(!t.data)throw new Error("Create root key response data is null");return t.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${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,t){return this.httpClient.delete(`/admin/keys/${e}/clients/${t}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,t){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:t.add,remove:t.remove})}};var oe=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 Ds(n){let e=new oe;return new q(e)}function Us(n){let e=new oe;return new q(e)}function Ms(n){let e=new oe;return new q(e)}function Mt(n,e){return new q(n)}var se={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};function Fe(n,e){let t=e>>>0;return(n&t)>>>0===t}function We(n,e){return(n|e)>>>0}function _s(n,e){return(n&~e)>>>0}var mr={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 hr(n){switch(n){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 n>=500&&n<600?"server":n>=400&&n<500?"invalid":"unknown"}function fr(n){if(!n||typeof n!="object")return;let e=n;for(let t of[e.status,e.response?.status,e.statusCode])if(typeof t=="number"&&Number.isFinite(t))return t}function Je(n,e="Request failed"){if(typeof n=="string")return n.trim()||e;if(!n||typeof n!="object")return e;let t=n;for(let r of[t.explanation,t.response?.data?.error,t.response?.data?.message,t.data?.message,t.error,t.message])if(typeof r=="string"&&r.trim())return r;return e}function ze(n){let e=fr(n),t;return e!==void 0?t=hr(e):n instanceof TypeError?t="unreachable":t="unknown",{kind:t,status:e,retryable:mr[t],message:Je(n)}}function yr(n){return n.status!=="failed"||!n.retryable}function $s(n){return!yr(n)}function br(n){let e=n.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 wr(n,e){let{kind:t,status:r}=ze(n),o=br(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}:t==="unavailable"?{reason:"no-one-online",retryable:!0}:t==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Nt(n,e){let{namespaceId:t,invitation:r,teamName:o}=n,s=null;try{await e.join(t,r)}catch(d){s=d}let a=null;try{a=(await e.memberships()).includes(t)}catch{a=null}if(s===null)return{status:"joined",namespaceId:t,teamName:o};if(a===!0)return{status:"already-member",namespaceId:t,teamName:o};let i=Je(s,"Could not join. Check the invitation."),{reason:c,retryable:l}=wr(s,i);return{status:"failed",namespaceId:t,message:i,reason:c,retryable:l}}function p(n){return n?.data}function Ar(n,e){let[t,r]=_t(n),[o,s]=_t(e),a=t.split("."),i=o.split("."),c=Math.max(a.length,i.length);for(let g=0;g<c;g++){let b=Gt(a[g]??"0",i[g]??"0");if(b!==0)return b}if(r===void 0&&s===void 0)return 0;if(r===void 0)return 1;if(s===void 0)return-1;let l=r.split("."),d=s.split("."),u=Math.max(l.length,d.length);for(let g=0;g<u;g++){if(g>=l.length)return-1;if(g>=d.length)return 1;let b=Gt(l[g],d[g]);if(b!==0)return b}return 0}function _t(n){let e=n.split("+",1)[0],t=e.indexOf("-");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Gt(n,e){let t=/^\d+$/.test(n),r=/^\d+$/.test(e);if(t&&r){let o=Number(n)-Number(e);return o<0?-1:o>0?1:0}return t?-1:r?1:n<e?-1:n>e?1:0}async function Rr(n,e,t){return be(async()=>{let r=await fetch(n,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${t}`);throw o.status=r.status,o}return r},{attempts:3})}var L=class{constructor(e){this.httpClient=e}async healthCheck(){return p(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return p(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return p(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,t){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",t);let s=await(await Rr(r.toString(),"versions",t)).json();return(Array.isArray(s)?s:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,i)=>Ar(i,a))}async installDevApplication(e){return p(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return p(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return p(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return p(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return p(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let r=t?`?service_name=${encodeURIComponent(t)}`:"";return p(await this.httpClient.get(`/admin-api/applications/${e}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let t=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return t?.data??t}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let t={...e,initializationParams:e.initializationParams??[]};return p(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e){return p(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return p(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return p(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return p(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return p(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let t=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(t,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return p(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/application`,t)}async getContextsWithExecutorsForApplication(e){let t=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(t)?t:t?.contexts??t?.data??[]}async uploadBlob(e){let t=new URLSearchParams;e.hash&&t.set("hash",e.hash),e.contextId&&t.set("context_id",e.contextId);let r=t.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",s=p(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:s.blob_id,size:s.size}}async deleteBlob(e){let t=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:t.blob_id,deleted:t.deleted}}async listBlobs(){return{blobs:p(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}blobPath(e,t){if(!t?.contextId)return`/admin-api/blobs/${e}`;let r=new URLSearchParams({context_id:t.contextId});return`/admin-api/blobs/${e}?${r.toString()}`}async getBlob(e,t){return this.httpClient.get(this.blobPath(e,t),{parse:"arrayBuffer"})}async getBlobInfo(e,t){let{headers:r}=await this.httpClient.head(this.blobPath(e,t)),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 p(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return p(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return p(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return p(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return p(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return p(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return p(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return p(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return p(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let t=await this.getNodeIdentity();return{namespaceId:e,publicKey:t.publicKey,account:t.accountId}}async performIntent(e,t){return p(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async queryContext(e,t){return p(await this.httpClient.post(`/admin-api/contexts/${e}/query`,t))}async getIntentRelay(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return p(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return p(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return p(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async admitJoin(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,t,{timeoutMs:65e3}))}async joinNamespace(e,t){let r=p(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,t,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,t,r={}){let{groupName:o,teamName:s}=r;return Nt({namespaceId:e,invitation:t,teamName:s},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:t}:{invitation:t,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(a=>a.namespaceId)})}async createGroupInNamespace(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return p(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return p(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return p(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,t){return p(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,t??{}))}async rescopeAccountDevice(e,t){return p(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/scope`,t))}async signWithAccountRoot(e){return p(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,t){return p(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/label`,t))}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,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,t))}async getGroupInfo(e){return p(await this.httpClient.get(`/admin-api/groups/${e}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return p(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(t?.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 t}async listMemberDevices(e,t={}){let r=new URLSearchParams;t.offset!==void 0&&r.set("offset",String(t.offset)),t.limit!==void 0&&r.set("limit",String(t.limit));let o=r.toString(),s=`/admin-api/groups/${e}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(s)}async sealToAccount(e,t,r){return p(await this.httpClient.post(`/admin-api/groups/${e}/accounts/${t}/seal`,r))}async listGroupContexts(e){return p(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members`,t)}async removeGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,t)}async updateMemberRole(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/role`,r)}async getMemberCapabilities(e,t){return p(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/capabilities`))}async setMemberCapabilities(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/capabilities`,r)}async setDefaultCapabilities(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,t)}async openToDelegatedExecution(e){let t=await this.getDefaultCapabilities(e);if(Fe(t,se.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:t};let r=We(t,se.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,t){let{capabilities:r}=await this.getMemberCapabilities(e,t);if(Fe(r,se.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=We(r,se.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,t,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,t)}async setTeeAdmissionPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,t)}async getTeeAdmissionPolicy(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return t.data??t}async setTeeAuthoringPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-authoring-policy`,t)}async disableTeeAuthoringPolicy(e){await this.httpClient.delete(`/admin-api/groups/${e}/settings/tee-authoring-policy`)}async setGroupMetadata(e,t){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,t)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/metadata`,r)}async getMemberMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/metadata`))?.data??null}async setContextMetadata(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${t}/metadata`,r)}async getContextMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${t}/metadata`))?.data??null}async syncGroup(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,t){return p(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return p(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let t=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${t}/migration-status`)}async getCascadeStatus(e){let t=encodeURIComponent(e);return p(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,t){let r=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,t);return r?.data??r}async listSubgroups(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return t.subgroups??t.data??[]}async detachContextFromGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,{})}async createGroupInvitation(e,t){return p(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return p(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return p(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return p(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return p(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 p(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${e}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,{})}async issueOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,t)}async issueNamespaceOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,t)}async setMemberAutoFollow(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function Fs(n){return Array.from(new TextEncoder().encode(n),e=>e.toString(16).padStart(2,"0")).join("")}function Ys(n){return new L(z(n))}function Xs(n){return new L(ye(n))}function Zs(n){return new L(Ve(n))}function Ot(n,e){return new L(n)}function Qe(n){try{let e=n.indexOf("#");if(e===-1)return null;let t=n.substring(e+1),r=new URLSearchParams(t),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 Ye(n,e){let t=new URLSearchParams;return t.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&t.set("permissions",e.permissions.join(",")),t.set("mode",e.mode),e.packageName&&(t.set("package-name",e.packageName),e.packageVersion&&t.set("package-version",e.packageVersion),e.registryUrl&&t.set("registry-url",e.registryUrl)),`${n.replace(/\/+$/,"")}/auth/login?${t.toString()}`}var Ht=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function A(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!0),e}function y(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function f(n,e,t){let r=n.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${r.length}`);let o=new Uint8Array(t);for(let s=0;s<t;s+=1)o[s]=Number.parseInt(r.slice(s*2,s*2+2),16);return o}function we(n,e){let t=n.trim();if(!/^[0-9a-fA-F]*$/.test(t)||t.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(t.slice(o*2,o*2+2),16);return r}function w(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function h(...n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}async function I(n,e){let t=[w(n.length),n];for(let r of e)t.push(w(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",h(...t)))}async function T(n){let e=f(n,"deviceSecret",32),t=h(Ht,e);try{return await crypto.subtle.importKey("pkcs8",t,{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 E(n){let e=f(n,"deviceSecret",32),t=h(Ht,e),r=await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!0,["sign"]),s=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(s.replace(/-/g,"+").replace(/_/g,"/")),a=>a.charCodeAt(0))}var xr=new TextEncoder().encode("calimero.auth.request.v1"),vr=new TextEncoder().encode("calimero.auth.request.body.v1");function $t(n){let e=new TextEncoder().encode(n);return h(A(e.length),e)}async function Xe(n=new Uint8Array(0)){let e=typeof n=="string"?new TextEncoder().encode(n):n;return I(vr,[e])}async function Ae(n){let e=await T(n.signerSecret),t=await Xe(n.body),r=w(n.issuedAt),o=w(n.expiresAt),s=new TextEncoder,a=await I(xr,[s.encode(n.method),s.encode(n.path),t,r,o]),i=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,a));return y(h($t(n.method),$t(n.path),t,r,o,i))}function Re(n){let e=we(n.credential,"credential"),t=we(n.request,"request signature"),r=n.session===void 0?new Uint8Array([0]):h(new Uint8Array([1]),we(n.session,"session statement"));return y(h(e,r,t))}function Cr(n){if(n==null)return new Uint8Array(0);if(typeof n=="string"||n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error(`a request-carried proof cannot commit to a ${n?.constructor?.name??typeof n} body: pass a string or bytes, or use a session for this call`)}function xe(n){let e=n.ttlSeconds??120,t=n.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=t();return Re({credential:n.credential,session:n.session,request:await Ae({method:r.method,path:r.path,body:Cr(r.body),issuedAt:o,expiresAt:o+e,signerSecret:n.signerSecret})})}}var ve=class extends Error{constructor(e,t,r,o){super(t),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Ze(n,e,t){let r=await n.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:t});if(r.error){let o=r.error;throw new ve(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var ie=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await Ze(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return t&&"output"in t?t.output:t}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 kr=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function qt(n){return n.type!==void 0&&kr.has(n.type)}var Sr=new Set(["token_reuse","token_revoked"]),Ir=new Set([401,403]);function Lt(n){let e=n.headers.get("x-auth-error");return!e||!Ir.has(n.status)?null:Sr.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.closed=!1;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken,this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(t,r)=>e.fetch?e.fetch(t,r):globalThis.fetch(t,r)}on(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(t)||o.push(t)}}off(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r],s=o.indexOf(t);s!==-1&&o.splice(s,1)}}onAppVersionChanged(e){let t=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",t),()=>this.off("event",t)}onMigrationEvent(e){let t=r=>{qt(r)&&e(r)};return this.on("event",t),()=>this.off("event",t)}emit(e,t){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(t)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=await this.getAuthToken(),t=`${this.baseUrl}/sse`,r=await this.fetchImpl(t,{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"},signal:this.abortController.signal});if(!r.ok){let o=Lt(r),s=await r.text().catch(()=>{});throw o?new _(o,r.status,r.statusText,t,r.headers,s):new S(r.status,r.statusText,t,r.headers,s)}if(!r.body)throw new Error("SSE response has no body");this.readStream(r.body).catch(o=>{if(this.closed)return;let s=o instanceof Error?o:new Error(String(o));this.emit("error",s),this.scheduleReconnect()})}catch(e){if(this.closed)return;let t=e instanceof Error?e:new Error(String(e));if(this.emit("error",t),t instanceof _)return;this.scheduleReconnect()}}}async readStream(e){let t=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:s,value:a}=await t.read();if(s)break;o+=r.decode(a,{stream:!0});let i=o.split(`
|
|
2
|
-
`);o=i.pop()??"";for(let c of i)if(c.startsWith("data:")){let l=c.slice(5).trim();l&&this.handleMessage(l)}}if(o+=r.decode(),o.startsWith("data:")){let s=o.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.closed)return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let t=JSON.parse(e);if(t.type==="connect"&&t.session_id){this.sessionId=t.session_id,this.emit("connect",t.session_id),(this.subscribedContextIds.size>0||this.subscribedGroupIds.size>0)&&this.sendSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]});return}if(!t.result)return;let r=t.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),s=new TextDecoder().decode(o);r=JSON.parse(s)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:r});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:r})}catch{}}async subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,r=(t.contextIds??[]).filter(s=>!this.subscribedContextIds.has(s)),o=(t.groupIds??[]).filter(s=>!this.subscribedGroupIds.has(s));for(let s of t.contextIds??[])this.subscribedContextIds.add(s);for(let s of t.groupIds??[])this.subscribedGroupIds.add(s);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}async unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,r=(t.contextIds??[]).filter(s=>this.subscribedContextIds.has(s)),o=(t.groupIds??[]).filter(s=>this.subscribedGroupIds.has(s));for(let s of t.contextIds??[])this.subscribedContextIds.delete(s);for(let s of t.groupIds??[])this.subscribedGroupIds.delete(s);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,t){try{let r=await this.getAuthToken(),o={};t.contextIds&&t.contextIds.length>0&&(o.contextIds=t.contextIds),t.groupIds&&t.groupIds.length>0&&(o.groupIds=t.groupIds);let s=await this.fetchImpl(`${this.baseUrl}/sse/subscription`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({id:this.sessionId,method:e,params:o})});if(!s.ok){let a=Lt(s),i=await s.text().catch(()=>{});this.emit("error",a?new _(a,s.status,s.statusText,`${this.baseUrl}/sse/subscription`,s.headers,i):new S(s.status,s.statusText,`${this.baseUrl}/sse/subscription`,s.headers,i))}}catch(r){this.emit("error",r instanceof Error?r:new Error(`SSE ${e} failed`))}}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 Ce=class Ce{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,t){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(t)||o.push(t)}}off(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r],s=o.indexOf(t);s!==-1&&o.splice(s,1)}}emit(e,t){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(t)}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 t=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${t}/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 t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);if(!t.result)return;let r=t.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),s=new TextDecoder().decode(o);r=JSON.parse(s)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:r});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:r})}catch{}}subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let r of t.contextIds??[])this.subscribedContextIds.add(r);for(let r of t.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.groupIds??[])})}unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let r of t.contextIds??[])this.subscribedContextIds.delete(r);for(let r of t.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.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,t){let r={};return e.length>0&&(r.contextIds=e),t.length>0&&(r.groupIds=t),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),Ce.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()}};Ce.MAX_BACKOFF_MS=3e4;var Y=Ce;function ke(){return{encode(n){return Array.from(new TextEncoder().encode(JSON.stringify(n)))},decode(n){return JSON.parse(new TextDecoder().decode(new Uint8Array(n)))}}}var ae=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,r=ke()){await Ze(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(t)})}subscribe(e,t,r=ke()){let o=s=>{let a=s;if(a.type!=="Ephemeral"||a.contextId!==e)return;let i=a.data;if(!i?.author)return;let c=!!i.removed,l={author:i.author,state:c||i.state===void 0?void 0:r.decode(i.state),removed:c};i.ageMs!==void 0&&(l.ageMs=i.ageMs),t(l)};return this.sse.on("event",o),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",o)}}};var Tr=new TextEncoder().encode("calimero.device.cert.v1"),Bt=new TextEncoder().encode("calimero.account.genesis.v1"),Er=new TextEncoder().encode("calimero.device.id.v1"),et=2;async function Kt(n,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let t=f(n,"account",32);return y(await I(Er,[t,e]))}async function tt(n){return I(Tr,[f(n.account,"account",32),f(n.device,"device",32),f(n.signPublicKey,"signPublicKey",32),f(n.kemPublicKey,"kemPublicKey",32),A(n.keyEpoch),A(n.deviceEpoch)])}function jt(n){return h(new Uint8Array([et]),n.rootPublicKey,A(0),f(n.account,"account",32),f(n.device,"device",32),f(n.signPublicKey,"signPublicKey",32),f(n.kemPublicKey,"kemPublicKey",32),A(n.keyEpoch),A(n.deviceEpoch),n.signature)}async function Vt(n){let e=await E(n.rootSecret),t=y(await I(Bt,[h(new Uint8Array([et]),e)])),r=0,o=await tt({account:t,device:n.device,signPublicKey:n.signPublicKey,kemPublicKey:n.kemPublicKey,keyEpoch:r,deviceEpoch:n.deviceEpoch}),s=await T(n.rootSecret),a=new Uint8Array(await crypto.subtle.sign("Ed25519",s,o)),i=jt({rootPublicKey:e,account:t,device:n.device,signPublicKey:n.signPublicKey,kemPublicKey:n.kemPublicKey,keyEpoch:r,deviceEpoch:n.deviceEpoch,signature:a});return y(i)}async function Se(n){let e=await E(n);return y(await I(Bt,[h(new Uint8Array([et]),e)]))}var nt=["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 Pr=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Dr=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),ce=256,Ft=ce/32,rt=(ce+Ft)/11;async function Wt(){let n=crypto.getRandomValues(new Uint8Array(ce/8));return zt(y(n),await Mr(n))}async function Jt(n){let e=Ur(n);return zt(y(await Nr(e)),e.join(" "))}async function B(n){return f(n,"secret",32),{secret:n,publicKey:y(await E(n)),accountId:await Se(n)}}async function ue(n){if(!n.nonce)throw new Error("nonce is required to sign an account link");let e=await T(n.rootSecret),t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,h(Pr,new TextEncoder().encode(n.nonce))));return Xt(t)}async function Ie(n){if(!n.nonce)throw new Error("nonce is required to sign an account login");let e=await T(n.rootSecret),t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,h(Dr,new TextEncoder().encode(n.nonce))));return Xt(t)}async function zt(n,e){return{...await B(n),phrase:e}}function Ur(n){let e=n.normalize("NFKD").toLowerCase().trim().split(/\s+/),t=e[0]===""?0:e.length;if(t!==rt)throw new Error(`recovery phrase must be ${rt} words, got ${t}`);return e}async function Mr(n){let e=Yt(n)+await Qt(n),t=[];for(let r=0;r<rt;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);t.push(nt[o])}return t.join(" ")}async function Nr(n){let e="";for(let r of n){let o=nt.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 t=new Uint8Array(ce/8);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(ce)!==await Qt(t))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return t}async function Qt(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",n));return Yt(e).slice(0,Ft)}function Yt(n){let e="";for(let t of n)e+=t.toString(2).padStart(8,"0");return e}function Xt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var _r=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Zt(n,e){f(e,"deviceSecret",32);let t=await T(e),r=h(_r,new TextEncoder().encode(n)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,r));return Gr(o)}async function Te(n,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":n.nonce,"X-Calimero-Signature":await Zt(n.nonce,e.deviceSecret)}}function Gr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Or="https://cloud.calimero.network";function ot(n,e){return typeof n.can_execute=="boolean"?n.can_execute:e}function st(n){return typeof n.tee_role=="string"&&n.tee_role!==""?n.tee_role:null}function it(n){return n.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}var Hr="x-mdma-session-refresh",$r="x-mdma-session-expires",K=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Or).replace(/\/+$/,""),this.onSession=e.onSession;let t=e.fetch;this.fetchImpl=t?(r,o)=>t(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 t=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(t)}async signInWithAccount(e){let t=await B(e),{nonce:r}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:t.publicKey,nonce:r,signature:await Ie({rootSecret:e,nonce:r})})}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 t=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(t)}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(t=>({namespaceId:String(t.namespace_id??t.group_id??""),groupId:String(t.group_id??t.namespace_id??""),haStatus:String(t.ha_status??"none"),haEnabledAt:t.ha_enabled_at??null,contexts:Array.isArray(t.contexts)?t.contexts:[],fleetReplicas:t.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,s=r.executor_account??null,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:s,status:String(r.status??""),authorshipReady:a,teeRole:st(r),canExecute:ot(r,a&&o!==null&&s!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null}})}async findExecutingRelay(e){let t=await this.getNamespaceRelays(e);return it(t)}async getNamespaceRouting(e){let t=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(t.namespace_id??e),nodes:(t.admitters??[]).map(r=>{let o=r.account??null,s=r.relay_url??null,a=r.fresh===!0,i=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:s,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:a,canAdmit:r.can_admit===!0,authorshipReady:i,teeRole:st(r),canExecute:ot(r,i&&s!==null&&o!==null&&a)}}),servable:t.servable===!0,writable:t.writable===!0}}async getRoutingChallenge(e){let t=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{namespaceId:String(t.namespace_id??e),nonce:String(t.nonce??""),expiresAtMs:Number(t.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let t=await this.getRoutingChallenge(e);return Te(t,this.routingCredential)}async getAccountRelaysChallenge(e){let t=await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{accountId:String(t.account_id??e),nonce:String(t.nonce??""),expiresAtMs:Number(t.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 t=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/relays`,{anonymous:!0,headers:await Te(t,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0}))}async findAdmitter(e,t){let{nodes:r}=await this.getNamespaceRouting(e),o=t&&t.length>0?new Set(t.map(s=>s.toLowerCase())):null;return r.find(s=>s.canAdmit&&(o===null||s.account!==null&&o.has(s.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(t=>{let r=t.relay_url??null,o=t.executor_account??null,s=(Array.isArray(t.namespaces)?t.namespaces:[]).map(a=>{let i=a;return{namespaceId:String(i.namespace_id??""),status:String(i.status??""),authorshipReady:i.authorship_ready===!0,teeRole:st(i),fresh:i.fresh===!0,confirmedAt:i.confirmed_at??null,lastSeenAt:i.last_seen_at??null}});return{peerId:String(t.peer_id??""),relayUrl:r,executorAccount:o,canExecute:ot(t,r!==null&&o!==null&&s.some(a=>a.authorshipReady)),namespaces:s}})}async claimNamespace(e,t){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:t}})}async enableNamespaceHa(e,t={}){let r=t.admitterAddrs===void 0?{}:{admitter_addrs:[...t.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:r})}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${t.toString()}`)}disableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${t.toString()}`)}async linkAccount(e){let t=await B(e),{nonce:r}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:t.accountId,rootPublicKey:t.publicKey,nonce:r,signature:await ue({rootSecret:e,nonce:r})})}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 t=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(t.account_id??e.accountId),linkedAt:t.linked_at??null,alreadyLinked:t.already_linked===!0}}static accountLinkHandoff(e){let t=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":e.callbackUrl});return{url:`${t}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let t=e??(typeof window>"u"?"":window.location.href);if(!t)return{};let r;try{r=new URL(t).hash}catch{return{}}let o=new URLSearchParams(r.replace(/^#/,"")),s=o.get("grant"),a=o.get("account"),i=o.get("error"),c={};return s&&(c.grant=s),a&&(c.accountId=a),i&&(c.error=i),c}async linkAccountWithGrant(e){let t=await B(e.rootSecret),r=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:t.publicKey,signature:await ue({rootSecret:e.rootSecret,nonce:e.grant})},anonymous:!0});return{accountId:String(r.account_id??t.accountId),linkedAt:r.linked_at??null,alreadyLinked:r.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(t=>({accountId:String(t.account_id??""),linkedAt:t.linked_at??null,hasRecoveryEnvelope:t.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,t,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 s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs),i;try{i=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:s.signal})}catch(c){throw new S(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(this.adoptRollingRefresh(i),!i.ok){let c=await i.text().catch(()=>{});throw new S(i.status,i.statusText,`${this.baseUrl}${t}`,i.headers,c)}if(!(r.parse==="none"||i.status===204))return await i.json()}adoptRollingRefresh(e){let t=e.headers.get(Hr);if(!t||!this.session)return;let r=e.headers.get($r),o=Number(r);this.session={sessionToken:t,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function qr(n){let e=n&&typeof n=="object"?n.data??n:void 0;if(!e||typeof e!="object")return[];let t=e.localPeerId,r=e.externalAddrs;if(typeof t!="string"||!t||!Array.isArray(r))return[];let o=`/p2p/${t}`,s=[];for(let a of r){if(typeof a!="string")continue;let i=a.trim();if(!i.startsWith("/"))continue;let c=i.endsWith(o)?i:`${i}${o}`;s.includes(c)||s.push(c)}return s}function Lr(n){if(n)return typeof n=="function"?n:xe(n)}var Br="mero-js:token-refresh";function Kr(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function at(n,e){try{let t=n.split(".");if(t.length===3){let r=t[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 Ee=class{constructor(e){this.tokenData=null;this.refreshPromise=null;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());let t=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=Lr(this.config.requestProof);this.httpClient=z({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.tokenStore?.setTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(t?"omit":void 0)}),this.authClient=Mt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Ot(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 ie({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 ae({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 Y({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let t=e||this.config.credentials;if(!t)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:t.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:t.username,password:t.password}},o=await this.authClient.generateTokens(r),s=o.data.access_token;return this.tokenData={access_token:s,refresh_token:o.data.refresh_token,expires_at:at(s,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,t=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=t;try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}withRefreshLock(e){let t=Kr();return t?t.request(Br,e):e()}async performTokenRefreshLocked(e){let t=this.tokenStore?.getTokens()??null;if(t?.refresh_token&&(this.tokenData=t,e&&t.access_token!==e))return t;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let r=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),o=r.data.access_token;return this.tokenData={access_token:o,refresh_token:r.data.refresh_token,expires_at:at(o,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Token refresh failed: ${r instanceof Error?r.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let t=e.expires_at||at(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:t},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return Qe(e)}static buildAuthLoginUrl(e,t){return Ye(e,t)}};function jr(n){return new Ee(n)}var ct=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Vr="mero-tokens",ut=class{constructor(e=Vr){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let t=JSON.parse(e);return t&&t.access_token&&t.refresh_token?{access_token:t.access_token,refresh_token:t.refresh_token,expires_at:typeof t.expires_at=="number"?t.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 Fr=new TextEncoder().encode("calimero.warrant.v2"),Wr=new TextEncoder().encode("calimero.warrant.intent.v1"),en=64,Jr="00".repeat(32);async function lt(n,e){let t=new TextEncoder().encode(JSON.stringify(e));return I(Wr,[new TextEncoder().encode(n),t])}async function Pe(n){let e=f(n.context,"context",32),t=f(n.authorAccount,"authorAccount",32),r=f(n.executor,"executor",32),o=f(n.appVersion??Jr,"appVersion",32),s=G(n.accountHeads,"accountHeads"),a=G(n.governanceFloor,"governanceFloor"),i=await T(n.deviceSecret),c=await E(n.deviceSecret),l=new TextEncoder().encode(n.method),d=await lt(n.method,n.argsJson),u=w(n.nonce),g=w(n.notAfter),b=await I(Fr,[e,t,c,r,o,l,d,w(s.length),...s,w(a.length),...a,u,g]),m=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},i,b));return y(h(e,t,c,r,o,A(l.length),l,d,A(s.length),...s,A(a.length),...a,u,g,m))}function G(n,e){let t=n??[];if(t.length>en)throw new Error(`${e} cites ${t.length} heads, over the ${en} a node accepts`);return t.map((r,o)=>f(r,`${e}[${o}]`,32))}var zr=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Qr=new TextEncoder().encode("calimero.context-creation.init.v1"),De=256;async function dt(n){let e=new TextEncoder().encode(JSON.stringify(n));return I(Qr,[e])}async function Yr(n){return I(zr,[n.group,n.seed,n.authorAccount,n.deviceKey,n.executor,n.applicationId,new Uint8Array([n.serviceName===null?0:1]),n.serviceName??new Uint8Array(0),new Uint8Array([n.name===null?0:1]),n.name??new Uint8Array(0),n.initHash,w(n.accountHeads.length),...n.accountHeads,w(n.governanceFloor.length),...n.governanceFloor,w(n.nonce),w(n.notAfter)])}async function Ue(n){let e=f(n.group,"group",32),t=n.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):f(n.seed,"seed",32),r=f(n.authorAccount,"authorAccount",32),o=f(n.executor,"executor",32),s=f(n.applicationId,"applicationId",32),a=tn(n.serviceName,"serviceName"),i=tn(n.name,"name"),c=G(n.accountHeads,"accountHeads"),l=G(n.governanceFloor,"governanceFloor"),d=await T(n.deviceSecret),u=await E(n.deviceSecret),g=await dt(n.initArgs),b=await Yr({group:e,seed:t,authorAccount:r,deviceKey:u,executor:o,applicationId:s,serviceName:a,name:i,initHash:g,accountHeads:c,governanceFloor:l,nonce:n.nonce,notAfter:n.notAfter}),m=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},d,b));return{warrant:y(h(e,t,r,u,o,s,nn(a),nn(i),g,A(c.length),...c,A(l.length),...l,w(n.nonce),w(n.notAfter),m)),seed:y(t)}}function rn(n){let e=n.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 t=new Uint8Array(e.length/2);for(let u=0;u<t.length;u+=1)t[u]=Number.parseInt(e.slice(u*2,u*2+2),16);let r=new DataView(t.buffer),o=0,s=(u,g)=>{if(o+u>t.length)throw new Error(`creation warrant ends inside ${g} (${t.length} bytes)`);let b=t.subarray(o,o+u);return o+=u,b},a=u=>r.getUint32(s(4,u).byteOffset,!0),i=u=>r.getBigUint64(s(8,u).byteOffset,!0),c=u=>{let g=s(1,u)[0];if(g===0)return null;if(g!==1)throw new Error(`${u} has option tag ${g}, expected 0 or 1`);let b=a(u);if(b>De)throw new Error(`${u} is ${b} bytes, over the ${De} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(s(b,u))},l=u=>{let g=a(u);if(g>64)throw new Error(`${u} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>y(s(32,u)))},d={group:y(s(32,"group")),seed:y(s(32,"seed")),authorAccount:y(s(32,"authorAccount")),deviceKey:y(s(32,"deviceKey")),executor:y(s(32,"executor")),applicationId:y(s(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(s(32,"initHash")),accountHeads:l("accountHeads"),governanceFloor:l("governanceFloor"),nonce:i("nonce"),notAfter:i("notAfter"),signature:y(s(64,"signature"))};if(o!==t.length)throw new Error(`creation warrant is ${t.length} bytes but its fields account for ${o}`);return d}function tn(n,e){if(n===void 0)return null;let t=new TextEncoder().encode(n);if(t.length>De)throw new Error(`${e} is ${t.length} UTF-8 bytes, over the ${De} a node accepts`);return t}function nn(n){return n===null?new Uint8Array([0]):h(new Uint8Array([1]),A(n.length),n)}var Xr=new TextEncoder().encode("calimero.governance-warrant.v1"),Zr=new TextEncoder().encode("calimero.governance-warrant.op.v1"),eo={group:0,root:1};async function pt(n){return I(Zr,[new Uint8Array([gt(n.kind)]),n.bytes])}async function to(n){return I(Xr,[n.scope,new Uint8Array([gt(n.kind)]),n.authorAccount,n.deviceKey,n.executor,n.opHash,w(n.accountHeads.length),...n.accountHeads,w(n.governanceFloor.length),...n.governanceFloor,w(n.nonce),w(n.notAfter)])}async function Me(n){let e=f(n.scope,"scope",32),t=f(n.authorAccount,"authorAccount",32),r=f(n.executor,"executor",32),o=G(n.accountHeads,"accountHeads"),s=G(n.governanceFloor,"governanceFloor"),a=gt(n.op.kind),i=await T(n.deviceSecret),c=await E(n.deviceSecret),l=await pt(n.op),d=await to({scope:e,kind:n.op.kind,authorAccount:t,deviceKey:c,executor:r,opHash:l,accountHeads:o,governanceFloor:s,nonce:n.nonce,notAfter:n.notAfter}),u=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},i,d));return y(h(e,new Uint8Array([a]),t,c,r,l,A(o.length),...o,A(s.length),...s,w(n.nonce),w(n.notAfter),u))}function on(n){let e=n.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 t=new Uint8Array(e.length/2);for(let u=0;u<t.length;u+=1)t[u]=Number.parseInt(e.slice(u*2,u*2+2),16);let r=new DataView(t.buffer),o=0,s=(u,g)=>{if(o+u>t.length)throw new Error(`governance warrant ends inside ${g} (${t.length} bytes)`);let b=t.subarray(o,o+u);return o+=u,b},a=u=>r.getUint32(s(4,u).byteOffset,!0),i=u=>r.getBigUint64(s(8,u).byteOffset,!0),c=u=>{let g=a(u);if(g>64)throw new Error(`${u} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>y(s(32,u)))},l=()=>{let u=s(1,"kind")[0];if(u===0)return"group";if(u===1)return"root";throw new Error(`governance warrant has kind ${u}, expected 0 (group) or 1 (root)`)},d={scope:y(s(32,"scope")),kind:l(),authorAccount:y(s(32,"authorAccount")),deviceKey:y(s(32,"deviceKey")),executor:y(s(32,"executor")),opHash:y(s(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:i("nonce"),notAfter:i("notAfter"),signature:y(s(64,"signature"))};if(o!==t.length)throw new Error(`governance warrant is ${t.length} bytes but its fields account for ${o}`);return d}function gt(n){let e=eo[n];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(n)}`);return e}var mt=300,j=class extends Error{constructor(t,r,o){super(`relay refused the intent (HTTP ${o}): ${t}`);this.reason=t;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},le=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,""),this.executorAccount=e.executorAccount;let t=e.fetch;this.fetchImpl=t?(r,o)=>t(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4}async describe(e){let t=await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`);return this.executorAccount=t.data.executorAccount,t.data}async execute(e,t,r={}){let o=this.executorAccount??(await this.describe(e)).executorAccount,s=await this.config.nonces.next(),a=this.config.ttlSeconds??mt,i=await Pe({context:e,authorAccount:this.config.authorAccount,executor:o,method:t,argsJson:r,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),deviceSecret:this.config.deviceSecret}),c=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:t,argsJson:r,warrant:i,authorProof:this.config.authorProof});return{rootHash:c.data.rootHash,returns:c.data.returns??null}}async describeCreation(e,t={}){let r=t.author?`?author=${encodeURIComponent(t.author)}`:"";return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/context-intents${r}`)).data}async createContext(e){let t=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!t.canCreateOnBehalf)throw new j(`the relay (${t.executorAccount}) has no standing to act for members of group ${t.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(t.authorMayCreate===!1)throw new j(`the author (${this.config.authorAccount}) may not create contexts in group ${t.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(t.executorAccount),o=e.initArgs??{},s=await this.config.nonces.next(),a=this.config.ttlSeconds??mt,{warrant:i}=await Ue({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),deviceSecret:this.config.deviceSecret}),c=await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/context-intents`,{warrant:i,authorProof:this.config.authorProof,initArgs:o});return{contextId:c.data.contextId,groupId:c.data.groupId,memberPublicKey:c.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`)).data}async govern(e){let t=await this.describeGovernance(e.groupId);if(!t.canActOnBehalf)throw new j(`the relay (${t.executorAccount}) has no standing to act for members of group ${t.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(t.executorAccount),o=await this.config.nonces.next(),s=this.config.ttlSeconds??mt,a=await Me({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r,nonce:o,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),deviceSecret:this.config.deviceSecret});return{groupId:(await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/governance-intents`,{warrant:a,authorProof:this.config.authorProof,op:y(e.op.bytes)})).data.groupId}}checkedExecutor(e){let t=this.config.executorAccount;if(t&&t.toLowerCase()!==e.toLowerCase())throw new Error(`configured executorAccount ${t} is not the relay's account ${e}; a warrant naming it would be unspendable`);return this.executorAccount=e,e}async json(e,t,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs),i;try{i=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:s.signal})}catch(c){throw new S(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(!i.ok){let c=await i.text().catch(()=>"");if(i.status===400||i.status===403){let l=no(c);throw new j(l,/nonce/i.test(l),i.status)}throw new S(i.status,i.statusText,`${this.baseUrl}${t}`,i.headers,c)}return await i.json()}};function no(n){if(!n)return"no reason given";try{let e=JSON.parse(n);for(let t of[e.error,e.message])if(typeof t=="string"&&t)return t}catch{}return n}function ht(n=1){let e=BigInt(n);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let t=e;return e+=1n,Promise.resolve(t)}}}function ft(n,e){let t=e??globalThis.localStorage;if(!t)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");return{next(){let r=t.getItem(n),o=0n;if(r!==null&&r!=="")try{let a=BigInt(r);a>0n&&(o=a)}catch{o=0n}let s=o+1n;return t.setItem(n,s.toString()),Promise.resolve(s)}}}var ro="Noise_NK_25519_AESGCM_SHA256",yt=32,oo=16,so=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),wt=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(ro),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await ao(h(this.h,e))}async mixKey(e){let[t,r]=await cn(this.ck,e);this.ck=t,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 t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:an(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:an(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return cn(this.ck,new Uint8Array)}};async function un(n,e,t){let r=await wt.initialize();await r.mixHash(e),await r.mixHash(n);let o=await io(t);return await r.mixHash(o.publicKey),await r.mixKey(await sn(o.privateKey,n)),{message1:h(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<yt+oo)throw new Error("Noise: message 2 is too short");let i=a.slice(0,yt);return await r.mixHash(i),await r.mixKey(await sn(o.privateKey,i)),{payload:await r.decryptAndHash(a.slice(yt)),split:await r.split()}}}}async function io(n){if(!n){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.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(so,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:co(t.x)}}async function sn(n,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n,256))}function an(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function ao(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function bt(n,e){let t=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function cn(n,e){let t=await bt(n,e),r=await bt(t,new Uint8Array([1])),o=await bt(t,h(r,new Uint8Array([2])));return[r,o]}function co(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var gn="/sealed/v2/handshake",mn="/sealed/v2",pe="application/vnd.calimero.sealed",At=2,uo=new TextEncoder().encode("calimero/sealed-http/v2"),de=16,lo=1+de+8,po=0,go=1,mo=2,ho=1+64*1024+16,fo=1024,yo=6e4,bo="calimero.tee-attest.transport-key.v1",wo=[101,204,205,304],hn=new TextEncoder,ge=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},X=class extends Error{constructor(t,r,o,s){super(o);this.status=t;this.code=r;this.retryAfterMs=s;this.name="SealedTransportError"}};async function fn(n,e){let t=await crypto.subtle.digest("SHA-256",h(hn.encode(bo),n,e));return new Uint8Array(t)}async function yn(n,e,t={}){if(t.applicationId===void 0!=(t.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 n.teeAttest({nonce:r,applicationId:t.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 s=f(o.transportPublicKey,"transportPublicKey",32),a=t.applicationHash?f(t.applicationHash,"applicationHash",32):new Uint8Array(32),i=y(await fn(a,s));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:i,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return s}function me(n){let e=n.fetch??((o,s)=>fetch(o,s)),t=`${n.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let s=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json();if(!a.data)throw new Error("The attestation response is malformed");return a.data}};return bn({baseUrl:n.baseUrl,transportPublicKey:()=>yn(r,n.verify,{applicationId:n.applicationId,applicationHash:n.applicationHash}),fetch:e})}function bn(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),r=`${e.origin}${t}`,o=n.fetch??((u,g)=>fetch(u,g)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,c=async()=>{try{return await dn(o,r,await ln(a))}catch(u){if(!(u instanceof ge)||!s)throw u;return a=Promise.resolve().then(s),dn(o,r,await ln(a))}},l=async()=>{let u=i??d(void 0),g=await u;if(Date.now()<g.renewAt)return[g,u];let b=d(u);return[await b,b]},d=u=>{if(i===u){let g=c();i=g,g.catch(()=>{i===g&&(i=void 0)})}return i};return async(u,g)=>{let b=new Request(u,g),m=new URL(b.url);if(m.origin!==e.origin||!m.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${m.href} outside the sealed node at ${n.baseUrl}`);let R=[];b.headers.forEach((D,N)=>R.push([N,D]));let k={method:b.method,path:m.pathname.slice(t.length)+m.search,headers:R},v=new Uint8Array(await b.arrayBuffer()),C=async D=>{let{requestId:N,header:V,envelope:F}=await Ro(D,k,v),W=await o(`${r}${mn}`,{method:"POST",headers:{"content-type":pe},body:F,signal:b.signal});if(W.headers.get("content-type")!==pe)throw await An(W);return vo(W,D.responseKey,V,N)},[P,$]=await l();try{return await C(P)}catch(D){if(!(D instanceof X)||D.code!=="unknown_session")throw D;return C(await d($))}}}async function ln(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function dn(n,e,t){try{return await pn(n,e,t)}catch(r){if(!(r instanceof X)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),pn(n,e,t)}}async function pn(n,e,t){let r=await un(t,uo),o=await n(`${e}${gn}`,{method:"POST",headers:{"content-type":pe},body:h(new Uint8Array([At]),t,r.message1)});if(o.headers.get("content-type")!==pe)throw await An(o);let s=await ko(o,fo);return Ao(r,s)}async function Ao(n,e){if(e[0]!==At)throw new Error("The handshake reply is malformed");let t;try{t=await n.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}=t;if(r.length!==de+4)throw new Error("The handshake reply is malformed");let s=r.slice(0,de),a=new DataView(r.buffer,r.byteOffset).getUint32(de,!1),[i,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:i,responseKey:c,nextRequestId:1,renewAt:Date.now()+a*1e3-yo,header(l){let d=new Uint8Array(lo);return d[0]=At,d.set(s,1),new DataView(d.buffer).setBigUint64(1+de,BigInt(l),!1),d}}}async function Ro(n,e,t){let r=n.nextRequestId;n.nextRequestId+=1;let o=n.header(r),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:wn(r,0),additionalData:o},n.requestKey,xo(e,t));return{requestId:r,header:o,envelope:h(o,new Uint8Array(s))}}function wn(n,e){let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setBigUint64(0,BigInt(n),!1),r.setUint32(8,e,!1),t}function xo(n,e){let t=hn.encode(JSON.stringify(n)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t.length,!1),h(r,t,e)}async function vo(n,e,t,r){if(!n.body)throw new Error("The sealed response has no body");let o=Co(n.body.getReader()),s=0,a=async()=>{let d=await o.next();if(!d)return null;let u;try{u=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:wn(r,s),additionalData:t},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:u[0],data:u.slice(1)}},i=await a();if(!i||i.kind!==po)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(i.data));if(wo.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let l=new ReadableStream({async pull(d){try{let u=await a();u?u.kind===go?d.enqueue(u.data):u.kind===mo?(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(u){d.error(u)}},cancel(){return o.cancel()}});return new Response(l,{status:c.status,headers:c.headers})}function Co(n){let e=new Uint8Array,t=async r=>{for(;e.length<r;){let{done:o,value:s}=await n.read();if(o)return!1;e=h(e,s)}return!0};return{async next(){if(!await t(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>ho)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>n.cancel()}}async function ko(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:s}=await t.read();if(o)return r;if(r=h(r,s),r.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function An(n){let e,t=`Sealed request refused: HTTP ${n.status}`;try{let s=await n.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new ge;let r=Number(n.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new X(n.status,e,t,o)}async function So(n){if(!n.sessionToken&&!n.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=new K({cloudBaseUrl:n.cloudBaseUrl,sessionToken:n.sessionToken,onSession:n.onSession,fetch:n.fetch,timeoutMs:n.timeoutMs});!n.sessionToken&&n.googleIdToken&&await e.signInWithGoogle(n.googleIdToken);let t=await e.getMyNamespaces(),r=Io(t,n.namespaceId),o=await e.getNamespaceRelays(r.namespaceId),s=it(o);if(!s)throw new Error(To(r,o));let a=new le({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:n.authorAccount,authorProof:n.authorProof,deviceSecret:n.deviceSecret,nonces:n.nonces??await Eo(n.deviceSecret),ttlSeconds:n.ttlSeconds,fetch:n.seal?me({baseUrl:s.relayUrl,verify:n.seal,fetch:n.fetch}):n.fetch,timeoutMs:n.timeoutMs});return{cloud:e,relay:a,namespaceId:r.namespaceId,namespace:r,relayInfo:s,execute:(i,c,l)=>a.execute(i,c,l)}}function Io(n,e){if(e){let t=n.find(r=>r.namespaceId===e);if(!t)throw new Error(`this account owns no namespace ${e}; it owns: ${n.map(r=>r.namespaceId).join(", ")||"(none)"}`);return t}if(n.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(n.length>1)throw new Error(`this account owns ${n.length} namespaces \u2014 pass namespaceId to say which: ${n.map(t=>t.namespaceId).join(", ")}`);return n[0]}function To(n,e){if(e.length===0)return n.haStatus==="enabled"?`namespace ${n.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${n.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let t=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(t.length===e.length)return`every node on namespace ${n.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+t.length===e.length?`every relay on namespace ${n.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 ${n.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`}async function Eo(n){let e=`mero-js:warrant-nonce:${y(await E(n))}`;try{return ft(e)}catch{return ht(1)}}var Po=/^[0-9a-f]{96}$/,Do=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function Rt(n){let e=Z(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,c)=>{let l=`allowedMeasurements[${c}]`;return Do.map(d=>Z([i?.[d]??""],`${l}.${d}`)[0]).join()}),r=[Z(n.allowedRtmr0??[],"allowedRtmr0"),Z(n.allowedRtmr1??[],"allowedRtmr1"),Z(n.allowedRtmr2??[],"allowedRtmr2"),Z(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.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(i=>i.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=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:c,reportDataSuffix:l,collateral:d})=>{let u=Mo(i),g=d??await n.fetchCollateral?.(u);if(!g)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let b;try{b=n.dcapVerify(u,g,Math.floor(s()/1e3))}catch(v){throw new Error(`The quote did not verify: ${v?.message??String(v)}`)}if(b.status==="Revoked"||!o.includes(b.status))throw new Error(`The platform's TCB status is ${b.status}, which is not accepted`);let m=Uo(b.report),R=[m.mrTd,m.rtMr0,m.rtMr1,m.rtMr2,m.rtMr3].map(v=>y(v));if(t.length>0&&!t.includes(R.join()))throw new Error(`The measurements (MRTD ${R[0]}, RTMR0-3 ${R.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(R[0]))throw new Error(`MRTD ${R[0]} is not an image this verifier trusts`);if([m.rtMr0,m.rtMr1,m.rtMr2,m.rtMr3].forEach((v,C)=>{let P=r[C];if(P.length>0&&!P.includes(y(v)))throw new Error(`RTMR${C} ${y(v)} is not one this verifier trusts`)}),y(m.reportData)!==`${c}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Z(n,e){return n.map(t=>{let r=t.trim().toLowerCase();if(!Po.test(r))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return r})}function Uo(n){let e=n.data;if(n.type==="td10"&&e)return e;if(n.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${n.type} quote, not a TDX one`)}function Mo(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var No=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function xt(n,{profile:e}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let t,r=n.map((o,s)=>{let a=o?.tag??`releases[${s}]`;if(o?.role!==void 0&&o.role!=="node")throw new Error(`${a} lists the measurements of a ${o.role}, not of a node image`);let i=o?.profiles?.[e];if(!i){let l=Object.keys(o?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${l})`)}let c=(i.allowed_tcb_statuses??["uptodate"]).map(l=>_o(l,a));return t=t===void 0?c:t.filter(l=>c.includes(l)),{mrtd:i.mrtd,rtmr0:i.rtmr0,rtmr1:i.rtmr1,rtmr2:i.rtmr2,rtmr3:i.rtmr3}});if(!t||t.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:t}}function _o(n,e){let t=No.find(r=>r.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var Rn=[{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"]}],xn=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Go="1.2.840.10045.2.1",Oo={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Ho={"P-256":32,"P-384":48},$o={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function vn(n,e,t){if(e+2>t)throw new Error("it is truncated");let r=n[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=n[e+1],s=e+2;if(o&128){let i=o&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<i;c+=1)o=o*256+n[s+c];s+=i}let a=s+o;if(a>t)throw new Error("it is truncated");return{tag:r,bytes:n,offset:e,start:s,end:a}}function te(n){let e=vn(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function U(n){let e=[];for(let t=n.start;t<n.end;){let r=vn(n.bytes,t,n.end);e.push(r),t=r.end}return e}function x(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function O(n){return n.bytes.slice(n.start,n.end)}function Ne(n){return n.bytes.slice(n.offset,n.end)}function ee(n){let e=O(x(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],r=0;for(let a of e)r=r*128+(a&127),a&128||(t.push(r),r=0);let o=t.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...t].join(".")}function qo(n){let e=new TextDecoder().decode(O(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=t??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(o[1]);t&&(s+=s<50?2e3:1900);let[a,i,c,l,d]=o.slice(2).map(Number);return Date.UTC(s,a-1,i,c,l,d)}function vt(n){try{let[e,t,r,...o]=U(x(te(n),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let s=U(x(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,c,l,d,u,g,...b]=s.slice(a);x(i,2,"The serial number");let m=ee(U(x(t,48,"The signature algorithm"))[0]);if(ee(U(x(c,48,"The signature algorithm"))[0])!==m)throw new Error("it names two different signature algorithms");let k=$o[m];if(!k)throw new Error(`it is signed with ${m}, not ECDSA with SHA-256 or SHA-384`);let[v,C]=U(x(d,48,"The validity")).map(qo);if(C===void 0)throw new Error("its validity is incomplete");let[P,$]=U(x(g,48,"The public key"));x($,3,"The public key");let[D,N]=U(x(P,48,"The key algorithm"));if(ee(D)!==Go)throw new Error("its key is not an elliptic-curve key");let V=Oo[ee(N)];if(!V)throw new Error("its key is on a curve other than P-256 or P-384");let F=new Map,W=b.find(qe=>qe.tag===163);if(W){let[qe]=U(W);for(let ar of U(x(qe,48,"The extensions"))){let J=U(x(ar,48,"An extension"));if(J.length===3)x(J[1],1,"An extension's critical flag");else if(J.length!==2)throw new Error("it has a malformed extension");let Le=ee(J[0]);if(F.has(Le))throw new Error(`it has extension ${Le} twice`);F.set(Le,O(x(J[J.length-1],4,"An extension value")))}}let Dt=O(x(r,3,"The signature"));if(Dt[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:Ne(e),signatureHash:k,signature:Dt.slice(1),issuer:Ne(x(l,48,"The issuer")),subject:Ne(x(u,48,"The subject")),notBefore:v,notAfter:C,spki:Ne(g),curve:V,extensions:F}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Cn(n){return U(x(te(n),48,"The list")).map(ee)}function Lo(n,e){let t=Ho[e],r=U(x(te(n),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(t*2);return r.forEach((s,a)=>{let i=O(x(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");o.set(i,a*t+t-i.length)}),o}async function _e(n,e,t,r,o){let s;try{s=Lo(r,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,o)}function M(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function Ct(n,e){let t=[...n.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||n.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return M(t[0][1],e)}var Bo="2.5.29.17",Ko="2.5.29.37",jo="1.3.6.1.5.5.7.3.3",Vo="1.3.6.1.4.1.57264.1.8",Fo="1.3.6.1.4.1.57264.1.1",Wo=134,Jo=12,zo=48,Qo=new TextEncoder,ne=n=>new TextDecoder().decode(n);async function kn(n,e,t,r){let{base64Signature:o,cert:s,rekorBundle:a}=es(e),i=a.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=M(o,"The bundle signature"),l=Ct(ne(M(s,"The bundle certificate")),"The bundle certificate"),d=vt(l),u=xn.find(C=>C.logId===i.logID.toLowerCase());if(!u)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let g=Qo.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await _e(M(u.publicKey,"The Rekor key"),"P-256","SHA-256",M(a.SignedEntryTimestamp,"The signed entry timestamp"),g))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let m=i.integratedTime*1e3;if(!Tn(m,u.validFor))throw new Error(`Rekor log ${u.baseUrl} was not in use at ${he(m)}, when the entry says it was logged`);let R=ts(i.body),k=y(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(R.hash!==k)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!kt(M(R.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let v=Ct(ne(M(R.publicKey,"The logged certificate")),"The logged certificate");if(!kt(v,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await _e(d.spki,"P-256","SHA-256",c,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await Yo(d,m),Zo(d,t),{integratedTime:i.integratedTime}}async function Yo(n,e){if(!In(n,e))throw new Error(`The signing certificate was valid ${he(n.notBefore)} to ${he(n.notAfter)}, not at ${he(e)} when Rekor logged it`);let t=[];for(let r of Rn){let o=r.certChain.map(a=>vt(M(a,"A Fulcio certificate")));if(!await Sn(n,o[0]))continue;let s=await Xo(o,r.validFor,e);if(!s)return;t.push(`${r.uri} (valid from ${r.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${he(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Xo(n,e,t){if(!Tn(t,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of n.entries()){if(!In(o,t))return`its certificate ${r} was not valid then`;let s=n[r+1]??o;if(!await Sn(o,s))return`its certificate ${r} is not signed by the next`}}async function Sn(n,e){return kt(n.issuer,e.subject)?_e(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function Zo(n,e){let t=n.extensions.get(Bo);if(!t)throw new Error("The signing certificate names no identity");let r=U(x(te(t),zo,"The subject alternative name")),o=r.filter(l=>l.tag===Wo).map(l=>ne(O(l)));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 s=n.extensions.get(Vo),a=n.extensions.get(Fo),i=s?ne(O(x(te(s),Jo,"The OIDC issuer"))):a?ne(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let c=n.extensions.get(Ko);if(!c||!Cn(c).includes(jo))throw new Error("The signing certificate is not for code signing")}function es(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,r=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.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 t}function ts(n){let e;try{e=JSON.parse(ne(M(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.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:t.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function In(n,e){return n.notBefore<=e&&e<=n.notAfter}function Tn(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function he(n){return new Date(n).toISOString()}function kt(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var St=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"}),ns=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Pn="https://cloud.calimero.network";async function Dn(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await kn(r,e,{identity:t.identity??St.identity,issuer:t.issuer??St.issuer},t.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 s=Object.values(o.profiles??{}),a=i=>ns.every(c=>/^[0-9a-f]{96}$/i.test(String(i?.[c])));if(typeof o.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&o.tag!==t.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${t.expectedVersion}`);return o}async function Un(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let r;try{r=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function Mn(n){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(n);if(!e)throw new Error(`${JSON.stringify(n)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function Nn(n,e={}){let t=await Gn(n,e.fetch??fetch);if(t===void 0)throw new Error(`${_n(n)} 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 t}function _n(n){return`${n.replace(/\/+$/,"")}/admin-api/tee/info`}async function Gn(n,e){let t=_n(n),r=await e(t,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(a=>a?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${t} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${t} did not name the node's image`);return Mn(o)}function On(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${fe(e,"version")}`}async function Hn(n){let e=fe(n.minReleaseVersion,"minReleaseVersion"),t=fe(n.release?.version,"The release version"),r=await Dn(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(os(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return xt([r],{profile:n.profile})}function $n(n){return fe(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let r=await Hn({release:await n.release(),profile:n.profile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return Rt({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...r})(t)},{includeCollateral:!0})}function rs(n){let{baseUrl:e,releaseSource:t,releaseVersion:r,applicationId:o,applicationHash:s,fetch:a,...i}=n;r!==void 0&&fe(r,"releaseVersion");let c=a??((d,u)=>fetch(d,u));return me({baseUrl:e,verify:$n({...i,release:async()=>{let d=r===void 0?await Nn(e,{fetch:c}):await Gn(e,c)??r;return typeof t=="function"?t({baseUrl:e,version:d,fetch:c}):Un(On(t??Pn,d),{fetch:c})}}),applicationId:o,applicationHash:s,fetch:c})}var qn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function fe(n,e){let t=typeof n=="string"?qn.exec(n):null,r=t?.[4];if(!t||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function os(n,e){let[t,r]=En(n),[o,s]=En(e);for(let c=0;c<3;c+=1)if(t[c]!==o[c])return t[c]<o[c]?-1:1;if(r===void 0||s===void 0)return r===s?0:r===void 0?1:-1;let a=r.split("."),i=s.split(".");for(let c=0;c<Math.max(a.length,i.length);c+=1){let[l,d]=[a[c],i[c]];if(l===void 0||d===void 0)return l===void 0?-1:1;let[u,g]=[/^\d+$/.test(l),/^\d+$/.test(d)],b=u&&g?Math.sign(Number(l)-Number(d)):u!==g?u?-1:1:l<d?-1:l>d?1:0;if(b!==0)return b}return 0}function En(n){let e=qn.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var ss={Admin:0,Member:1,ReadOnly:2},Oe={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4},It={GroupCreated:0,GroupReparented:1,GroupDeleted:2},Ln=new Uint8Array(32),Ge=A(0);function Bn(n){let e=ss[n];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(n)}`);return new Uint8Array([e])}function H(n){return new Uint8Array([n])}function Kn(n,e){return{kind:"group",bytes:h(H(Oe.MemberAdded),f(n,"member",32),Bn(e))}}function jn(n){return{kind:"group",bytes:h(H(Oe.MemberRemoved),f(n,"member",32),Ln,Ge)}}function Vn(n){return{kind:"group",bytes:h(H(Oe.MemberLeft),f(n,"member",32),Ln,Ge)}}function Fn(n,e){return{kind:"group",bytes:h(H(Oe.MemberRoleSet),f(n,"member",32),Bn(e))}}function Wn(n){return{kind:"root",bytes:h(H(It.GroupCreated),f(n.groupId,"groupId",32),f(n.parentId,"parentId",32),H(n.restricted?1:0),f(n.admin,"admin",32))}}function Jn(n,e){return{kind:"root",bytes:h(H(It.GroupReparented),f(n,"childGroupId",32),f(e,"newParentId",32))}}function zn(n){return{kind:"root",bytes:h(H(It.GroupDeleted),f(n,"rootGroupId",32),Ge,Ge)}}var Et=15,is=new TextEncoder().encode("calimero.namespace.v1"),as=0,Qn={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Tt(n,e){if(n.length!==32)throw new Error(`${e} must be 32 bytes, got ${n.length}`);return new Uint8Array(n)}function Yn(n,e){if(n==null)return new Uint8Array([0]);if(n.length!==32)throw new Error(`${e} must be 32 bytes, got ${n.length}`);return h(new Uint8Array([1]),new Uint8Array(n))}function Xn(n){let e=new TextEncoder().encode(n);return h(A(e.length),e)}function He(n){let e=n.invitation,t=e.admitters??[],r=n.admitter_addrs??[];return h(Tt(e.inviter_identity,"inviter_identity"),Tt(e.group_id,"group_id"),w(e.expiration_timestamp),Tt(e.secret_salt,"secret_salt"),new Uint8Array([e.invited_role]),A(t.length),...t.map((o,s)=>f(o,`admitters[${s}]`,32)),Xn(n.inviter_signature),n.inviter_account?h(new Uint8Array([1]),f(n.inviter_account,"inviter_account",32)):new Uint8Array([0]),A(r.length),...r.map(Xn),Yn(n.application_id,"application_id"),Yn(n.app_key,"app_key"))}async function Zn(n){let e=n.parentOpHashes??[],t=f(n.credential,"credential",n.credential.length/2),r=BigInt(n.invitation.invitation.expiration_timestamp??0)!==0n,o=n.joinedAt??BigInt(Math.floor(Date.now()/1e3)),s=r?h(new Uint8Array([Qn.MemberJoinedAt]),f(n.member,"member",32),He(n.invitation),w(o),t):h(new Uint8Array([Qn.MemberJoined]),f(n.member,"member",32),He(n.invitation),t),a=h(new Uint8Array([as]),s),i=await T(n.deviceSecret),c=await E(n.deviceSecret),l=h(new Uint8Array([Et]),f(n.namespaceId,"namespaceId",32),A(e.length),...e.map((g,b)=>f(g,`parentOpHashes[${b}]`,32)),c,w(n.nonce),a),d=new Uint8Array(await crypto.subtle.sign("Ed25519",i,h(is,l))),u=new Uint8Array([0]);return y(h(l,d,u))}var cs=new TextEncoder().encode("calimero.auth.login.v1"),er={webOrigin:0,codeSigningId:1,cli:2};function tr(n){let e=new TextEncoder;switch(n.kind){case"webOrigin":return e.encode(n.origin);case"codeSigningId":return e.encode(n.id);case"cli":return new Uint8Array(0)}}function us(n){return h(Uint8Array.from([er[n.kind]]),tr(n))}function ls(n){let e=Uint8Array.from([er[n.kind]]);if(n.kind==="cli")return e;let t=tr(n);return h(e,A(t.length),t)}async function $e(n){let e=f(n.node,"node",32),t=f(n.challenge,"challenge",32),r=f(n.sessionKey,"sessionKey",32),o=await T(n.deviceSecret),s=await E(n.deviceSecret),a=w(n.issuedAt),i=w(n.expiresAt),c=await I(cs,[e,us(n.audience),t,r,s,a,i]),l=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},o,c));return y(h(e,ls(n.audience),t,r,s,a,i,l))}var ds=300;async function Pt(){let n=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await E(n)),secret:n}}function ps(n){switch(n.kind){case"webOrigin":return n.origin;case"codeSigningId":return n.id;case"cli":return"cli"}}async function nr(n){let e=n.nodeUrl.replace(/\/+$/,""),t=n.timeoutMs??1e4,r=async(g,b)=>{let m=new AbortController,R=setTimeout(()=>m.abort(),t),k;try{let C={...b,signal:m.signal};k=n.fetch?await n.fetch(`${e}${g}`,C):await globalThis.fetch(`${e}${g}`,C)}catch(C){throw new S(0,C instanceof Error?C.name:"NetworkError",`${e}${g}`,new Headers,C instanceof Error?C.message:String(C))}finally{clearTimeout(R)}let v=await k.text().catch(()=>"");if(!k.ok)throw new S(k.status,k.statusText,`${e}${g}`,k.headers,v);return v?JSON.parse(v):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),s=o.challenge??o.data?.challenge;if(!s)throw new Error("the node issued no challenge");let a=await Pt(),i=Math.floor(Date.now()/1e3),c=await $e({node:n.node,audience:n.audience,challenge:s,sessionKey:a.publicKey,issuedAt:i,expiresAt:i+(n.ttlSeconds??ds),deviceSecret:n.deviceSecret}),l=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:a.publicKey,client_name:n.clientName??ps(n.audience),timestamp:i,provider_data:{challenge:s,login_statement:c,account_proof:n.accountProof}})}),d=l.access_token??l.data?.access_token,u=l.refresh_token??l.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:u??"",sessionKey:a.publicKey,sessionSecret:a.secret}}var rr=[2428,2429,2528,2529],gs="localhost",ms=2e3;function or(n){return`http://${gs}:${n}`}function sr(n,e){let t=n.endsWith("/")?n:`${n}/`;return new URL(e,t).toString()}async function ir(n,e={}){let{timeoutMs:t=ms,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,s=()=>o.abort(),a=r;a&&a.addEventListener("abort",s,{once:!0});let i=setTimeout(()=>o.abort(),t);try{let c=sr(n,"admin-api/health"),l=await fetch(c,{method:"GET",signal:o.signal});if(!l.ok)return!1;try{let d=await l.json(),u=d?.data?.status!==void 0?d?.data?.status:d?.status;return u===void 0?!0:typeof u=="string"&&u.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(i),a&&a.removeEventListener("abort",s)}}async function hs(n={}){let{ports:e=rr,timeoutMs:t,signal:r}=n;return(await Promise.all(e.map(async s=>{let a=or(s);return await ir(a,{timeoutMs:t,signal:r})?a:null}))).filter(s=>s!==null)}export{L as AdminApiClient,q as AuthApiClient,_ as AuthRevokedError,se as CAPABILITIES,K as CloudClient,rr as DEFAULT_LOCAL_NODE_PORTS,Pn as DEFAULT_RELEASE_MIRROR,ae as EphemeralClient,gn as HANDSHAKE_PATH,S as HTTPError,j as IntentRefusedError,ut as LocalStorageTokenStore,ct as MemoryTokenStore,Ee as MeroJs,St as NODE_RELEASE_SIGNER,le as RelayClient,ie as RpcClient,ve as RpcError,pe as SEALED_CONTENT_TYPE,mn as SEALED_PATH,Et as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,X as SealedTransportError,Q as SseClient,ge as StaleTransportKeyError,re as WebHttpClient,Y as WsClient,Se as accountForRoot,Jt as accountRootFromPhrase,B as accountRootFromSecret,qr as admitterAddrsFromNetworkStatus,Ye as buildAuthLoginUrl,Re as callerProof,ze as classifyError,On as cloudNodeReleaseUrl,Be as combineSignals,Ar as compareSemver,So as connectCloud,Zs as createAdminApiClient,Ot as createAdminApiClientFromHttpClient,me as createAttestedSealedFetch,Ms as createAuthApiClient,Mt as createAuthApiClientFromHttpClient,Ys as createBrowserAdminApiClient,Ds as createBrowserAuthApiClient,z as createBrowserHttpClient,je as createHttpClient,ft as createLocalStorageNonceSource,ht as createMemoryNonceSource,jr as createMeroJs,Xs as createNodeAdminApiClient,Us as createNodeAuthApiClient,ye as createNodeHttpClient,xe as createProofSigner,Rt as createQuoteVerifier,gr as createRetryableMethod,bn as createSealedFetch,rs as createSignedReleaseSealedFetch,$n as createSignedReleaseVerifier,Ke as createTimeoutSignal,Ve as createUniversalHttpClient,dt as creationInitHash,tt as deviceCertPayload,hs as discoverLocalNodes,He as encodeSignedInvitation,yn as fetchAttestedTransportKey,Un as fetchNodeRelease,Nn as fetchNodeReleaseVersion,Wt as generateAccountRoot,Pt as generateSessionKey,pt as governanceOpHash,Wn as groupCreatedOp,zn as groupDeletedOp,Jn as groupReparentedOp,Fe as hasCap,Fs as hexEncodeUtf8,lt as intentHash,yr as isSettled,ke as jsonCodec,or as localNodeUrl,nr as login,Kn as memberAddedOp,Vn as memberLeftOp,jn as memberRemovedOp,Fn as memberRoleSetOp,Kt as mintDeviceId,sr as nodeEndpoint,Mn as nodeReleaseVersionFromImage,Qe as parseAuthCallback,rn as parseCreationWarrant,on as parseGovernanceWarrant,ir as probeNodeHealth,Nt as redeemInvitation,Xe as requestBodyHash,Te as routingProofHeaders,$s as shouldRetain,ue as signAccountLink,Ie as signAccountLogin,Ue as signCreationWarrant,Vt as signDeviceCert,Me as signGovernanceWarrant,$e as signLoginStatement,Zn as signMemberJoinOp,Ae as signRequest,Zt as signRoutingChallenge,Pe as signWarrant,fn as transportKeyBinding,Hn as trustSignedRelease,xt as trustedMeasurementsFromReleases,Dn as verifySignedNodeRelease,We as withCap,be as withRetry,_s as withoutCap};
|
|
1
|
+
function je(n){let e=n.filter(Boolean);if(e.length===0)return;let t=AbortSignal;if(typeof t.any=="function")try{return t.any(e)}catch{}let r=new AbortController,o=s=>{r.abort(s.target.reason);for(let a of e)a.removeEventListener("abort",o)};for(let s of e){if(s.aborted)return AbortSignal.abort(s.reason);s.addEventListener("abort",o,{once:!0})}return r.signal}function Fe(n){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(n);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},n),e.signal}var mr=new Set(["token_reuse","token_revoked"]);function hr(n){if(n)try{let e=JSON.parse(n),t=e?.error;if(typeof t=="string"&&t.trim()!=="")return t;let r=t?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var S=class extends Error{constructor(t,r,o,s,a){let i=hr(a)??(t===0&&a?.trim()?a.trim():void 0);super(i?`HTTP ${t} ${r}: ${i}`:`HTTP ${t} ${r}`);this.status=t;this.statusText=r;this.url=o;this.headers=s;this.bodyText=a;this.name="HTTPError";this.explanation=i}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:_t(this.headers),bodyText:this.bodyText}}},_=class extends S{constructor(t,r,o,s,a,i){super(r,o,s,a,i);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${r} ${o}`}};function _t(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}function fr(n){try{return new URL(n).pathname}catch{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)}}var oe=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,r){return this.request(e,{...r,method:"POST",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,t,r){return this.request(e,{...r,method:"PUT",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}async patch(e,t,r){return this.request(e,{...r,method:"PATCH",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,t){let r=await this.makeRequest(e,{...t,method:"HEAD",parse:"response"});return{headers:_t(r.headers),status:r.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,r=0,o){let a=this.buildUrl(e),i=o??Date.now(),c=this.createAbortSignal(t),l=await this.buildHeaders(t?.headers),d;l instanceof Headers?(d={},l.forEach((f,x)=>{d[x]=f})):d=l;let u={method:t?.method||"GET",headers:d},g=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!g||t?.body!==void 0&&g&&r===0)&&(u.body=t.body);let b;if(r>0&&o!==void 0){let f=t?.timeoutMs||this.transport.timeoutMs;if(f){let x=Date.now()-i,k=Math.max(0,f-x);b=this.createAbortSignal({...t,timeoutMs:k})}else b=this.createAbortSignal(t)}else b=c;if(b&&(u.signal=b),this.transport.credentials!==void 0&&(u.credentials=this.transport.credentials),t?.mode!==void 0&&(u.mode=t.mode),t?.cache!==void 0&&(u.cache=t.cache),t?.redirect!==void 0&&(u.redirect=t.redirect),t?.referrer!==void 0&&(u.referrer=t.referrer),t?.referrerPolicy!==void 0&&(u.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(u.integrity=t.integrity),t?.keepalive!==void 0&&(u.keepalive=t.keepalive),this.transport.getProof){let f=await this.transport.getProof({method:u.method??"GET",path:fr(a),body:u.body});f&&(d["X-Calimero-Proof"]=f)}try{let f=await this.transport.fetch(a,u);if(!f.ok){let x=await this.getBodyText(f),k=new S(f.status,f.statusText,a,f.headers,x),v=f.headers.get("x-auth-error");if((f.status===401||f.status===403)&&v&&mr.has(v)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new _(v,f.status,f.statusText,a,f.headers,x)}let C=t?.signal?.aborted===!0;if(f.status===401&&this.transport.refreshToken&&v==="token_expired"&&r<1&&!g&&!C)try{let I=this.refreshTokenPromise;I||(I=this.transport.refreshToken(),this.refreshTokenPromise=I);let q=await I;if(!q||q.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 T=this.onTokenRefreshPromise;T||(T=this.transport.onTokenRefresh(q),this.onTokenRefreshPromise=T),await T,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let N=t?.timeoutMs||this.transport.timeoutMs;if(N&&o!==void 0){let V=Date.now()-i;if(N-V<=0)throw k}return this.makeRequest(e,t,r+1,i)}catch(I){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,I instanceof Error&&I.message.includes("onTokenRefresh")?I:k}throw k}return this.parseResponse(f,t?.parse)}catch(f){throw f instanceof S||f instanceof Error&&f.message.includes("onTokenRefresh")?f:new S(0,"Network Error",a,new Headers,f instanceof Error?f.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let t=this.transport.baseUrl;return e.startsWith("/")?`${t.endsWith("/")?t.slice(0,-1):t}${e}`:`${t.endsWith("/")?t:`${t}/`}${e}`}createAbortSignal(e){let t=[];this.transport.defaultAbortSignal&&t.push(this.transport.defaultAbortSignal),e?.signal&&t.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&t.push(Fe(r)),t.length>0?je(t):void 0}async buildHeaders(e){let t={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(t.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{t[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{t[r]=o}):Object.assign(t,e)),t}async parseResponse(e,t){switch(t){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 t=await e.text();return t.length>65536?t.slice(0,65536)+"...":t}catch{return""}}};function Ve(n){return new oe(n)}function Q(n){let e={fetch:(t,r)=>n.fetch?n.fetch(t,r):globalThis.fetch(t,r),baseUrl:n.baseUrl,getAuthToken:n.getAuthToken,getProof:n.getProof,onTokenRefresh:n.onTokenRefresh,refreshToken:n.refreshToken,onAuthRevoked:n.onAuthRevoked,defaultHeaders:n.defaultHeaders,timeoutMs:n.timeoutMs,credentials:n.credentials,defaultAbortSignal:n.defaultAbortSignal};return Ve(e)}function we(n){let e=n.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,s)=>globalThis.fetch(o,s):(o,s)=>e(o,s),baseUrl:n.baseUrl,getAuthToken:n.getAuthToken,getProof:n.getProof,onTokenRefresh:n.onTokenRefresh,refreshToken:n.refreshToken,onAuthRevoked:n.onAuthRevoked,defaultHeaders:n.defaultHeaders,timeoutMs:n.timeoutMs,credentials:n.credentials,defaultAbortSignal:n.defaultAbortSignal};return Ve(r)}function We(n){return typeof window<"u"?Q(n):we(n)}function yr(n,e){if(e<=0)return!1;let r=n?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=n;if("status"in o&&typeof o.status=="number"){let s=o.status;return s>=500||s===429}return r==="TypeError"}function br(n){let t=250*Math.pow(2,n-1),r=(Math.random()-.5)*.4*t;return Math.max(0,t+r)}async function Ae(n,e={}){let{attempts:t=3}=e,r;for(let o=1;o<=t;o++)try{return await n(o)}catch(s){if(r=s,!yr(r,t-o))throw r;let a=br(o),l=r.headers?.get?.("Retry-After");if(l){let d=parseInt(l,10);if(!isNaN(d))a=Math.max(a,d*1e3);else{let u=new Date(l);if(!isNaN(u.getTime())){let g=Math.max(0,u.getTime()-Date.now());a=Math.max(a,Math.min(g,6e4))}}}await new Promise(d=>setTimeout(d,a))}throw r||new Error("Retry failed without error")}function wr(n,e={}){return async(...t)=>Ae(()=>n(...t),e)}var L=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 t=await this.validateTokenGet(e);return{valid:t.status===200,headers:t.headers,status:t.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let t=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:t.status,headers:t.headers}}async revokeTokens(e){let t=await this.httpClient.post("/admin/revoke",e);if(!t.data)throw new Error("Revoke tokens response data is null");return t.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 t=await this.httpClient.post("/admin/keys",e);if(!t.data)throw new Error("Create root key response data is null");return t.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${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,t){return this.httpClient.delete(`/admin/keys/${e}/clients/${t}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,t){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:t.add,remove:t.remove})}};var se=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 Hs(n){let e=new se;return new L(e)}function $s(n){let e=new se;return new L(e)}function qs(n){let e=new se;return new L(e)}function Gt(n,e){return new L(n)}var ie={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};function Je(n,e){let t=e>>>0;return(n&t)>>>0===t}function ze(n,e){return(n|e)>>>0}function Ks(n,e){return(n&~e)>>>0}var Ar={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 xr(n){switch(n){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 n>=500&&n<600?"server":n>=400&&n<500?"invalid":"unknown"}function Rr(n){if(!n||typeof n!="object")return;let e=n;for(let t of[e.status,e.response?.status,e.statusCode])if(typeof t=="number"&&Number.isFinite(t))return t}function Qe(n,e="Request failed"){if(typeof n=="string")return n.trim()||e;if(!n||typeof n!="object")return e;let t=n;for(let r of[t.explanation,t.response?.data?.error,t.response?.data?.message,t.data?.message,t.error,t.message])if(typeof r=="string"&&r.trim())return r;return e}function Ye(n){let e=Rr(n),t;return e!==void 0?t=xr(e):n instanceof TypeError?t="unreachable":t="unknown",{kind:t,status:e,retryable:Ar[t],message:Qe(n)}}function vr(n){return n.status!=="failed"||!n.retryable}function Vs(n){return!vr(n)}function Cr(n){let e=n.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 kr(n,e){let{kind:t,status:r}=Ye(n),o=Cr(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}:t==="unavailable"?{reason:"no-one-online",retryable:!0}:t==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function Ot(n,e){let{namespaceId:t,invitation:r,teamName:o}=n,s=null;try{await e.join(t,r)}catch(d){s=d}let a=null;try{a=(await e.memberships()).includes(t)}catch{a=null}if(s===null)return{status:"joined",namespaceId:t,teamName:o};if(a===!0)return{status:"already-member",namespaceId:t,teamName:o};let i=Qe(s,"Could not join. Check the invitation."),{reason:c,retryable:l}=kr(s,i);return{status:"failed",namespaceId:t,message:i,reason:c,retryable:l}}function p(n){return n?.data}function Sr(n,e){let[t,r]=Ht(n),[o,s]=Ht(e),a=t.split("."),i=o.split("."),c=Math.max(a.length,i.length);for(let g=0;g<c;g++){let b=$t(a[g]??"0",i[g]??"0");if(b!==0)return b}if(r===void 0&&s===void 0)return 0;if(r===void 0)return 1;if(s===void 0)return-1;let l=r.split("."),d=s.split("."),u=Math.max(l.length,d.length);for(let g=0;g<u;g++){if(g>=l.length)return-1;if(g>=d.length)return 1;let b=$t(l[g],d[g]);if(b!==0)return b}return 0}function Ht(n){let e=n.split("+",1)[0],t=e.indexOf("-");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function $t(n,e){let t=/^\d+$/.test(n),r=/^\d+$/.test(e);if(t&&r){let o=Number(n)-Number(e);return o<0?-1:o>0?1:0}return t?-1:r?1:n<e?-1:n>e?1:0}async function Er(n,e,t){return Ae(async()=>{let r=await fetch(n,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${t}`);throw o.status=r.status,o}return r},{attempts:3})}var K=class{constructor(e){this.httpClient=e}async healthCheck(){return p(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return p(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return p(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,t){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",t);let s=await(await Er(r.toString(),"versions",t)).json();return(Array.isArray(s)?s:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,i)=>Sr(i,a))}async installDevApplication(e){return p(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return p(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return p(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return p(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return p(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let r=t?`?service_name=${encodeURIComponent(t)}`:"";return p(await this.httpClient.get(`/admin-api/applications/${e}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let t=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return t?.data??t}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let t={...e,initializationParams:e.initializationParams??[]};return p(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e){return p(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return p(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return p(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return p(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return p(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let t=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(t,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return p(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/application`,t)}async getContextsWithExecutorsForApplication(e){let t=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(t)?t:t?.contexts??t?.data??[]}async uploadBlob(e){let t=new URLSearchParams;e.hash&&t.set("hash",e.hash),e.contextId&&t.set("context_id",e.contextId);let r=t.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",s=p(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:s.blob_id,size:s.size}}async deleteBlob(e){let t=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:t.blob_id,deleted:t.deleted}}async listBlobs(){return{blobs:p(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}blobPath(e,t){if(!t?.contextId)return`/admin-api/blobs/${e}`;let r=new URLSearchParams({context_id:t.contextId});return`/admin-api/blobs/${e}?${r.toString()}`}async getBlob(e,t){return this.httpClient.get(this.blobPath(e,t),{parse:"arrayBuffer"})}async getBlobInfo(e,t){let{headers:r}=await this.httpClient.head(this.blobPath(e,t)),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 p(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return p(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return p(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return p(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return p(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return p(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return p(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return p(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return p(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return p(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return p(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let t=await this.getNodeIdentity();return{namespaceId:e,publicKey:t.publicKey,account:t.accountId}}async performIntent(e,t){return p(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async queryContext(e,t){return p(await this.httpClient.post(`/admin-api/contexts/${e}/query`,t))}async getIntentRelay(e){return p(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return p(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return p(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return p(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async admitJoin(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,t,{timeoutMs:65e3}))}async joinNamespace(e,t){let r=p(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,t,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,t,r={}){let{groupName:o,teamName:s}=r;return Ot({namespaceId:e,invitation:t,teamName:s},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:t}:{invitation:t,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(a=>a.namespaceId)})}async createGroupInNamespace(e,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return p(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return p(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return p(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,t){return p(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,t??{}))}async rescopeAccountDevice(e,t){return p(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/scope`,t))}async signWithAccountRoot(e){return p(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,t){return p(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/label`,t))}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,t){return p(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,t))}async getGroupInfo(e){return p(await this.httpClient.get(`/admin-api/groups/${e}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return p(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(t?.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 t}async listMemberDevices(e,t={}){let r=new URLSearchParams;t.offset!==void 0&&r.set("offset",String(t.offset)),t.limit!==void 0&&r.set("limit",String(t.limit));let o=r.toString(),s=`/admin-api/groups/${e}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(s)}async sealToAccount(e,t,r){return p(await this.httpClient.post(`/admin-api/groups/${e}/accounts/${t}/seal`,r))}async listGroupContexts(e){return p(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members`,t)}async removeGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,t)}async updateMemberRole(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/role`,r)}async getMemberCapabilities(e,t){return p(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/capabilities`))}async setMemberCapabilities(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/capabilities`,r)}async setDefaultCapabilities(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,t)}async openToDelegatedExecution(e){let t=await this.getDefaultCapabilities(e);if(Je(t,ie.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:t};let r=ze(t,ie.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,t){let{capabilities:r}=await this.getMemberCapabilities(e,t);if(Je(r,ie.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=ze(r,ie.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,t,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,t)}async setTeeAdmissionPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,t)}async getTeeAdmissionPolicy(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return t.data??t}async setTeeAuthoringPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-authoring-policy`,t)}async disableTeeAuthoringPolicy(e){await this.httpClient.delete(`/admin-api/groups/${e}/settings/tee-authoring-policy`)}async setGroupMetadata(e,t){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,t)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/metadata`,r)}async getMemberMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/metadata`))?.data??null}async setContextMetadata(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${t}/metadata`,r)}async getContextMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${t}/metadata`))?.data??null}async syncGroup(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,t){return p(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return p(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let t=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${t}/migration-status`)}async getCascadeStatus(e){let t=encodeURIComponent(e);return p(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,t){let r=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,t);return r?.data??r}async listSubgroups(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return t.subgroups??t.data??[]}async detachContextFromGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,{})}async createGroupInvitation(e,t){return p(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return p(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return p(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return p(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return p(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return p(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 p(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${e}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,{})}async issueOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,t)}async issueNamespaceOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,t)}async setMemberAutoFollow(e,t,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function Zs(n){return Array.from(new TextEncoder().encode(n),e=>e.toString(16).padStart(2,"0")).join("")}function oi(n){return new K(Q(n))}function si(n){return new K(we(n))}function ii(n){return new K(We(n))}function qt(n,e){return new K(n)}function Xe(n){try{let e=n.indexOf("#");if(e===-1)return null;let t=n.substring(e+1),r=new URLSearchParams(t),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 Ze(n,e){let t=new URLSearchParams;return t.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&t.set("permissions",e.permissions.join(",")),t.set("mode",e.mode),e.packageName&&(t.set("package-name",e.packageName),e.packageVersion&&t.set("package-version",e.packageVersion),e.registryUrl&&t.set("registry-url",e.registryUrl)),`${n.replace(/\/+$/,"")}/auth/login?${t.toString()}`}var Lt=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function A(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!0),e}function y(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function m(n,e,t){let r=n.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${r.length}`);let o=new Uint8Array(t);for(let s=0;s<t;s+=1)o[s]=Number.parseInt(r.slice(s*2,s*2+2),16);return o}function xe(n,e){let t=n.trim();if(!/^[0-9a-fA-F]*$/.test(t)||t.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(t.slice(o*2,o*2+2),16);return r}function w(n){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(n),!0),e}function h(...n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}async function E(n,e){let t=[w(n.length),n];for(let r of e)t.push(w(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",h(...t)))}async function D(n){let e=m(n,"deviceSecret",32),t=h(Lt,e);try{return await crypto.subtle.importKey("pkcs8",t,{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 U(n){let e=m(n,"deviceSecret",32),t=h(Lt,e),r=await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!0,["sign"]),s=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(s.replace(/-/g,"+").replace(/_/g,"/")),a=>a.charCodeAt(0))}var Ir=new TextEncoder().encode("calimero.auth.request.v1"),Tr=new TextEncoder().encode("calimero.auth.request.body.v1");function Kt(n){let e=new TextEncoder().encode(n);return h(A(e.length),e)}async function et(n=new Uint8Array(0)){let e=typeof n=="string"?new TextEncoder().encode(n):n;return E(Tr,[e])}async function Re(n){let e=await D(n.signerSecret),t=await et(n.body),r=w(n.issuedAt),o=w(n.expiresAt),s=new TextEncoder,a=await E(Ir,[s.encode(n.method),s.encode(n.path),t,r,o]),i=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,a));return y(h(Kt(n.method),Kt(n.path),t,r,o,i))}function ve(n){let e=xe(n.credential,"credential"),t=xe(n.request,"request signature"),r=n.session===void 0?new Uint8Array([0]):h(new Uint8Array([1]),xe(n.session,"session statement"));return y(h(e,r,t))}function Pr(n){if(n==null)return new Uint8Array(0);if(typeof n=="string"||n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error(`a request-carried proof cannot commit to a ${n?.constructor?.name??typeof n} body: pass a string or bytes, or use a session for this call`)}function Ce(n){let e=n.ttlSeconds??120,t=n.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=t();return ve({credential:n.credential,session:n.session,request:await Re({method:r.method,path:r.path,body:Pr(r.body),issuedAt:o,expiresAt:o+e,signerSecret:n.signerSecret})})}}var ke=class extends Error{constructor(e,t,r,o){super(t),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function tt(n,e,t){let r=await n.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:t});if(r.error){let o=r.error;throw new ke(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var ae=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await tt(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return t&&"output"in t?t.output:t}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 Dr=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Bt(n){return n.type!==void 0&&Dr.has(n.type)}var Ur=new Set(["token_reuse","token_revoked"]),Mr=new Set([401,403]);function jt(n){let e=n.headers.get("x-auth-error");return!e||!Mr.has(n.status)?null:Ur.has(e)?e:null}var Y=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.closed=!1;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken,this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(t,r)=>e.fetch?e.fetch(t,r):globalThis.fetch(t,r)}on(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(t)||o.push(t)}}off(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r],s=o.indexOf(t);s!==-1&&o.splice(s,1)}}onAppVersionChanged(e){let t=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",t),()=>this.off("event",t)}onMigrationEvent(e){let t=r=>{Bt(r)&&e(r)};return this.on("event",t),()=>this.off("event",t)}emit(e,t){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(t)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=await this.getAuthToken(),t=`${this.baseUrl}/sse`,r=await this.fetchImpl(t,{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"},signal:this.abortController.signal});if(!r.ok){let o=jt(r),s=await r.text().catch(()=>{});throw o?new _(o,r.status,r.statusText,t,r.headers,s):new S(r.status,r.statusText,t,r.headers,s)}if(!r.body)throw new Error("SSE response has no body");this.readStream(r.body).catch(o=>{if(this.closed)return;let s=o instanceof Error?o:new Error(String(o));this.emit("error",s),this.scheduleReconnect()})}catch(e){if(this.closed)return;let t=e instanceof Error?e:new Error(String(e));if(this.emit("error",t),t instanceof _)return;this.scheduleReconnect()}}}async readStream(e){let t=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:s,value:a}=await t.read();if(s)break;o+=r.decode(a,{stream:!0});let i=o.split(`
|
|
2
|
+
`);o=i.pop()??"";for(let c of i)if(c.startsWith("data:")){let l=c.slice(5).trim();l&&this.handleMessage(l)}}if(o+=r.decode(),o.startsWith("data:")){let s=o.slice(5).trim();s&&this.handleMessage(s)}}catch(s){if(this.closed)return;let a=s instanceof Error?s:new Error(String(s));this.emit("error",a)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let t=JSON.parse(e);if(t.type==="connect"&&t.session_id){this.sessionId=t.session_id,this.emit("connect",t.session_id),(this.subscribedContextIds.size>0||this.subscribedGroupIds.size>0)&&this.sendSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]});return}if(!t.result)return;let r=t.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),s=new TextDecoder().decode(o);r=JSON.parse(s)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:r});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:r})}catch{}}async subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,r=(t.contextIds??[]).filter(s=>!this.subscribedContextIds.has(s)),o=(t.groupIds??[]).filter(s=>!this.subscribedGroupIds.has(s));for(let s of t.contextIds??[])this.subscribedContextIds.add(s);for(let s of t.groupIds??[])this.subscribedGroupIds.add(s);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}async unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,r=(t.contextIds??[]).filter(s=>this.subscribedContextIds.has(s)),o=(t.groupIds??[]).filter(s=>this.subscribedGroupIds.has(s));for(let s of t.contextIds??[])this.subscribedContextIds.delete(s);for(let s of t.groupIds??[])this.subscribedGroupIds.delete(s);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,t){try{let r=await this.getAuthToken(),o={};t.contextIds&&t.contextIds.length>0&&(o.contextIds=t.contextIds),t.groupIds&&t.groupIds.length>0&&(o.groupIds=t.groupIds);let s=await this.fetchImpl(`${this.baseUrl}/sse/subscription`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({id:this.sessionId,method:e,params:o})});if(!s.ok){let a=jt(s),i=await s.text().catch(()=>{});this.emit("error",a?new _(a,s.status,s.statusText,`${this.baseUrl}/sse/subscription`,s.headers,i):new S(s.status,s.statusText,`${this.baseUrl}/sse/subscription`,s.headers,i))}}catch(r){this.emit("error",r instanceof Error?r:new Error(`SSE ${e} failed`))}}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 Se=class Se{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,t){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(t)||o.push(t)}}off(e,t){let r=e;if(r in this.listeners){let o=this.listeners[r],s=o.indexOf(t);s!==-1&&o.splice(s,1)}}emit(e,t){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(t)}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 t=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${t}/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 t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);if(!t.result)return;let r=t.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),s=new TextDecoder().decode(o);r=JSON.parse(s)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:r});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:r})}catch{}}subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let r of t.contextIds??[])this.subscribedContextIds.add(r);for(let r of t.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.groupIds??[])})}unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let r of t.contextIds??[])this.subscribedContextIds.delete(r);for(let r of t.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.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,t){let r={};return e.length>0&&(r.contextIds=e),t.length>0&&(r.groupIds=t),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),Se.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()}};Se.MAX_BACKOFF_MS=3e4;var X=Se;function Ee(){return{encode(n){return Array.from(new TextEncoder().encode(JSON.stringify(n)))},decode(n){return JSON.parse(new TextDecoder().decode(new Uint8Array(n)))}}}var ce=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,r=Ee()){await tt(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(t)})}subscribe(e,t,r=Ee()){let o=s=>{let a=s;if(a.type!=="Ephemeral"||a.contextId!==e)return;let i=a.data;if(!i?.author)return;let c=!!i.removed,l={author:i.author,state:c||i.state===void 0?void 0:r.decode(i.state),removed:c};i.ageMs!==void 0&&(l.ageMs=i.ageMs),t(l)};return this.sse.on("event",o),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",o)}}};var Nr=new TextEncoder().encode("calimero.device.cert.v1"),Ft=new TextEncoder().encode("calimero.account.genesis.v1"),_r=new TextEncoder().encode("calimero.device.id.v1"),nt=2;async function Vt(n,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let t=m(n,"account",32);return y(await E(_r,[t,e]))}async function rt(n){return E(Nr,[m(n.account,"account",32),m(n.device,"device",32),m(n.signPublicKey,"signPublicKey",32),m(n.kemPublicKey,"kemPublicKey",32),A(n.keyEpoch),A(n.deviceEpoch)])}function Wt(n){return h(new Uint8Array([nt]),n.rootPublicKey,A(0),m(n.account,"account",32),m(n.device,"device",32),m(n.signPublicKey,"signPublicKey",32),m(n.kemPublicKey,"kemPublicKey",32),A(n.keyEpoch),A(n.deviceEpoch),n.signature)}async function Jt(n){let e=await U(n.rootSecret),t=y(await E(Ft,[h(new Uint8Array([nt]),e)])),r=0,o=await rt({account:t,device:n.device,signPublicKey:n.signPublicKey,kemPublicKey:n.kemPublicKey,keyEpoch:r,deviceEpoch:n.deviceEpoch}),s=await D(n.rootSecret),a=new Uint8Array(await crypto.subtle.sign("Ed25519",s,o)),i=Wt({rootPublicKey:e,account:t,device:n.device,signPublicKey:n.signPublicKey,kemPublicKey:n.kemPublicKey,keyEpoch:r,deviceEpoch:n.deviceEpoch,signature:a});return y(i)}async function Ie(n){let e=await U(n);return y(await E(Ft,[h(new Uint8Array([nt]),e)]))}var ot=["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 Gr=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),Or=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),ue=256,zt=ue/32,st=(ue+zt)/11;async function Qt(){let n=crypto.getRandomValues(new Uint8Array(ue/8));return Xt(y(n),await $r(n))}async function Yt(n){let e=Hr(n);return Xt(y(await qr(e)),e.join(" "))}async function B(n){return m(n,"secret",32),{secret:n,publicKey:y(await U(n)),accountId:await Ie(n)}}async function le(n){if(!n.nonce)throw new Error("nonce is required to sign an account link");let e=await D(n.rootSecret),t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,h(Gr,new TextEncoder().encode(n.nonce))));return tn(t)}async function Te(n){if(!n.nonce)throw new Error("nonce is required to sign an account login");let e=await D(n.rootSecret),t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,h(Or,new TextEncoder().encode(n.nonce))));return tn(t)}async function Xt(n,e){return{...await B(n),phrase:e}}function Hr(n){let e=n.normalize("NFKD").toLowerCase().trim().split(/\s+/),t=e[0]===""?0:e.length;if(t!==st)throw new Error(`recovery phrase must be ${st} words, got ${t}`);return e}async function $r(n){let e=en(n)+await Zt(n),t=[];for(let r=0;r<st;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);t.push(ot[o])}return t.join(" ")}async function qr(n){let e="";for(let r of n){let o=ot.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 t=new Uint8Array(ue/8);for(let r=0;r<t.length;r+=1)t[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(ue)!==await Zt(t))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return t}async function Zt(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",n));return en(e).slice(0,zt)}function en(n){let e="";for(let t of n)e+=t.toString(2).padStart(8,"0");return e}function tn(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Lr=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function nn(n,e){m(e,"deviceSecret",32);let t=await D(e),r=h(Lr,new TextEncoder().encode(n)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,r));return Kr(o)}async function Pe(n,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":n.nonce,"X-Calimero-Signature":await nn(n.nonce,e.deviceSecret)}}function Kr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Br="https://cloud.calimero.network";function it(n,e){return typeof n.can_execute=="boolean"?n.can_execute:e}function at(n){return typeof n.tee_role=="string"&&n.tee_role!==""?n.tee_role:null}function ct(n){return n.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}var jr="x-mdma-session-refresh",Fr="x-mdma-session-expires",j=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Br).replace(/\/+$/,""),this.onSession=e.onSession;let t=e.fetch;this.fetchImpl=t?(r,o)=>t(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 t=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(t)}async signInWithAccount(e){let t=await B(e),{nonce:r}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:t.publicKey,nonce:r,signature:await Te({rootSecret:e,nonce:r})})}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 t=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(t)}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(t=>({namespaceId:String(t.namespace_id??t.group_id??""),groupId:String(t.group_id??t.namespace_id??""),haStatus:String(t.ha_status??"none"),haEnabledAt:t.ha_enabled_at??null,contexts:Array.isArray(t.contexts)?t.contexts:[],fleetReplicas:t.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,s=r.executor_account??null,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:s,status:String(r.status??""),authorshipReady:a,teeRole:at(r),canExecute:it(r,a&&o!==null&&s!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null}})}async findExecutingRelay(e){let t=await this.getNamespaceRelays(e);return ct(t)}async getNamespaceRouting(e){let t=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(t.namespace_id??e),nodes:(t.admitters??[]).map(r=>{let o=r.account??null,s=r.relay_url??null,a=r.fresh===!0,i=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:s,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:a,canAdmit:r.can_admit===!0,authorshipReady:i,teeRole:at(r),canExecute:it(r,i&&s!==null&&o!==null&&a)}}),servable:t.servable===!0,writable:t.writable===!0}}async getRoutingChallenge(e){let t=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{namespaceId:String(t.namespace_id??e),nonce:String(t.nonce??""),expiresAtMs:Number(t.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let t=await this.getRoutingChallenge(e);return Pe(t,this.routingCredential)}async getAccountRelaysChallenge(e){let t=await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{accountId:String(t.account_id??e),nonce:String(t.nonce??""),expiresAtMs:Number(t.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 t=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/relays`,{anonymous:!0,headers:await Pe(t,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0}))}async findAdmitter(e,t){let{nodes:r}=await this.getNamespaceRouting(e),o=t&&t.length>0?new Set(t.map(s=>s.toLowerCase())):null;return r.find(s=>s.canAdmit&&(o===null||s.account!==null&&o.has(s.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(t=>{let r=t.relay_url??null,o=t.executor_account??null,s=(Array.isArray(t.namespaces)?t.namespaces:[]).map(a=>{let i=a;return{namespaceId:String(i.namespace_id??""),status:String(i.status??""),authorshipReady:i.authorship_ready===!0,teeRole:at(i),fresh:i.fresh===!0,confirmedAt:i.confirmed_at??null,lastSeenAt:i.last_seen_at??null}});return{peerId:String(t.peer_id??""),relayUrl:r,executorAccount:o,canExecute:it(t,r!==null&&o!==null&&s.some(a=>a.authorshipReady)),namespaces:s}})}async claimNamespace(e,t){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:t}})}async enableNamespaceHa(e,t={}){let r=t.admitterAddrs===void 0?{}:{admitter_addrs:[...t.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:r})}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${t.toString()}`)}disableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${t.toString()}`)}async linkAccount(e){let t=await B(e),{nonce:r}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:t.accountId,rootPublicKey:t.publicKey,nonce:r,signature:await le({rootSecret:e,nonce:r})})}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 t=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(t.account_id??e.accountId),linkedAt:t.linked_at??null,alreadyLinked:t.already_linked===!0}}static accountLinkHandoff(e){let t=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":e.callbackUrl});return{url:`${t}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let t=e??(typeof window>"u"?"":window.location.href);if(!t)return{};let r;try{r=new URL(t).hash}catch{return{}}let o=new URLSearchParams(r.replace(/^#/,"")),s=o.get("grant"),a=o.get("account"),i=o.get("error"),c={};return s&&(c.grant=s),a&&(c.accountId=a),i&&(c.error=i),c}async linkAccountWithGrant(e){let t=await B(e.rootSecret),r=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:t.publicKey,signature:await le({rootSecret:e.rootSecret,nonce:e.grant})},anonymous:!0});return{accountId:String(r.account_id??t.accountId),linkedAt:r.linked_at??null,alreadyLinked:r.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(t=>({accountId:String(t.account_id??""),linkedAt:t.linked_at??null,hasRecoveryEnvelope:t.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,t,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 s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs),i;try{i=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:s.signal})}catch(c){throw new S(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(this.adoptRollingRefresh(i),!i.ok){let c=await i.text().catch(()=>{});throw new S(i.status,i.statusText,`${this.baseUrl}${t}`,i.headers,c)}if(!(r.parse==="none"||i.status===204))return await i.json()}adoptRollingRefresh(e){let t=e.headers.get(jr);if(!t||!this.session)return;let r=e.headers.get(Fr),o=Number(r);this.session={sessionToken:t,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Vr(n){let e=n&&typeof n=="object"?n.data??n:void 0;if(!e||typeof e!="object")return[];let t=e.localPeerId,r=e.externalAddrs;if(typeof t!="string"||!t||!Array.isArray(r))return[];let o=`/p2p/${t}`,s=[];for(let a of r){if(typeof a!="string")continue;let i=a.trim();if(!i.startsWith("/"))continue;let c=i.endsWith(o)?i:`${i}${o}`;s.includes(c)||s.push(c)}return s}function Wr(n){if(n)return typeof n=="function"?n:Ce(n)}var Jr="mero-js:token-refresh";function zr(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function ut(n,e){try{let t=n.split(".");if(t.length===3){let r=t[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 De=class{constructor(e){this.tokenData=null;this.refreshPromise=null;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());let t=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=Wr(this.config.requestProof);this.httpClient=Q({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.tokenStore?.setTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(t?"omit":void 0)}),this.authClient=Gt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=qt(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 ae({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new Y({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 ce({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new j(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 X({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let t=e||this.config.credentials;if(!t)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:t.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:t.username,password:t.password}},o=await this.authClient.generateTokens(r),s=o.data.access_token;return this.tokenData={access_token:s,refresh_token:o.data.refresh_token,expires_at:ut(s,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,t=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=t;try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}withRefreshLock(e){let t=zr();return t?t.request(Jr,e):e()}async performTokenRefreshLocked(e){let t=this.tokenStore?.getTokens()??null;if(t?.refresh_token&&(this.tokenData=t,e&&t.access_token!==e))return t;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let r=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),o=r.data.access_token;return this.tokenData={access_token:o,refresh_token:r.data.refresh_token,expires_at:ut(o,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Token refresh failed: ${r instanceof Error?r.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let t=e.expires_at||ut(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:t},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return Xe(e)}static buildAuthLoginUrl(e,t){return Ze(e,t)}};function Qr(n){return new De(n)}var lt=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Yr="mero-tokens",dt=class{constructor(e=Yr){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let t=JSON.parse(e);return t&&t.access_token&&t.refresh_token?{access_token:t.access_token,refresh_token:t.refresh_token,expires_at:typeof t.expires_at=="number"?t.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 Xr=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function rn(n){let e=n instanceof Error?`: ${n.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 pt(n,e="secret"){let t=m(n,e,32),r=h(Xr,t),o,s;try{let a=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),i=await crypto.subtle.exportKey("jwk",a);s=y(Uint8Array.from(atob(i.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(a){throw rn(a)}return sn(o,s)}async function on(n,e){if(n.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${n.type} key`);if(!n.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let t;if(typeof e=="string")m(e,"publicKey",32),t=e.trim().toLowerCase();else try{t=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 sn(n,t)}function sn(n,e){return{publicKey:e,async sign(t){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}catch(r){throw rn(r)}}}}async function G(n,e,t){if(e&&n!==void 0)throw new Error(`pass either ${t} or signer, not both \u2014 they may name different keys`);if(e)return e;if(n!==void 0)return pt(n,t);throw new Error(`${t} or signer is required`)}var Zr=new TextEncoder().encode("calimero.warrant.v2"),eo=new TextEncoder().encode("calimero.warrant.intent.v1"),an=64,to="00".repeat(32);async function gt(n,e){let t=new TextEncoder().encode(JSON.stringify(e));return E(eo,[new TextEncoder().encode(n),t])}async function Ue(n){let e=m(n.context,"context",32),t=m(n.authorAccount,"authorAccount",32),r=m(n.executor,"executor",32),o=m(n.appVersion??to,"appVersion",32),s=O(n.accountHeads,"accountHeads"),a=O(n.governanceFloor,"governanceFloor"),i=await G(n.deviceSecret,n.signer,"deviceSecret"),c=m(i.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(n.method),d=await gt(n.method,n.argsJson),u=w(n.nonce),g=w(n.notAfter),b=await E(Zr,[e,t,c,r,o,l,d,w(s.length),...s,w(a.length),...a,u,g]),f=de(await i.sign(b));return y(h(e,t,c,r,o,A(l.length),l,d,A(s.length),...s,A(a.length),...a,u,g,f))}function de(n){if(!(n instanceof Uint8Array)||n.length!==64){let e=n instanceof Uint8Array?`${n.length} bytes`:typeof n;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return n}function O(n,e){let t=n??[];if(t.length>an)throw new Error(`${e} cites ${t.length} heads, over the ${an} a node accepts`);return t.map((r,o)=>m(r,`${e}[${o}]`,32))}var no=new TextEncoder().encode("calimero.context-creation-warrant.v1"),ro=new TextEncoder().encode("calimero.context-creation.init.v1"),Me=256;async function mt(n){let e=new TextEncoder().encode(JSON.stringify(n));return E(ro,[e])}async function oo(n){return E(no,[n.group,n.seed,n.authorAccount,n.deviceKey,n.executor,n.applicationId,new Uint8Array([n.serviceName===null?0:1]),n.serviceName??new Uint8Array(0),new Uint8Array([n.name===null?0:1]),n.name??new Uint8Array(0),n.initHash,w(n.accountHeads.length),...n.accountHeads,w(n.governanceFloor.length),...n.governanceFloor,w(n.nonce),w(n.notAfter)])}async function Ne(n){let e=m(n.group,"group",32),t=n.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):m(n.seed,"seed",32),r=m(n.authorAccount,"authorAccount",32),o=m(n.executor,"executor",32),s=m(n.applicationId,"applicationId",32),a=cn(n.serviceName,"serviceName"),i=cn(n.name,"name"),c=O(n.accountHeads,"accountHeads"),l=O(n.governanceFloor,"governanceFloor"),d=await G(n.deviceSecret,n.signer,"deviceSecret"),u=m(d.publicKey,"signer.publicKey",32),g=await mt(n.initArgs),b=await oo({group:e,seed:t,authorAccount:r,deviceKey:u,executor:o,applicationId:s,serviceName:a,name:i,initHash:g,accountHeads:c,governanceFloor:l,nonce:n.nonce,notAfter:n.notAfter}),f=de(await d.sign(b));return{warrant:y(h(e,t,r,u,o,s,un(a),un(i),g,A(c.length),...c,A(l.length),...l,w(n.nonce),w(n.notAfter),f)),seed:y(t)}}function ln(n){let e=n.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 t=new Uint8Array(e.length/2);for(let u=0;u<t.length;u+=1)t[u]=Number.parseInt(e.slice(u*2,u*2+2),16);let r=new DataView(t.buffer),o=0,s=(u,g)=>{if(o+u>t.length)throw new Error(`creation warrant ends inside ${g} (${t.length} bytes)`);let b=t.subarray(o,o+u);return o+=u,b},a=u=>r.getUint32(s(4,u).byteOffset,!0),i=u=>r.getBigUint64(s(8,u).byteOffset,!0),c=u=>{let g=s(1,u)[0];if(g===0)return null;if(g!==1)throw new Error(`${u} has option tag ${g}, expected 0 or 1`);let b=a(u);if(b>Me)throw new Error(`${u} is ${b} bytes, over the ${Me} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(s(b,u))},l=u=>{let g=a(u);if(g>64)throw new Error(`${u} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>y(s(32,u)))},d={group:y(s(32,"group")),seed:y(s(32,"seed")),authorAccount:y(s(32,"authorAccount")),deviceKey:y(s(32,"deviceKey")),executor:y(s(32,"executor")),applicationId:y(s(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:y(s(32,"initHash")),accountHeads:l("accountHeads"),governanceFloor:l("governanceFloor"),nonce:i("nonce"),notAfter:i("notAfter"),signature:y(s(64,"signature"))};if(o!==t.length)throw new Error(`creation warrant is ${t.length} bytes but its fields account for ${o}`);return d}function cn(n,e){if(n===void 0)return null;let t=new TextEncoder().encode(n);if(t.length>Me)throw new Error(`${e} is ${t.length} UTF-8 bytes, over the ${Me} a node accepts`);return t}function un(n){return n===null?new Uint8Array([0]):h(new Uint8Array([1]),A(n.length),n)}var so=new TextEncoder().encode("calimero.governance-warrant.v1"),io=new TextEncoder().encode("calimero.governance-warrant.op.v1"),ao={group:0,root:1};async function ht(n){return E(io,[new Uint8Array([ft(n.kind)]),n.bytes])}async function co(n){return E(so,[n.scope,new Uint8Array([ft(n.kind)]),n.authorAccount,n.deviceKey,n.executor,n.opHash,w(n.accountHeads.length),...n.accountHeads,w(n.governanceFloor.length),...n.governanceFloor,w(n.nonce),w(n.notAfter)])}async function _e(n){let e=m(n.scope,"scope",32),t=m(n.authorAccount,"authorAccount",32),r=m(n.executor,"executor",32),o=O(n.accountHeads,"accountHeads"),s=O(n.governanceFloor,"governanceFloor"),a=ft(n.op.kind),i=await G(n.deviceSecret,n.signer,"deviceSecret"),c=m(i.publicKey,"signer.publicKey",32),l=await ht(n.op),d=await co({scope:e,kind:n.op.kind,authorAccount:t,deviceKey:c,executor:r,opHash:l,accountHeads:o,governanceFloor:s,nonce:n.nonce,notAfter:n.notAfter}),u=de(await i.sign(d));return y(h(e,new Uint8Array([a]),t,c,r,l,A(o.length),...o,A(s.length),...s,w(n.nonce),w(n.notAfter),u))}function dn(n){let e=n.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 t=new Uint8Array(e.length/2);for(let u=0;u<t.length;u+=1)t[u]=Number.parseInt(e.slice(u*2,u*2+2),16);let r=new DataView(t.buffer),o=0,s=(u,g)=>{if(o+u>t.length)throw new Error(`governance warrant ends inside ${g} (${t.length} bytes)`);let b=t.subarray(o,o+u);return o+=u,b},a=u=>r.getUint32(s(4,u).byteOffset,!0),i=u=>r.getBigUint64(s(8,u).byteOffset,!0),c=u=>{let g=a(u);if(g>64)throw new Error(`${u} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>y(s(32,u)))},l=()=>{let u=s(1,"kind")[0];if(u===0)return"group";if(u===1)return"root";throw new Error(`governance warrant has kind ${u}, expected 0 (group) or 1 (root)`)},d={scope:y(s(32,"scope")),kind:l(),authorAccount:y(s(32,"authorAccount")),deviceKey:y(s(32,"deviceKey")),executor:y(s(32,"executor")),opHash:y(s(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:i("nonce"),notAfter:i("notAfter"),signature:y(s(64,"signature"))};if(o!==t.length)throw new Error(`governance warrant is ${t.length} bytes but its fields account for ${o}`);return d}function ft(n){let e=ao[n];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(n)}`);return e}var yt=300,F=class extends Error{constructor(t,r,o){super(`relay refused the intent (HTTP ${o}): ${t}`);this.reason=t;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},pe=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,""),this.executorAccount=e.executorAccount;let t=e.fetch;this.fetchImpl=t?(r,o)=>t(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4}async authorSigner(){return G(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){let t=await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`);return this.executorAccount=t.data.executorAccount,t.data}async execute(e,t,r={}){let o=this.executorAccount??(await this.describe(e)).executorAccount,s=await this.authorSigner(),a=await this.config.nonces.next(),i=this.config.ttlSeconds??yt,c=await Ue({context:e,authorAccount:this.config.authorAccount,executor:o,method:t,argsJson:r,nonce:a,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(i),signer:s}),l=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:t,argsJson:r,warrant:c,authorProof:this.config.authorProof});return{rootHash:l.data.rootHash,returns:l.data.returns??null}}async describeCreation(e,t={}){let r=t.author?`?author=${encodeURIComponent(t.author)}`:"";return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/context-intents${r}`)).data}async createContext(e){let t=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!t.canCreateOnBehalf)throw new F(`the relay (${t.executorAccount}) has no standing to act for members of group ${t.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(t.authorMayCreate===!1)throw new F(`the author (${this.config.authorAccount}) may not create contexts in group ${t.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(t.executorAccount),o=e.initArgs??{},s=await this.authorSigner(),a=await this.config.nonces.next(),i=this.config.ttlSeconds??yt,{warrant:c}=await Ne({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:a,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(i),signer:s}),l=await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:l.data.contextId,groupId:l.data.groupId,memberPublicKey:l.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`)).data}async govern(e){let t=await this.describeGovernance(e.groupId);if(!t.canActOnBehalf)throw new F(`the relay (${t.executorAccount}) has no standing to act for members of group ${t.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(t.executorAccount),o=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??yt,i=await _e({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:o});return{groupId:(await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/governance-intents`,{warrant:i,authorProof:this.config.authorProof,op:y(e.op.bytes)})).data.groupId}}checkedExecutor(e){let t=this.config.executorAccount;if(t&&t.toLowerCase()!==e.toLowerCase())throw new Error(`configured executorAccount ${t} is not the relay's account ${e}; a warrant naming it would be unspendable`);return this.executorAccount=e,e}async json(e,t,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs),i;try{i=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:s.signal})}catch(c){throw new S(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(!i.ok){let c=await i.text().catch(()=>"");if(i.status===400||i.status===403){let l=uo(c);throw new F(l,/nonce/i.test(l),i.status)}throw new S(i.status,i.statusText,`${this.baseUrl}${t}`,i.headers,c)}return await i.json()}};function uo(n){if(!n)return"no reason given";try{let e=JSON.parse(n);for(let t of[e.error,e.message])if(typeof t=="string"&&t)return t}catch{}return n}function bt(n=1){let e=BigInt(n);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let t=e;return e+=1n,Promise.resolve(t)}}}function wt(n,e){let t=e??globalThis.localStorage;if(!t)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");return{next(){let r=t.getItem(n),o=0n;if(r!==null&&r!=="")try{let a=BigInt(r);a>0n&&(o=a)}catch{o=0n}let s=o+1n;return t.setItem(n,s.toString()),Promise.resolve(s)}}}var lo="Noise_NK_25519_AESGCM_SHA256",At=32,po=16,go=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),Rt=class n{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(lo),t=new Uint8Array(32);return t.set(e),new n(t)}async mixHash(e){this.h=await ho(h(this.h,e))}async mixKey(e){let[t,r]=await mn(this.ck,e);this.ck=t,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 t=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:gn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(t),t}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:gn(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),t}split(){return mn(this.ck,new Uint8Array)}};async function hn(n,e,t){let r=await Rt.initialize();await r.mixHash(e),await r.mixHash(n);let o=await mo(t);return await r.mixHash(o.publicKey),await r.mixKey(await pn(o.privateKey,n)),{message1:h(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<At+po)throw new Error("Noise: message 2 is too short");let i=a.slice(0,At);return await r.mixHash(i),await r.mixKey(await pn(o.privateKey,i)),{payload:await r.decryptAndHash(a.slice(At)),split:await r.split()}}}}async function mo(n){if(!n){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(s){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${s?.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(go,n),{name:"X25519"},!0,["deriveBits"]),t=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:fo(t.x)}}async function pn(n,e){let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n,256))}function gn(n){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(n),!1),e}async function ho(n){return new Uint8Array(await crypto.subtle.digest("SHA-256",n))}async function xt(n,e){let t=await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",t,e))}async function mn(n,e){let t=await xt(n,e),r=await xt(t,new Uint8Array([1])),o=await xt(t,h(r,new Uint8Array([2])));return[r,o]}function fo(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(t,r=>r.charCodeAt(0))}var wn="/sealed/v2/handshake",An="/sealed/v2",me="application/vnd.calimero.sealed",vt=2,yo=new TextEncoder().encode("calimero/sealed-http/v2"),ge=16,bo=1+ge+8,wo=0,Ao=1,xo=2,Ro=1+64*1024+16,vo=1024,Co=6e4,ko="calimero.tee-attest.transport-key.v1",So=[101,204,205,304],xn=new TextEncoder,he=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Z=class extends Error{constructor(t,r,o,s){super(o);this.status=t;this.code=r;this.retryAfterMs=s;this.name="SealedTransportError"}};async function Rn(n,e){let t=await crypto.subtle.digest("SHA-256",h(xn.encode(ko),n,e));return new Uint8Array(t)}async function vn(n,e,t={}){if(t.applicationId===void 0!=(t.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 n.teeAttest({nonce:r,applicationId:t.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 s=m(o.transportPublicKey,"transportPublicKey",32),a=t.applicationHash?m(t.applicationHash,"applicationHash",32):new Uint8Array(32),i=y(await Rn(a,s));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:i,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return s}function fe(n){let e=n.fetch??((o,s)=>fetch(o,s)),t=`${n.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let s=await e(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!s.ok)throw new Error(`The node refused to attest: HTTP ${s.status}`);let a=await s.json();if(!a.data)throw new Error("The attestation response is malformed");return a.data}};return Cn({baseUrl:n.baseUrl,transportPublicKey:()=>vn(r,n.verify,{applicationId:n.applicationId,applicationHash:n.applicationHash}),fetch:e})}function Cn(n){let e=new URL(n.baseUrl),t=e.pathname.replace(/\/+$/,""),r=`${e.origin}${t}`,o=n.fetch??((u,g)=>fetch(u,g)),s=typeof n.transportPublicKey=="function"?n.transportPublicKey:void 0,a=s?Promise.resolve().then(s):Promise.resolve(n.transportPublicKey);a.catch(()=>{});let i,c=async()=>{try{return await yn(o,r,await fn(a))}catch(u){if(!(u instanceof he)||!s)throw u;return a=Promise.resolve().then(s),yn(o,r,await fn(a))}},l=async()=>{let u=i??d(void 0),g=await u;if(Date.now()<g.renewAt)return[g,u];let b=d(u);return[await b,b]},d=u=>{if(i===u){let g=c();i=g,g.catch(()=>{i===g&&(i=void 0)})}return i};return async(u,g)=>{let b=new Request(u,g),f=new URL(b.url);if(f.origin!==e.origin||!f.pathname.startsWith(`${t}/`))throw new Error(`Refusing to send ${f.href} outside the sealed node at ${n.baseUrl}`);let x=[];b.headers.forEach((T,N)=>x.push([N,T]));let k={method:b.method,path:f.pathname.slice(t.length)+f.search,headers:x},v=new Uint8Array(await b.arrayBuffer()),C=async T=>{let{requestId:N,header:V,envelope:W}=await Io(T,k,v),J=await o(`${r}${An}`,{method:"POST",headers:{"content-type":me},body:W,signal:b.signal});if(J.headers.get("content-type")!==me)throw await Sn(J);return Po(J,T.responseKey,V,N)},[I,q]=await l();try{return await C(I)}catch(T){if(!(T instanceof Z)||T.code!=="unknown_session")throw T;return C(await d(q))}}}async function fn(n){let e=await n;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function yn(n,e,t){try{return await bn(n,e,t)}catch(r){if(!(r instanceof Z)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),bn(n,e,t)}}async function bn(n,e,t){let r=await hn(t,yo),o=await n(`${e}${wn}`,{method:"POST",headers:{"content-type":me},body:h(new Uint8Array([vt]),t,r.message1)});if(o.headers.get("content-type")!==me)throw await Sn(o);let s=await Uo(o,vo);return Eo(r,s)}async function Eo(n,e){if(e[0]!==vt)throw new Error("The handshake reply is malformed");let t;try{t=await n.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}=t;if(r.length!==ge+4)throw new Error("The handshake reply is malformed");let s=r.slice(0,ge),a=new DataView(r.buffer,r.byteOffset).getUint32(ge,!1),[i,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:i,responseKey:c,nextRequestId:1,renewAt:Date.now()+a*1e3-Co,header(l){let d=new Uint8Array(bo);return d[0]=vt,d.set(s,1),new DataView(d.buffer).setBigUint64(1+ge,BigInt(l),!1),d}}}async function Io(n,e,t){let r=n.nextRequestId;n.nextRequestId+=1;let o=n.header(r),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:kn(r,0),additionalData:o},n.requestKey,To(e,t));return{requestId:r,header:o,envelope:h(o,new Uint8Array(s))}}function kn(n,e){let t=new Uint8Array(12),r=new DataView(t.buffer);return r.setBigUint64(0,BigInt(n),!1),r.setUint32(8,e,!1),t}function To(n,e){let t=xn.encode(JSON.stringify(n)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t.length,!1),h(r,t,e)}async function Po(n,e,t,r){if(!n.body)throw new Error("The sealed response has no body");let o=Do(n.body.getReader()),s=0,a=async()=>{let d=await o.next();if(!d)return null;let u;try{u=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:kn(r,s),additionalData:t},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return s+=1,{kind:u[0],data:u.slice(1)}},i=await a();if(!i||i.kind!==wo)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(i.data));if(So.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let l=new ReadableStream({async pull(d){try{let u=await a();u?u.kind===Ao?d.enqueue(u.data):u.kind===xo?(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(u){d.error(u)}},cancel(){return o.cancel()}});return new Response(l,{status:c.status,headers:c.headers})}function Do(n){let e=new Uint8Array,t=async r=>{for(;e.length<r;){let{done:o,value:s}=await n.read();if(o)return!1;e=h(e,s)}return!0};return{async next(){if(!await t(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Ro)throw await n.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await t(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>n.cancel()}}async function Uo(n,e){if(!n.body)return new Uint8Array;let t=n.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:s}=await t.read();if(o)return r;if(r=h(r,s),r.length>e)throw await t.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function Sn(n){let e,t=`Sealed request refused: HTTP ${n.status}`;try{let s=await n.json();e=s?.error?.code,s?.error?.message&&(t=`Sealed request refused: ${s.error.message}`)}catch{}if(e==="stale_transport_key")return new he;let r=Number(n.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Z(n.status,e,t,o)}async function Mo(n){if(!n.sessionToken&&!n.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=new j({cloudBaseUrl:n.cloudBaseUrl,sessionToken:n.sessionToken,onSession:n.onSession,fetch:n.fetch,timeoutMs:n.timeoutMs});!n.sessionToken&&n.googleIdToken&&await e.signInWithGoogle(n.googleIdToken);let t=await e.getMyNamespaces(),r=No(t,n.namespaceId),o=await e.getNamespaceRelays(r.namespaceId),s=ct(o);if(!s)throw new Error(_o(r,o));let a=new pe({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:n.authorAccount,authorProof:n.authorProof,deviceSecret:n.deviceSecret,nonces:n.nonces??await Go(n.deviceSecret),ttlSeconds:n.ttlSeconds,fetch:n.seal?fe({baseUrl:s.relayUrl,verify:n.seal,fetch:n.fetch}):n.fetch,timeoutMs:n.timeoutMs});return{cloud:e,relay:a,namespaceId:r.namespaceId,namespace:r,relayInfo:s,execute:(i,c,l)=>a.execute(i,c,l)}}function No(n,e){if(e){let t=n.find(r=>r.namespaceId===e);if(!t)throw new Error(`this account owns no namespace ${e}; it owns: ${n.map(r=>r.namespaceId).join(", ")||"(none)"}`);return t}if(n.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(n.length>1)throw new Error(`this account owns ${n.length} namespaces \u2014 pass namespaceId to say which: ${n.map(t=>t.namespaceId).join(", ")}`);return n[0]}function _o(n,e){if(e.length===0)return n.haStatus==="enabled"?`namespace ${n.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${n.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let t=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(t.length===e.length)return`every node on namespace ${n.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+t.length===e.length?`every relay on namespace ${n.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 ${n.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`}async function Go(n){let e=`mero-js:warrant-nonce:${y(await U(n))}`;try{return wt(e)}catch{return bt(1)}}var Oo=/^[0-9a-f]{96}$/,Ho=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function Ct(n){let e=ee(n.allowedMrtd??[],"allowedMrtd"),t=(n.allowedMeasurements??[]).map((i,c)=>{let l=`allowedMeasurements[${c}]`;return Ho.map(d=>ee([i?.[d]??""],`${l}.${d}`)[0]).join()}),r=[ee(n.allowedRtmr0??[],"allowedRtmr0"),ee(n.allowedRtmr1??[],"allowedRtmr1"),ee(n.allowedRtmr2??[],"allowedRtmr2"),ee(n.allowedRtmr3??[],"allowedRtmr3")];if(n.allowedMeasurements!==void 0&&t.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(t.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(i=>i.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=n.allowedTcbStatuses??["UpToDate"],s=n.now??Date.now;return Object.assign(async({quoteB64:i,nonce:c,reportDataSuffix:l,collateral:d})=>{let u=qo(i),g=d??await n.fetchCollateral?.(u);if(!g)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let b;try{b=n.dcapVerify(u,g,Math.floor(s()/1e3))}catch(v){throw new Error(`The quote did not verify: ${v?.message??String(v)}`)}if(b.status==="Revoked"||!o.includes(b.status))throw new Error(`The platform's TCB status is ${b.status}, which is not accepted`);let f=$o(b.report),x=[f.mrTd,f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].map(v=>y(v));if(t.length>0&&!t.includes(x.join()))throw new Error(`The measurements (MRTD ${x[0]}, RTMR0-3 ${x.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(x[0]))throw new Error(`MRTD ${x[0]} is not an image this verifier trusts`);if([f.rtMr0,f.rtMr1,f.rtMr2,f.rtMr3].forEach((v,C)=>{let I=r[C];if(I.length>0&&!I.includes(y(v)))throw new Error(`RTMR${C} ${y(v)} is not one this verifier trusts`)}),y(f.reportData)!==`${c}${l}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function ee(n,e){return n.map(t=>{let r=t.trim().toLowerCase();if(!Oo.test(r))throw new Error(`${e} holds ${JSON.stringify(t)}, which is not a 48-byte hex measurement`);return r})}function $o(n){let e=n.data;if(n.type==="td10"&&e)return e;if(n.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${n.type} quote, not a TDX one`)}function qo(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var Lo=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function kt(n,{profile:e}){if(n.length===0)throw new Error("No release given, so no image would be trusted");let t,r=n.map((o,s)=>{let a=o?.tag??`releases[${s}]`;if(o?.role!==void 0&&o.role!=="node")throw new Error(`${a} lists the measurements of a ${o.role}, not of a node image`);let i=o?.profiles?.[e];if(!i){let l=Object.keys(o?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${l})`)}let c=(i.allowed_tcb_statuses??["uptodate"]).map(l=>Ko(l,a));return t=t===void 0?c:t.filter(l=>c.includes(l)),{mrtd:i.mrtd,rtmr0:i.rtmr0,rtmr1:i.rtmr1,rtmr2:i.rtmr2,rtmr3:i.rtmr3}});if(!t||t.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:t}}function Ko(n,e){let t=Lo.find(r=>r.toLowerCase()===String(n).toLowerCase());if(!t)throw new Error(`${e} accepts TCB status ${JSON.stringify(n)}, which this verifier does not know`);return t}var En=[{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"]}],In=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Bo="1.2.840.10045.2.1",jo={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Fo={"P-256":32,"P-384":48},Vo={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function Tn(n,e,t){if(e+2>t)throw new Error("it is truncated");let r=n[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=n[e+1],s=e+2;if(o&128){let i=o&127;if(i===0||i>4||s+i>t)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<i;c+=1)o=o*256+n[s+c];s+=i}let a=s+o;if(a>t)throw new Error("it is truncated");return{tag:r,bytes:n,offset:e,start:s,end:a}}function ne(n){let e=Tn(n,0,n.length);if(e.end!==n.length)throw new Error("it has trailing bytes");return e}function P(n){let e=[];for(let t=n.start;t<n.end;){let r=Tn(n.bytes,t,n.end);e.push(r),t=r.end}return e}function R(n,e,t){if(!n||n.tag!==e)throw new Error(`${t} is not where it should be`);return n}function H(n){return n.bytes.slice(n.start,n.end)}function Ge(n){return n.bytes.slice(n.offset,n.end)}function te(n){let e=H(R(n,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let t=[],r=0;for(let a of e)r=r*128+(a&127),a&128||(t.push(r),r=0);let o=t.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...t].join(".")}function Wo(n){let e=new TextDecoder().decode(H(n)),t=n.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=n.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=t??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let s=Number(o[1]);t&&(s+=s<50?2e3:1900);let[a,i,c,l,d]=o.slice(2).map(Number);return Date.UTC(s,a-1,i,c,l,d)}function St(n){try{let[e,t,r,...o]=P(R(ne(n),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let s=P(R(e,48,"The signed part")),a=s[0]?.tag===160?1:0,[i,c,l,d,u,g,...b]=s.slice(a);R(i,2,"The serial number");let f=te(P(R(t,48,"The signature algorithm"))[0]);if(te(P(R(c,48,"The signature algorithm"))[0])!==f)throw new Error("it names two different signature algorithms");let k=Vo[f];if(!k)throw new Error(`it is signed with ${f}, not ECDSA with SHA-256 or SHA-384`);let[v,C]=P(R(d,48,"The validity")).map(Wo);if(C===void 0)throw new Error("its validity is incomplete");let[I,q]=P(R(g,48,"The public key"));R(q,3,"The public key");let[T,N]=P(R(I,48,"The key algorithm"));if(te(T)!==Bo)throw new Error("its key is not an elliptic-curve key");let V=jo[te(N)];if(!V)throw new Error("its key is on a curve other than P-256 or P-384");let W=new Map,J=b.find(Ke=>Ke.tag===163);if(J){let[Ke]=P(J);for(let gr of P(R(Ke,48,"The extensions"))){let z=P(R(gr,48,"An extension"));if(z.length===3)R(z[1],1,"An extension's critical flag");else if(z.length!==2)throw new Error("it has a malformed extension");let Be=te(z[0]);if(W.has(Be))throw new Error(`it has extension ${Be} twice`);W.set(Be,H(R(z[z.length-1],4,"An extension value")))}}let Nt=H(R(r,3,"The signature"));if(Nt[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:n,tbs:Ge(e),signatureHash:k,signature:Nt.slice(1),issuer:Ge(R(l,48,"The issuer")),subject:Ge(R(u,48,"The subject")),notBefore:v,notAfter:C,spki:Ge(g),curve:V,extensions:W}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function Pn(n){return P(R(ne(n),48,"The list")).map(te)}function Jo(n,e){let t=Fo[e],r=P(R(ne(n),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(t*2);return r.forEach((s,a)=>{let i=H(R(s,2,"The signature"));if(i.length===0||i[0]&128)throw new Error("The signature is not an ECDSA signature");for(;i.length>1&&i[0]===0;)i=i.subarray(1);if(i.length>t)throw new Error("The signature is not an ECDSA signature");o.set(i,a*t+t-i.length)}),o}async function Oe(n,e,t,r,o){let s;try{s=Jo(r,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",n,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:t},a,s,o)}function M(n,e){let t=n.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(t)||t.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(t),o=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)o[s]=r.charCodeAt(s);return o}function Et(n,e){let t=[...n.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(t.length!==1||n.replace(t[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return M(t[0][1],e)}var zo="2.5.29.17",Qo="2.5.29.37",Yo="1.3.6.1.5.5.7.3.3",Xo="1.3.6.1.4.1.57264.1.8",Zo="1.3.6.1.4.1.57264.1.1",es=134,ts=12,ns=48,rs=new TextEncoder,re=n=>new TextDecoder().decode(n);async function Dn(n,e,t,r){let{base64Signature:o,cert:s,rekorBundle:a}=as(e),i=a.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=M(o,"The bundle signature"),l=Et(re(M(s,"The bundle certificate")),"The bundle certificate"),d=St(l),u=In.find(C=>C.logId===i.logID.toLowerCase());if(!u)throw new Error(`The bundle names Rekor log ${i.logID}, which the Sigstore trust root does not know`);let g=rs.encode(`{"body":${JSON.stringify(i.body)},"integratedTime":${i.integratedTime},"logID":${JSON.stringify(i.logID)},"logIndex":${i.logIndex}}`);if(!await Oe(M(u.publicKey,"The Rekor key"),"P-256","SHA-256",M(a.SignedEntryTimestamp,"The signed entry timestamp"),g))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let f=i.integratedTime*1e3;if(!Nn(f,u.validFor))throw new Error(`Rekor log ${u.baseUrl} was not in use at ${ye(f)}, when the entry says it was logged`);let x=cs(i.body),k=y(new Uint8Array(await crypto.subtle.digest("SHA-256",n)));if(x.hash!==k)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!It(M(x.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let v=Et(re(M(x.publicKey,"The logged certificate")),"The logged certificate");if(!It(v,l))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Oe(d.spki,"P-256","SHA-256",c,n))throw new Error("The signature over the file does not verify with the bundle's certificate");return await os(d,f),is(d,t),{integratedTime:i.integratedTime}}async function os(n,e){if(!Mn(n,e))throw new Error(`The signing certificate was valid ${ye(n.notBefore)} to ${ye(n.notAfter)}, not at ${ye(e)} when Rekor logged it`);let t=[];for(let r of En){let o=r.certChain.map(a=>St(M(a,"A Fulcio certificate")));if(!await Un(n,o[0]))continue;let s=await ss(o,r.validFor,e);if(!s)return;t.push(`${r.uri} (valid from ${r.validFor.start}): ${s}`)}throw new Error(t.length>0?`The signing certificate's CA is not trusted at ${ye(e)}: ${t.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function ss(n,e,t){if(!Nn(t,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of n.entries()){if(!Mn(o,t))return`its certificate ${r} was not valid then`;let s=n[r+1]??o;if(!await Un(o,s))return`its certificate ${r} is not signed by the next`}}async function Un(n,e){return It(n.issuer,e.subject)?Oe(e.spki,e.curve,n.signatureHash,n.signature,n.tbs):!1}function is(n,e){let t=n.extensions.get(zo);if(!t)throw new Error("The signing certificate names no identity");let r=P(R(ne(t),ns,"The subject alternative name")),o=r.filter(l=>l.tag===es).map(l=>re(H(l)));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 s=n.extensions.get(Xo),a=n.extensions.get(Zo),i=s?re(H(R(ne(s),ts,"The OIDC issuer"))):a?re(a):void 0;if(i!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${i===void 0?"missing":JSON.stringify(i)}, not ${e.issuer}`);let c=n.extensions.get(Qo);if(!c||!Pn(c).includes(Yo))throw new Error("The signing certificate is not for code signing")}function as(n){let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let t=e,r=t?.rekorBundle?.Payload;if(!(typeof t?.base64Signature=="string"&&typeof t.cert=="string"&&typeof t.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 t}function cs(n){let e;try{e=JSON.parse(re(M(n,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let t=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||t?.algorithm!=="sha256"||typeof t.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:t.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function Mn(n,e){return n.notBefore<=e&&e<=n.notAfter}function Nn(n,e){return Date.parse(e.start)<=n&&(e.end===void 0||n<=Date.parse(e.end))}function ye(n){return new Date(n).toISOString()}function It(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Tt=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"}),us=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Gn="https://cloud.calimero.network";async function On(n,e,t={}){let r=typeof n=="string"?new TextEncoder().encode(n):n;await Dn(r,e,{identity:t.identity??Tt.identity,issuer:t.issuer??Tt.issuer},t.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 s=Object.values(o.profiles??{}),a=i=>us.every(c=>/^[0-9a-f]{96}$/i.test(String(i?.[c])));if(typeof o.tag!="string"||s.length===0||!s.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(t.expectedVersion!==void 0&&o.tag!==t.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${t.expectedVersion}`);return o}async function Hn(n,e={}){let t=await(e.fetch??fetch)(n,{headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Fetching the node release from ${n} failed: HTTP ${t.status}`);let r;try{r=(await t.json())?.data}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${n} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function $n(n){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(n);if(!e)throw new Error(`${JSON.stringify(n)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function qn(n,e={}){let t=await Kn(n,e.fetch??fetch);if(t===void 0)throw new Error(`${Ln(n)} 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 t}function Ln(n){return`${n.replace(/\/+$/,"")}/admin-api/tee/info`}async function Kn(n,e){let t=Ln(n),r=await e(t,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(a=>a?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${t} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${t} did not name the node's image`);return $n(o)}function Bn(n,e){return`${n.replace(/\/+$/,"")}/api/tee/node-releases/${be(e,"version")}`}async function jn(n){let e=be(n.minReleaseVersion,"minReleaseVersion"),t=be(n.release?.version,"The release version"),r=await On(n.release.publishedMrtds,n.release.bundle,{expectedVersion:t,identity:n.identity,issuer:n.issuer});if(ds(t,e)<0)throw new Error(`Release ${t} is older than the minimum trusted, ${e}`);return kt([r],{profile:n.profile})}function Fn(n){return be(n.minReleaseVersion,"minReleaseVersion"),Object.assign(async t=>{let r=await jn({release:await n.release(),profile:n.profile,minReleaseVersion:n.minReleaseVersion,identity:n.identity,issuer:n.issuer});return Ct({dcapVerify:n.dcapVerify,fetchCollateral:n.fetchCollateral,now:n.now,...r})(t)},{includeCollateral:!0})}function ls(n){let{baseUrl:e,releaseSource:t,releaseVersion:r,applicationId:o,applicationHash:s,fetch:a,...i}=n;r!==void 0&&be(r,"releaseVersion");let c=a??((d,u)=>fetch(d,u));return fe({baseUrl:e,verify:Fn({...i,release:async()=>{let d=r===void 0?await qn(e,{fetch:c}):await Kn(e,c)??r;return typeof t=="function"?t({baseUrl:e,version:d,fetch:c}):Hn(Bn(t??Gn,d),{fetch:c})}}),applicationId:o,applicationHash:s,fetch:c})}var Vn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function be(n,e){let t=typeof n=="string"?Vn.exec(n):null,r=t?.[4];if(!t||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(n)}, not a release version like 2.3.87`);return n}function ds(n,e){let[t,r]=_n(n),[o,s]=_n(e);for(let c=0;c<3;c+=1)if(t[c]!==o[c])return t[c]<o[c]?-1:1;if(r===void 0||s===void 0)return r===s?0:r===void 0?1:-1;let a=r.split("."),i=s.split(".");for(let c=0;c<Math.max(a.length,i.length);c+=1){let[l,d]=[a[c],i[c]];if(l===void 0||d===void 0)return l===void 0?-1:1;let[u,g]=[/^\d+$/.test(l),/^\d+$/.test(d)],b=u&&g?Math.sign(Number(l)-Number(d)):u!==g?u?-1:1:l<d?-1:l>d?1:0;if(b!==0)return b}return 0}function _n(n){let e=Vn.exec(n);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var ps={Admin:0,Member:1,ReadOnly:2},$e={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4},Pt={GroupCreated:0,GroupReparented:1,GroupDeleted:2},Wn=new Uint8Array(32),He=A(0);function Jn(n){let e=ps[n];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(n)}`);return new Uint8Array([e])}function $(n){return new Uint8Array([n])}function zn(n,e){return{kind:"group",bytes:h($($e.MemberAdded),m(n,"member",32),Jn(e))}}function Qn(n){return{kind:"group",bytes:h($($e.MemberRemoved),m(n,"member",32),Wn,He)}}function Yn(n){return{kind:"group",bytes:h($($e.MemberLeft),m(n,"member",32),Wn,He)}}function Xn(n,e){return{kind:"group",bytes:h($($e.MemberRoleSet),m(n,"member",32),Jn(e))}}function Zn(n){return{kind:"root",bytes:h($(Pt.GroupCreated),m(n.groupId,"groupId",32),m(n.parentId,"parentId",32),$(n.restricted?1:0),m(n.admin,"admin",32))}}function er(n,e){return{kind:"root",bytes:h($(Pt.GroupReparented),m(n,"childGroupId",32),m(e,"newParentId",32))}}function tr(n){return{kind:"root",bytes:h($(Pt.GroupDeleted),m(n,"rootGroupId",32),He,He)}}var Ut=16,gs=new TextEncoder().encode("calimero.namespace.v1"),ms=0,nr={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function Dt(n,e){if(n.length!==32)throw new Error(`${e} must be 32 bytes, got ${n.length}`);return new Uint8Array(n)}function rr(n,e){if(n==null)return new Uint8Array([0]);if(n.length!==32)throw new Error(`${e} must be 32 bytes, got ${n.length}`);return h(new Uint8Array([1]),new Uint8Array(n))}function or(n){let e=new TextEncoder().encode(n);return h(A(e.length),e)}function qe(n){let e=n.invitation,t=e.admitters??[],r=n.admitter_addrs??[];return h(Dt(e.inviter_identity,"inviter_identity"),Dt(e.group_id,"group_id"),w(e.expiration_timestamp),Dt(e.secret_salt,"secret_salt"),new Uint8Array([e.invited_role]),A(t.length),...t.map((o,s)=>m(o,`admitters[${s}]`,32)),or(n.inviter_signature),n.inviter_account?h(new Uint8Array([1]),m(n.inviter_account,"inviter_account",32)):new Uint8Array([0]),A(r.length),...r.map(or),rr(n.application_id,"application_id"),rr(n.app_key,"app_key"))}async function sr(n){let e=n.parentOpHashes??[],t=m(n.credential,"credential",n.credential.length/2),r=BigInt(n.invitation.invitation.expiration_timestamp??0)!==0n,o=n.joinedAt??BigInt(Math.floor(Date.now()/1e3)),s=r?h(new Uint8Array([nr.MemberJoinedAt]),m(n.member,"member",32),qe(n.invitation),w(o),t):h(new Uint8Array([nr.MemberJoined]),m(n.member,"member",32),qe(n.invitation),t),a=h(new Uint8Array([ms]),s),i=await D(n.deviceSecret),c=await U(n.deviceSecret),l=h(new Uint8Array([Ut]),m(n.namespaceId,"namespaceId",32),A(e.length),...e.map((g,b)=>m(g,`parentOpHashes[${b}]`,32)),c,w(n.nonce),a),d=new Uint8Array(await crypto.subtle.sign("Ed25519",i,h(gs,l))),u=new Uint8Array([0]);return y(h(l,d,u))}var hs=new TextEncoder().encode("calimero.auth.login.v1"),ir={webOrigin:0,codeSigningId:1,cli:2};function ar(n){let e=new TextEncoder;switch(n.kind){case"webOrigin":return e.encode(n.origin);case"codeSigningId":return e.encode(n.id);case"cli":return new Uint8Array(0)}}function fs(n){return h(Uint8Array.from([ir[n.kind]]),ar(n))}function ys(n){let e=Uint8Array.from([ir[n.kind]]);if(n.kind==="cli")return e;let t=ar(n);return h(e,A(t.length),t)}async function Le(n){let e=m(n.node,"node",32),t=m(n.challenge,"challenge",32),r=m(n.sessionKey,"sessionKey",32),o=await D(n.deviceSecret),s=await U(n.deviceSecret),a=w(n.issuedAt),i=w(n.expiresAt),c=await E(hs,[e,fs(n.audience),t,r,s,a,i]),l=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},o,c));return y(h(e,ys(n.audience),t,r,s,a,i,l))}var bs=300;async function Mt(){let n=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await U(n)),secret:n}}function ws(n){switch(n.kind){case"webOrigin":return n.origin;case"codeSigningId":return n.id;case"cli":return"cli"}}async function cr(n){let e=n.nodeUrl.replace(/\/+$/,""),t=n.timeoutMs??1e4,r=async(g,b)=>{let f=new AbortController,x=setTimeout(()=>f.abort(),t),k;try{let C={...b,signal:f.signal};k=n.fetch?await n.fetch(`${e}${g}`,C):await globalThis.fetch(`${e}${g}`,C)}catch(C){throw new S(0,C instanceof Error?C.name:"NetworkError",`${e}${g}`,new Headers,C instanceof Error?C.message:String(C))}finally{clearTimeout(x)}let v=await k.text().catch(()=>"");if(!k.ok)throw new S(k.status,k.statusText,`${e}${g}`,k.headers,v);return v?JSON.parse(v):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),s=o.challenge??o.data?.challenge;if(!s)throw new Error("the node issued no challenge");let a=await Mt(),i=Math.floor(Date.now()/1e3),c=await Le({node:n.node,audience:n.audience,challenge:s,sessionKey:a.publicKey,issuedAt:i,expiresAt:i+(n.ttlSeconds??bs),deviceSecret:n.deviceSecret}),l=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:a.publicKey,client_name:n.clientName??ws(n.audience),timestamp:i,provider_data:{challenge:s,login_statement:c,account_proof:n.accountProof}})}),d=l.access_token??l.data?.access_token,u=l.refresh_token??l.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:u??"",sessionKey:a.publicKey,sessionSecret:a.secret}}var ur=[2428,2429,2528,2529],As="localhost",xs=2e3;function lr(n){return`http://${As}:${n}`}function dr(n,e){let t=n.endsWith("/")?n:`${n}/`;return new URL(e,t).toString()}async function pr(n,e={}){let{timeoutMs:t=xs,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,s=()=>o.abort(),a=r;a&&a.addEventListener("abort",s,{once:!0});let i=setTimeout(()=>o.abort(),t);try{let c=dr(n,"admin-api/health"),l=await fetch(c,{method:"GET",signal:o.signal});if(!l.ok)return!1;try{let d=await l.json(),u=d?.data?.status!==void 0?d?.data?.status:d?.status;return u===void 0?!0:typeof u=="string"&&u.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(i),a&&a.removeEventListener("abort",s)}}async function Rs(n={}){let{ports:e=ur,timeoutMs:t,signal:r}=n;return(await Promise.all(e.map(async s=>{let a=lr(s);return await pr(a,{timeoutMs:t,signal:r})?a:null}))).filter(s=>s!==null)}export{K as AdminApiClient,L as AuthApiClient,_ as AuthRevokedError,ie as CAPABILITIES,j as CloudClient,ur as DEFAULT_LOCAL_NODE_PORTS,Gn as DEFAULT_RELEASE_MIRROR,ce as EphemeralClient,wn as HANDSHAKE_PATH,S as HTTPError,F as IntentRefusedError,dt as LocalStorageTokenStore,lt as MemoryTokenStore,De as MeroJs,Tt as NODE_RELEASE_SIGNER,pe as RelayClient,ae as RpcClient,ke as RpcError,me as SEALED_CONTENT_TYPE,An as SEALED_PATH,Ut as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Z as SealedTransportError,Y as SseClient,he as StaleTransportKeyError,oe as WebHttpClient,X as WsClient,Ie as accountForRoot,Yt as accountRootFromPhrase,B as accountRootFromSecret,Vr as admitterAddrsFromNetworkStatus,Ze as buildAuthLoginUrl,ve as callerProof,Ye as classifyError,Bn as cloudNodeReleaseUrl,je as combineSignals,Sr as compareSemver,Mo as connectCloud,ii as createAdminApiClient,qt as createAdminApiClientFromHttpClient,fe as createAttestedSealedFetch,qs as createAuthApiClient,Gt as createAuthApiClientFromHttpClient,oi as createBrowserAdminApiClient,Hs as createBrowserAuthApiClient,Q as createBrowserHttpClient,Ve as createHttpClient,wt as createLocalStorageNonceSource,bt as createMemoryNonceSource,Qr as createMeroJs,si as createNodeAdminApiClient,$s as createNodeAuthApiClient,we as createNodeHttpClient,Ce as createProofSigner,Ct as createQuoteVerifier,wr as createRetryableMethod,Cn as createSealedFetch,ls as createSignedReleaseSealedFetch,Fn as createSignedReleaseVerifier,Fe as createTimeoutSignal,We as createUniversalHttpClient,mt as creationInitHash,rt as deviceCertPayload,Rs as discoverLocalNodes,qe as encodeSignedInvitation,vn as fetchAttestedTransportKey,Hn as fetchNodeRelease,qn as fetchNodeReleaseVersion,Qt as generateAccountRoot,Mt as generateSessionKey,ht as governanceOpHash,Zn as groupCreatedOp,tr as groupDeletedOp,er as groupReparentedOp,Je as hasCap,Zs as hexEncodeUtf8,gt as intentHash,vr as isSettled,Ee as jsonCodec,lr as localNodeUrl,cr as login,zn as memberAddedOp,Yn as memberLeftOp,Qn as memberRemovedOp,Xn as memberRoleSetOp,Vt as mintDeviceId,dr as nodeEndpoint,$n as nodeReleaseVersionFromImage,Xe as parseAuthCallback,ln as parseCreationWarrant,dn as parseGovernanceWarrant,pr as probeNodeHealth,Ot as redeemInvitation,et as requestBodyHash,Pe as routingProofHeaders,Vs as shouldRetain,le as signAccountLink,Te as signAccountLogin,Ne as signCreationWarrant,Jt as signDeviceCert,_e as signGovernanceWarrant,Le as signLoginStatement,sr as signMemberJoinOp,Re as signRequest,nn as signRoutingChallenge,Ue as signWarrant,on as signerFromCryptoKey,pt as signerFromSecret,Rn as transportKeyBinding,jn as trustSignedRelease,kt as trustedMeasurementsFromReleases,On as verifySignedNodeRelease,ze as withCap,Ae as withRetry,Ks as withoutCap};
|
|
3
3
|
//# sourceMappingURL=index.browser.mjs.map
|