@nodatachat/sdk 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var Dt=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var $r=Object.prototype.hasOwnProperty;var Vr=(n,e)=>{for(var t in e)Dt(n,t,{get:e[t],enumerable:!0})},Gr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qr(e))!$r.call(n,s)&&s!==t&&Dt(n,s,{get:()=>e[s],enumerable:!(r=jr(e,s))||r.enumerable});return n};var zr=n=>Gr(Dt({},"__esModule",{value:!0}),n);var qs={};Vr(qs,{nodataFastify:()=>js});module.exports=zr(qs);var M=class extends Error{constructor(t,r,s,o){super(t);this.status=r;this.code=s;this.retryAfter=o;this.name="NoDataError"}};var Kr="https://www.nodatacapsule.com",Zr=3e4,Xr=2,Je=class{apiKey;baseUrl;timeout;retries;customHeaders;onRequest;onResponse;onError;constructor(e){if(!e.apiKey)throw new Error("NoData SDK: apiKey is required. Get one at https://www.nodatacapsule.com/developers");this.apiKey=e.apiKey,this.baseUrl=(e.baseUrl||Kr).replace(/\/+$/,""),this.timeout=e.timeout||Zr,this.retries=e.retries??Xr,this.customHeaders=e.headers||{},this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.onError=e.onError}async request(e,t,r,s){let o=`${this.baseUrl}${t}`;if(s){let d=new URLSearchParams(Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null))).toString();d&&(o+=`?${d}`)}let i={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...this.customHeaders},signal:AbortSignal.timeout(this.timeout)};r&&e!=="GET"&&(i.body=JSON.stringify(r)),this.onRequest?.(o,i);let a=null,u=1+this.retries;for(let c=1;c<=u;c++){let d=Date.now();try{let l=await fetch(o,i),h=Date.now()-d;if(this.onResponse?.(o,l.status,h),l.status===429&&c<u){let w=parseInt(l.headers.get("Retry-After")||"5",10);await Ht(w*1e3);continue}if(l.status>=500&&c<u){await Ht(1e3*c);continue}let p=await l.json().catch(()=>({}));if(!l.ok)throw new M(p.error||`HTTP ${l.status}`,l.status,p.code,l.status===429?parseInt(l.headers.get("Retry-After")||"60",10):void 0);return p}catch(l){if(a=l instanceof Error?l:new Error(String(l)),this.onError?.(o,a),l instanceof M)throw l;if(c<u){await Ht(1e3*c);continue}}}throw a||new Error("Request failed")}get baseURL(){return this.baseUrl}get(e,t){return this.request("GET",e,void 0,t)}post(e,t){return this.request("POST",e,t)}del(e,t){return this.request("DELETE",e,t)}async raw(e,t,r){let s=`${this.baseUrl}${t}`,o={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...r!==void 0?{"Content-Type":"application/json"}:{},...this.customHeaders},signal:AbortSignal.timeout(this.timeout),...r!==void 0?{body:JSON.stringify(r)}:{}};this.onRequest?.(s,o);let i=Date.now(),a=await fetch(s,o);this.onResponse?.(s,a.status,Date.now()-i);let u=await a.json().catch(()=>({})),c=u&&typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:u;return{ok:a.ok,status:a.status,data:{...c,...u.error?{error:u.error}:{}}}}};function Ht(n){return new Promise(e=>setTimeout(e,n))}var Re=class{constructor(e){this.http=e}async encrypt(e){return this.http.post("/api/v1/encrypt",{field:e.field,value:e.value,context:e.context})}async decrypt(e){return this.http.post("/api/v1/decrypt",{ciphertext:e.ciphertext,field:e.field,requester:e.requester,purpose:e.purpose})}async batchEncrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.encrypt({...o,context:o.context||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,ciphertext:"",field:e[i].field,audit_id:"",algorithm:"",error:o.reason?.message||"Encryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchDecrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.decrypt({...o,requester:o.requester||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,value:"",field:e[i].field,audit_id:"",error:o.reason?.message||"Decryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchNative(e,t){return this.http.post("/api/v1/batch",{items:e,context:t})}async encryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.encrypt({field:o,value:s,context:r})).ciphertext)}async decryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.decrypt({ciphertext:s,field:o,requester:r})).value)}async processObject(e,t,r){if(e==null)return e;if(Array.isArray(e))return Promise.all(e.map(s=>this.processObject(s,t,r)));if(typeof e=="object"){let s={};for(let[o,i]of Object.entries(e))t.includes(o)&&typeof i=="string"&&i.length>0?s[o]=await r(i,o):typeof i=="object"?s[o]=await this.processObject(i,t,r):s[o]=i;return s}return e}};var Ce=class{constructor(e){this.http=e}async registerTable(e){return this.http.post("/api/v1/governance/tables",{table_name:e.table,encrypted_columns:e.encryptedColumns??[],plaintext_columns:e.plaintextColumns??[],classification_column:e.classificationColumn,hkdf_prefix:e.hkdfPrefix,ui_label:e.uiLabel})}async listTables(){return this.http.get("/api/v1/governance/tables")}async grant(e){return this.http.post("/api/v1/governance/grant",{agent:e.agent,table:e.table,columns:e.columns,where:e.where,classifications:e.classifications,ttl_seconds:e.ttlSeconds})}async revoke(e){return this.http.post("/api/v1/governance/revoke",{handle:e.agent,jti:e.jti,reason:e.reason})}},Be=class{constructor(e,t){this.baseURL=e;this.grantToken=t}async read(e){let t=e.handle??Yr(this.grantToken);if(!t)throw new M("AgentReader.read: could not derive agent handle from token; pass { handle }",400);let r=`${this.baseURL}/api/agents/${encodeURIComponent(t)}/read`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.grantToken}`,"Content-Type":"application/json"},body:JSON.stringify({table:e.table,columns:e.columns,where:e.where,limit:e.limit})}),o=await s.json().catch(()=>({}));if(!s.ok)throw new M(o.error||`HTTP ${s.status}`,s.status,o.reason);return o}};function Yr(n){try{let t=(n.startsWith("ndca-")?n.slice(5):n).split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r)).handle??null}catch{return null}}var Qe=class{constructor(e,t){this.http=e;this.ref=t}add(e){let t=e.sections?.length?e.sections:[{label:e.title||"Document",classification:e.classification||"confidential",text:e.content??""}];return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`,{title:e.title,sections:t,recipients:e.recipients,zero_knowledge:e.zero_knowledge})}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`)}},et=class{constructor(e,t){this.http=e;this.ref=t}add(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`)}},tt=class{constructor(e,t){this.http=e;this.ref=t}get(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.limit&&(t.limit=String(e.limit)),this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/audit`,Object.keys(t).length?t:void 0)}},nt=class{constructor(e,t){this.http=e;this.ref=t}grant(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,{action:"revoke",agent_id:e})}read(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-read`,e)}},Te=class{constructor(e,t){this.http=e;this.summary=t;this.documents=new Qe(e,t.slug),this.members=new et(e,t.slug),this.audit=new tt(e,t.slug),this.ai=new nt(e,t.slug)}documents;members;audit;ai;get id(){return this.summary.capsule_id}get slug(){return this.summary.slug}get status(){return this.summary.status}embed(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/embed-token`,e)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/revoke`,{reason:e?.reason})}},Oe=class{constructor(e){this.http=e}async create(e){let t=await this.http.post("/api/v1/capsules",e);return new Te(this.http,t)}async get(e){let t=await this.http.get(`/api/v1/capsules/${encodeURIComponent(e)}`);return new Te(this.http,t)}list(e){return this.http.get("/api/v1/capsules",e?.limit?{limit:String(e.limit)}:void 0)}overview(){return this.http.get("/api/v1/overview")}};var Ie=class{constructor(e){this.http=e}create(e){return this.http.post("/api/v1/tenants",e)}get(e){return this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`)}};var De=class{constructor(e){this.http=e}async orgId(){let e=await this.http.get("/api/v1/partner/me");if(!e?.org_id)throw new Error("nd.scan: could not resolve the org from this API key.");return e.org_id}async enable(e){let t=await this.orgId(),r=await this.http.post(`/api/v1/tenants/${encodeURIComponent(t)}/capsule/install-token`,{}),s=r.install_token??"",o=(e.api_base??this.http.baseURL).replace(/\/+$/,""),i=e.source==="folder"?`--source folder --path ${e.path??"./"}`:e.source==="drive"?`--source drive --folder ${e.folder_id??"<folder-id>"}`:`--source ${e.source}`,a=e.per_customer?` --per-customer ${e.per_customer}`:"";return{ok:!0,scan_id:s.slice(0,12),install_token:s,install_command:`npx @nodatachat/capsule-agent --token ${s} --vault-api --api ${o} ${i}${a}`,expires_at:r.expires_at??null}}async status(){let e=await this.orgId(),t=await this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`);return{deployments:t.capsule?.deployments??[],last_scan_at:t.capsule?.last_scan_at??null,open_findings_count:t.capsule?.open_findings_count??0}}findings(e){let t={};return e?.limit&&(t.limit=String(e.limit)),e?.all&&(t.all="true"),this.http.get("/api/v1/scan/findings",Object.keys(t).length?t:void 0)}approve(e){return this.http.post("/api/v1/scan/approve",{finding_ids:e})}execute(e){return this.http.post("/api/v1/scan/execute",{finding_ids:e})}};var rt=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/secure-channel/init",{label:e.label,ttl:e.ttl||"24h",max_transfers:e.maxTransfers||10,require_verification:e.requireVerification??!1})}async send(e){let t=typeof e.data=="string"?e.data:JSON.stringify(e.data);return this.http.post("/api/secure-channel/upload",{channel_token:e.token,content:t,content_type:e.contentType||"application/json",burn_after_read:e.burnAfterRead??!0})}async receive(e){return this.http.post("/api/secure-channel/download",{channel_token:e.token,verification_code:e.verificationCode})}async verify(e,t){return this.http.post("/api/secure-channel/verify-code",{channel_token:e,code:t})}async proof(e){return this.http.post("/api/secure-channel/delivery-proof",{channel_token:e})}};var st=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/webhook/channel/create",{label:e.label,ttl:e.ttl||"30d",max_events:e.maxEvents||1e4,burn_after_read:e.burnAfterRead??!1})}async events(e,t){return this.http.post("/api/webhook/channel/events",{channel_token:e,limit:t?.limit||50,since:t?.since})}async list(){return this.http.get("/api/webhook/dashboard")}};var ot=class{constructor(e){this.http=e}async send(e){return this.http.post("/api/v1/deliver",{content:e.content,to:e.to,ttl:e.ttl||"24h",burn:e.burn??!0,maxViews:e.maxViews||1})}async burn(e,t){return this.http.post("/api/burn/create",{content:e,ttl_hours:t?.ttlHours||24,burn_after_read:t?.burnAfterRead??!0,available_at:t?.availableAt})}async read(e){return this.http.post("/api/burn/read",{drop_id:e})}};var it=class{constructor(e){this.http=e}async query(e={}){return this.http.get("/api/v1/evidence",{from:e.from||"",to:e.to||"",action:e.action||"",field:e.field||"",limit:String(e.limit||100)})}async certificate(e){return this.http.post("/api/proof-certificate",{audit_id:e})}async verify(e){return this.http.post("/api/receipt/verify",{proof_hash:e})}};var at=class{constructor(e){this.http=e}async create(e){return this.http.post("/api/vault/create",e)}async read(e){return this.http.post("/api/vault/read",{vault_id:e})}async delete(e){return this.http.post("/api/vault/delete",{vault_id:e})}async status(){return this.http.get("/api/vault/status")}};var He=class{governance;blindRelay;channel;deliver;evidence;vault;webhook;constructor(e){this.governance=new Ce(e),this.blindRelay=new Re(e),this.channel=new rt(e),this.deliver=new ot(e),this.evidence=new it(e),this.vault=new at(e),this.webhook=new st(e)}};var Le=class{constructor(e){this.http=e}async run(e){let t=await this.http.post("/api/v1/documents/compute",{question:e.question,clearance:e.clearance??"internal",...e.sections?{sections:e.sections}:{},...e.text?{text:e.text}:{}}),r=(t.sections??[]).map(s=>({title:s.title??"",classification:s.classification??"internal",sent:!!s.sent}));return{decision:t.decision??(r.some(s=>s.sent)?"allow":"deny"),answer:t.answer??null,model:t.model??null,sections:r,proof:{id:t.proof?.receipt_id??t.proof?.id??null,hash:t.proof?.hash??null,persisted:!!t.proof?.persisted}}}async verify(e){let t=await this.http.post("/api/access/verify",{proof_id:e});return{authentic:!!t.authentic,unaltered:!!t.unaltered,signer:t.signer,surface:t.surface,decision:t.decision,issuedAt:t.issued_at}}};function Lt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ie(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof n}`)}if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${n}`)}}function $(n,e,t=""){let r=Lt(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",u=r?`length=${s}`:`type=${typeof n}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):new TypeError(c)}return n}function Ue(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ie(n.outputLen),ie(n.blockLen),n.outputLen<1)throw new Error('"outputLen" must be >= 1');if(n.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ve(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function ct(n,e){$(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function X(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function ut(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Y(n,e){return n<<32-e|n>>>e}var Bn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Wr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function dt(n){if($(n),Bn)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Wr[n[t]];return e}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cn(n){if(n>=ee._0&&n<=ee._9)return n-ee._0;if(n>=ee.A&&n<=ee.F)return n-(ee.A-10);if(n>=ee.a&&n<=ee.f)return n-(ee.a-10)}function Pe(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Bn)try{return Uint8Array.fromHex(n)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Cn(n.charCodeAt(o)),a=Cn(n.charCodeAt(o+1));if(i===void 0||a===void 0){let u=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+a}return r}function Ut(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];$(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function Pt(n,e={}){let t=(s,o)=>n(o).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Tn(n=32){ie(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Ft=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function On(n,e,t){return n&e^~n&t}function In(n,e,t){return n&e^n&t^e&t}var Fe=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){ve(this),$(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let u=ut(e);for(;s<=o-i;i+=s)this.process(u,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)t[l]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let a=ut(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var N=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lt=BigInt(4294967295),Dn=BigInt(32);function Jr(n,e=!1){return e?{h:Number(n&lt),l:Number(n>>Dn&lt)}:{h:Number(n>>Dn&lt)|0,l:Number(n&lt)|0}}function Hn(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Jr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Mt=(n,e,t)=>n>>>t,Nt=(n,e,t)=>n<<32-t|e>>>t,ge=(n,e,t)=>n>>>t|e<<32-t,be=(n,e,t)=>n<<32-t|e>>>t,Me=(n,e,t)=>n<<64-t|e>>>t-32,Ne=(n,e,t)=>n>>>t-32|e<<64-t;function W(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Ln=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),Un=(n,e,t,r)=>e+t+r+(n/2**32|0)|0,Pn=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Fn=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,Mn=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),Nn=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;var es=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ae=new Uint32Array(64),jt=class extends Fe{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:u}=this;return[e,t,r,s,o,i,a,u]}set(e,t,r,s,o,i,a,u){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let l=0;l<16;l++,t+=4)ae[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=ae[l-15],p=ae[l-2],w=Y(h,7)^Y(h,18)^h>>>3,R=Y(p,17)^Y(p,19)^p>>>10;ae[l]=R+ae[l-7]+w+ae[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:u,G:c,H:d}=this;for(let l=0;l<64;l++){let h=Y(a,6)^Y(a,11)^Y(a,25),p=d+h+On(a,u,c)+es[l]+ae[l]|0,R=(Y(r,2)^Y(r,13)^Y(r,22))+In(r,s,o)|0;d=c,c=u,u=a,a=i+p|0,i=o,o=s,s=r,r=p+R|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,o,i,a,u,c,d)}roundClean(){X(ae)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),X(this.buffer)}},qt=class extends jt{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var jn=Hn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),ts=jn[0],ns=jn[1],ce=new Uint32Array(80),ue=new Uint32Array(80),$t=class extends Fe{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:u,Eh:c,El:d,Fh:l,Fl:h,Gh:p,Gl:w,Hh:R,Hl:f}=this;return[e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f]}set(e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=w|0,this.Hh=R|0,this.Hl=f|0}process(e,t){for(let x=0;x<16;x++,t+=4)ce[x]=e.getUint32(t),ue[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let k=ce[x-15]|0,A=ue[x-15]|0,B=ge(k,A,1)^ge(k,A,8)^Mt(k,A,7),E=be(k,A,1)^be(k,A,8)^Nt(k,A,7),C=ce[x-2]|0,S=ue[x-2]|0,D=ge(C,S,19)^Me(C,S,61)^Mt(C,S,6),H=be(C,S,19)^Ne(C,S,61)^Nt(C,S,6),b=Pn(E,H,ue[x-7],ue[x-16]),_=Fn(b,B,D,ce[x-7],ce[x-16]);ce[x]=_|0,ue[x]=b|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:u,Dh:c,Dl:d,Eh:l,El:h,Fh:p,Fl:w,Gh:R,Gl:f,Hh:g,Hl:y}=this;for(let x=0;x<80;x++){let k=ge(l,h,14)^ge(l,h,18)^Me(l,h,41),A=be(l,h,14)^be(l,h,18)^Ne(l,h,41),B=l&p^~l&R,E=h&w^~h&f,C=Mn(y,A,E,ns[x],ue[x]),S=Nn(C,g,k,B,ts[x],ce[x]),D=C|0,H=ge(r,s,28)^Me(r,s,34)^Me(r,s,39),b=be(r,s,28)^Ne(r,s,34)^Ne(r,s,39),_=r&o^r&a^o&a,m=s&i^s&u^i&u;g=R|0,y=f|0,R=p|0,f=w|0,p=l|0,w=h|0,{h:l,l:h}=W(c|0,d|0,S|0,D|0),c=a|0,d=u|0,a=o|0,u=i|0,o=r|0,i=s|0;let v=Ln(D,b,m);r=Un(v,S,H,_),s=v|0}({h:r,l:s}=W(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=W(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:u}=W(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l:d}=W(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:h}=W(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:w}=W(this.Fh|0,this.Fl|0,p|0,w|0),{h:R,l:f}=W(this.Gh|0,this.Gl|0,R|0,f|0),{h:g,l:y}=W(this.Hh|0,this.Hl|0,g|0,y|0),this.set(r,s,o,i,a,u,c,d,l,h,p,w,R,f,g,y)}roundClean(){X(ce,ue)}destroy(){this.destroyed=!0,X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vt=class extends $t{Ah=N[0]|0;Al=N[1]|0;Bh=N[2]|0;Bl=N[3]|0;Ch=N[4]|0;Cl=N[5]|0;Dh=N[6]|0;Dl=N[7]|0;Eh=N[8]|0;El=N[9]|0;Fh=N[10]|0;Fl=N[11]|0;Gh=N[12]|0;Gl=N[13]|0;Hh=N[14]|0;Hl=N[15]|0;constructor(){super(64)}};var je=Pt(()=>new qt,Ft(1));var ft=Pt(()=>new Vt,Ft(3));var O=(n,e,t)=>$(n,e,t),zt=ie,Kt=dt,J=(...n)=>Ut(...n),qn=n=>Pe(n),gt=Lt,bt=n=>Tn(n),ht=BigInt(0),Gt=BigInt(1);function Ee(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof n)}return n}function rs(n){if(typeof n=="bigint"){if(!pt(n))throw new RangeError("positive bigint expected, got "+n)}else zt(n);return n}function ne(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function $n(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?ht:BigInt("0x"+n)}function Zt(n){return $n(dt(n))}function K(n){return $n(dt(de($(n)).reverse()))}function Xt(n,e){if(ie(e),e===0)throw new RangeError("zero length");n=rs(n);let t=n.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pe(t.padStart(e*2,"0"))}function mt(n,e){return Xt(n,e).reverse()}function Vn(n,e){if(n=O(n),e=O(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function de(n){return Uint8Array.from(O(n))}function yt(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var pt=n=>typeof n=="bigint"&&ht<=n;function ss(n,e,t){return pt(n)&&pt(e)&&pt(t)&&e<=n&&n<t}function ke(n,e,t,r){if(!ss(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Yt(n){if(n<ht)throw new Error("expected non-negative bigint, got "+n);let e;for(e=0;n>ht;n>>=Gt,e+=1);return e}var Gn=n=>(Gt<<BigInt(n))-Gt;function re(n,e={},t={}){if(Object.prototype.toString.call(n)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(n,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=n[o];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${c}`)}let s=(o,i)=>Object.entries(o).forEach(([a,u])=>r(a,u,i));s(e,!1),s(t,!0)}var Wt=()=>{throw new Error("not implemented")};var j=BigInt(0),P=BigInt(1),me=BigInt(2),Xn=BigInt(3),Yn=BigInt(4),Wn=BigInt(5),os=BigInt(7),Jn=BigInt(8),is=BigInt(9),Qn=BigInt(16);function I(n,e){if(e<=j)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=j?t:e+t}function Z(n,e,t){if(e<j)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >j;)r*=r,r%=t;return r}function zn(n,e){if(n===j)throw new Error("invert: expected non-zero number");if(e<=j)throw new Error("invert: expected positive modulus, got "+e);let t=I(n,e),r=e,s=j,o=P,i=P,a=j;for(;t!==j;){let c=r/t,d=r-t*c,l=s-i*c,h=o-a*c;r=t,t=d,s=i,o=a,i=l,a=h}if(r!==P)throw new Error("invert: does not exist");return I(s,e)}function Jt(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function er(n,e){let t=n,r=(t.ORDER+P)/Yn,s=t.pow(e,r);return Jt(t,s,e),s}function as(n,e){let t=n,r=(t.ORDER-Wn)/Jn,s=t.mul(e,me),o=t.pow(s,r),i=t.mul(e,o),a=t.mul(t.mul(i,me),o),u=t.mul(i,t.sub(a,t.ONE));return Jt(t,u,e),u}function cs(n){let e=wt(n),t=tr(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+os)/Qn;return((a,u)=>{let c=a,d=c.pow(u,i),l=c.mul(d,r),h=c.mul(d,s),p=c.mul(d,o),w=c.eql(c.sqr(l),u),R=c.eql(c.sqr(h),u);d=c.cmov(d,l,w),l=c.cmov(p,h,R);let f=c.eql(c.sqr(l),u),g=c.cmov(d,l,f);return Jt(c,g,u),g})}function tr(n){if(n<Xn)throw new Error("sqrt is not defined for small field");let e=n-P,t=0;for(;e%me===j;)e/=me,t++;let r=me,s=wt(n);for(;Kn(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return er;let o=s.pow(r,e),i=(e+P)/me;return function(u,c){let d=u;if(d.is0(c))return c;if(Kn(d,c)!==1)throw new Error("Cannot find square root");let l=t,h=d.mul(d.ONE,o),p=d.pow(c,e),w=d.pow(c,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))return d.ZERO;let R=1,f=d.sqr(p);for(;!d.eql(f,d.ONE);)if(R++,f=d.sqr(f),R===l)throw new Error("Cannot find square root");let g=P<<BigInt(l-R-1),y=d.pow(h,g);l=R,h=d.sqr(y),p=d.mul(p,h),w=d.mul(w,y)}return w}}function us(n){return n%Yn===Xn?er:n%Jn===Wn?as:n%Qn===is?cs(n):tr(n)}var se=(n,e)=>(I(n,e)&P)===P,ds=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nr(n){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ds.reduce((r,s)=>(r[s]="function",r),e);if(re(n,t),ne(n.BYTES,"BYTES"),ne(n.BITS,"BITS"),n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ls(n,e,t){let r=n;if(t<j)throw new Error("invalid exponent, negatives unsupported");if(t===j)return r.ONE;if(t===P)return e;let s=r.ONE,o=e;for(;t>j;)t&P&&(s=r.mul(s,o)),o=r.sqr(o),t>>=P;return s}function _t(n,e,t=!1){let r=n,s=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,u,c)=>r.is0(u)?a:(s[c]=a,r.mul(a,u)),r.ONE),i=r.inv(o);return e.reduceRight((a,u,c)=>r.is0(u)?a:(s[c]=r.mul(a,s[c]),r.mul(a,u)),i),s}function Kn(n,e){let t=n,r=(t.ORDER-P)/me,s=t.pow(e,r),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function fs(n,e){if(e!==void 0&&zt(e),n<=j)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Yt(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}var Zn=new WeakMap,xt=class{ORDER;BITS;BYTES;isLE;ZERO=j;ONE=P;_lengths;_mod;constructor(e,t={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=fs(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return I(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return j<=e&&e<this.ORDER}is0(e){return e===j}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&P)===P}neg(e){return I(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return I(e*e,this.ORDER)}add(e,t){return I(e+t,this.ORDER)}sub(e,t){return I(e-t,this.ORDER)}mul(e,t){return I(e*t,this.ORDER)}pow(e,t){return ls(this,e,t)}div(e,t){return I(e*zn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return zn(e,this.ORDER)}sqrt(e){let t=Zn.get(this);return t||Zn.set(this,t=us(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?mt(e,this.BYTES):Xt(e,this.BYTES)}fromBytes(e,t=!1){O(e);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let u=o?K(e):Zt(e);if(a&&(u=I(u,i)),!t&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return _t(this,e)}cmov(e,t,r){return Ee(r,"condition"),r?t:e}};Object.freeze(xt.prototype);function wt(n,e={}){return new xt(n,e)}var Rt=BigInt(0),nn=BigInt(1);function rr(n,e){let t=e.negate();return n?t:e}function Et(n,e){let t=_t(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function ar(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Qt(n,e){ar(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=Gn(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function sr(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),u=n>>i;a>r&&(a-=o,u+=nn);let c=e*r,d=c+Math.abs(a)-1,l=a===0,h=a<0,p=e%2!==0;return{nextN:u,offset:d,isZero:l,isNeg:h,isNegF:p,offsetF:c}}var en=new WeakMap,cr=new WeakMap;function tn(n){return cr.get(n)||1}function or(n){if(n!==Rt)throw new Error("invalid wNAF")}var vt=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Rt;)t&nn&&(r=r.add(s)),s=s.double(),t>>=nn;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Qt(t,this.bits),o=[],i=e,a=i;for(let u=0;u<r;u++){a=i,o.push(a);for(let c=1;c<s;c++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Qt(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:d,isNeg:l,isNegF:h,offsetF:p}=sr(r,a,i);r=u,d?o=o.add(rr(h,t[p])):s=s.add(rr(l,t[c]))}return or(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Qt(e,this.bits);for(let i=0;i<o.windows&&r!==Rt;i++){let{nextN:a,offset:u,isZero:c,isNeg:d}=sr(r,i,o);if(r=a,!c){let l=t[u];s=s.add(d?l.negate():l)}}return or(r),s}getPrecomputes(e,t,r){let s=en.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),en.set(t,s))),s}cached(e,t,r){let s=tn(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=tn(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){ar(t,this.bits),cr.set(e,t),en.delete(e)}hasCache(e){return tn(e)!==1}};function ir(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nr(e),e}else return wt(n,{isLE:t})}function ur(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let u of["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Rt))throw new Error(`CURVE.${u} must be positive bigint`)}let s=ir(e.p,t.Fp,r),o=ir(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let u of a)if(!s.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function kt(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var le=BigInt(0),F=BigInt(1),rn=BigInt(2),ps=BigInt(8);function hs(n,e,t,r){let s=n.sqr(t),o=n.sqr(r),i=n.add(n.mul(e.a,s),o),a=n.add(n.ONE,n.mul(e.d,n.mul(s,o)));return n.eql(i,a)}function dr(n,e={}){let t=e,r=ur("edwards",n,t,t.FpFnLE),{Fp:s,Fn:o}=r,i=r.CURVE,{h:a}=i;re(t,{},{uvRatio:"function"});let u=rn<<BigInt(o.BYTES*8)-F,c=R=>s.create(R),d=t.uvRatio===void 0?(R,f)=>{try{return{isValid:!0,value:s.sqrt(s.div(R,f))}}catch{return{isValid:!1,value:le}}}:t.uvRatio;if(!hs(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(R,f,g=!1){let y=g?F:le;return ke("coordinate "+R,f,y,u),f}function h(R){if(!(R instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,F,c(i.Gx*i.Gy));static ZERO=new p(le,F,F,le);static Fp=s;static Fn=o;X;Y;Z;T;constructor(f,g,y,x){this.X=l("x",f),this.Y=l("y",g),this.Z=l("z",y,!0),this.T=l("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(f){if(f instanceof p)throw new Error("extended point not allowed");let{x:g,y}=f||{};return l("x",g),l("y",y),new p(g,y,F,c(g*y))}static fromBytes(f,g=!1){let y=s.BYTES,{a:x,d:k}=i;f=de(O(f,y,"point")),Ee(g,"zip215");let A=de(f),B=f[y-1];A[y-1]=B&-129;let E=K(A),C=g?u:s.ORDER;ke("point.y",E,le,C);let S=c(E*E),D=c(S-F),H=c(k*S-x),{isValid:b,value:_}=d(D,H);if(!b)throw new Error("bad point: invalid y coordinate");let m=(_&F)===F,v=(B&128)!==0;if(!g&&_===le&&v)throw new Error("bad point: x=0 and x_0=1");return v!==m&&(_=c(-_)),p.fromAffine({x:_,y:E})}static fromHex(f,g=!1){return p.fromBytes(qn(f),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,g=!0){return w.createCache(this,f),g||this.multiply(rn),this}assertValidity(){let f=this,{a:g,d:y}=i;if(f.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:A,T:B}=f,E=c(x*x),C=c(k*k),S=c(A*A),D=c(S*S),H=c(E*g),b=c(S*c(H+C)),_=c(D+c(y*c(E*C)));if(b!==_)throw new Error("bad point: equation left != right (1)");let m=c(x*k),v=c(A*B);if(m!==v)throw new Error("bad point: equation left != right (2)")}equals(f){h(f);let{X:g,Y:y,Z:x}=this,{X:k,Y:A,Z:B}=f,E=c(g*B),C=c(k*x),S=c(y*B),D=c(A*x);return E===C&&S===D}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:f}=i,{X:g,Y:y,Z:x}=this,k=c(g*g),A=c(y*y),B=c(rn*c(x*x)),E=c(f*k),C=g+y,S=c(c(C*C)-k-A),D=E+A,H=D-B,b=E-A,_=c(S*H),m=c(D*b),v=c(S*b),T=c(H*D);return new p(_,m,T,v)}add(f){h(f);let{a:g,d:y}=i,{X:x,Y:k,Z:A,T:B}=this,{X:E,Y:C,Z:S,T:D}=f,H=c(x*E),b=c(k*C),_=c(B*y*D),m=c(A*S),v=c((x+k)*(E+C)-H-b),T=m-_,L=m+_,U=c(b-g*H),q=c(v*T),V=c(L*U),G=c(v*U),z=c(T*L);return new p(q,V,z,G)}subtract(f){return h(f),this.add(f.negate())}multiply(f){if(!o.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:y}=w.cached(this,f,x=>Et(p,x));return Et(p,[g,y])[0]}multiplyUnsafe(f){if(!o.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===le?p.ZERO:this.is0()||f===F?this:w.unsafe(this,f,g=>Et(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(f){let g=this,y=f,{X:x,Y:k,Z:A}=g,B=g.is0();y==null&&(y=B?ps:s.inv(A));let E=c(x*y),C=c(k*y),S=s.mul(A,y);if(B)return{x:le,y:F};if(S!==F)throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===F?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:g}=this.toAffine(),y=s.toBytes(g);return y[y.length-1]|=f&F?128:0,y}toHex(){return Kt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new vt(p,o.BITS);return o.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Wt()}static fromHex(e){Wt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Kt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function lr(n,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,s=t;re(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:u}=n,c=r.outputLen,d=2*a.BYTES;if(c!==void 0&&(ne(c,"hash.outputLen"),c!==d))throw new Error(`hash.outputLen must be ${d}, got ${c}`);let l=s.randomBytes===void 0?bt:s.randomBytes,h=s.adjustScalarBytes===void 0?b=>b:s.adjustScalarBytes,p=s.domain===void 0?(b,_,m)=>{if(Ee(m,"phflag"),_.length||m)throw new Error("Contexts/pre-hash are not supported");return b}:s.domain;function w(b){return u.create(K(b))}function R(b){let _=E.secretKey;O(b,E.secretKey,"secretKey");let m=O(r(b),2*_,"hashedSecretKey"),v=h(m.slice(0,_)),T=m.slice(_,2*_),L=w(v);return{head:v,prefix:T,scalar:L}}function f(b){let{head:_,prefix:m,scalar:v}=R(b),T=i.multiply(v),L=T.toBytes();return{head:_,prefix:m,scalar:v,point:T,pointBytes:L}}function g(b){return f(b).pointBytes}function y(b=Uint8Array.of(),..._){let m=J(..._);return w(r(p(m,O(b,void 0,"context"),!!o)))}function x(b,_,m={}){b=O(b,void 0,"message"),o&&(b=o(b));let{prefix:v,scalar:T,pointBytes:L}=f(_),U=y(m.context,v,b),q=i.multiply(U).toBytes(),V=y(m.context,q,L,b),G=u.create(U+V*T);if(!u.isValid(G))throw new Error("sign failed: invalid s");let z=J(q,u.toBytes(G));return O(z,E.signature,"result")}let k={zip215:s.zip215};function A(b,_,m,v=k){let{context:T}=v,L=v.zip215===void 0?!!k.zip215:v.zip215,U=E.signature;b=O(b,U,"signature"),_=O(_,void 0,"message"),m=O(m,E.publicKey,"publicKey"),L!==void 0&&Ee(L,"zip215"),o&&(_=o(_));let q=U/2,V=b.subarray(0,q),G=K(b.subarray(q,U)),z,Ze,we;try{z=n.fromBytes(m,L),Ze=n.fromBytes(V,L),we=i.multiplyUnsafe(G)}catch{return!1}if(!L&&z.isSmallOrder())return!1;let Xe=y(T,V,m,_);return Ze.add(z.multiplyUnsafe(Xe)).subtract(we).clearCofactor().is0()}let B=a.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function C(b){return b=b===void 0?l(E.seed):b,O(b,E.seed,"seed")}function S(b){return gt(b)&&b.length===E.secretKey}function D(b,_){try{return!!n.fromBytes(b,_===void 0?k.zip215:_)}catch{return!1}}let H={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:S,isValidPublicKey:D,toMontgomery(b){let{y:_}=n.fromBytes(b),m=E.publicKey,v=m===32;if(!v&&m!==57)throw new Error("only defined for 25519 and 448");let T=v?a.div(F+_,F-_):a.div(_-F,_+F);return a.toBytes(T)},toMontgomerySecret(b){let _=E.secretKey;O(b,_);let m=r(b.subarray(0,_));return h(m).subarray(0,_)}};return Object.freeze(E),Object.freeze(H),Object.freeze({keygen:kt(C,g),getPublicKey:g,sign:x,verify:A,utils:H,Point:n,lengths:E})}function qe(n,e){if(ne(n),ne(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(n<0||n>2**(8*e)-1)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function gs(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function bs(n){if(!gt(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof n=="string"?yt(n):n;if(e.length===0)throw new Error("DST must be non-empty");return e}function sn(n,e,t,r){O(n),ne(t),e=bs(e),e.length>255&&(e=r(J(yt("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=r,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=J(e,qe(e.length,1)),u=new Uint8Array(o),c=qe(t,2),d=new Array(i),l=r(J(u,n,c,qe(0,1),a));d[0]=r(J(l,qe(1,1),a));for(let p=1;p<i;p++){let w=[gs(l,d[p-1]),qe(p+1,1),a];d[p]=r(J(...w))}return J(...d).slice(0,t)}var fr="HashToScalar-";var $e=BigInt(0),Ae=BigInt(1),St=BigInt(2);function ms(n){return re(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...n})}function pr(n){let e=ms(n),{P:t,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");let u=i===void 0?bt:i,c=a?255:448,d=a?32:56,l=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?St**BigInt(254):St**BigInt(447),w=a?BigInt(8)*St**BigInt(251)-Ae:BigInt(4)*St**BigInt(445)-Ae,R=p+w+Ae,f=m=>I(m,t),g=y(l);function y(m){return mt(f(m),d)}function x(m){let v=de(O(m,d,"uCoordinate"));return a&&(v[31]&=127),f(K(v))}function k(m){return K(s(de(O(m,d,"scalar"))))}function A(m,v){let T=D(x(v),k(m));if(T===$e)throw new Error("invalid private or public key received");return y(T)}function B(m){return A(m,g)}let E=B,C=A;function S(m,v,T){let L=f(m*(v-T));return v=f(v-L),T=f(T+L),{x_2:v,x_3:T}}function D(m,v){ke("u",m,$e,t),ke("scalar",v,p,R);let T=v,L=m,U=Ae,q=$e,V=m,G=Ae,z=$e;for(let we=BigInt(c-1);we>=$e;we--){let Xe=T>>we&Ae;z^=Xe,{x_2:U,x_3:V}=S(z,U,V),{x_2:q,x_3:G}=S(z,q,G),z=Xe;let Ye=U+q,We=f(Ye*Ye),It=U-q,Rn=f(It*It),vn=We-Rn,Mr=V+G,Nr=V-G,En=f(Nr*Ye),kn=f(Mr*It),An=En+kn,Sn=En-kn;V=f(An*An),G=f(L*f(Sn*Sn)),U=f(We*Rn),q=f(vn*(We+f(h*vn)))}({x_2:U,x_3:V}=S(z,U,V)),{x_2:q,x_3:G}=S(z,q,G);let Ze=o(q);return f(U*Ze)}let H={secretKey:d,publicKey:d,seed:d},b=m=>(m=m===void 0?u(d):m,O(m,H.seed,"seed"),m),_={randomSecretKey:b};return Object.freeze(H),Object.freeze(_),Object.freeze({keygen:kt(b,E),getSharedSecret:C,getPublicKey:E,scalarMult:A,scalarMultBase:B,utils:_,GuBytes:g.slice(),lengths:H})}var ys=BigInt(0),oe=BigInt(1),hr=BigInt(2),xs=BigInt(3),_s=BigInt(5),ws=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),un={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ws,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function mr(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),o=ye,a=n*n%o*n%o,u=Z(a,hr,o)*a%o,c=Z(u,oe,o)*n%o,d=Z(c,_s,o)*c%o,l=Z(d,e,o)*d%o,h=Z(l,t,o)*l%o,p=Z(h,r,o)*h%o,w=Z(p,s,o)*p%o,R=Z(w,s,o)*p%o,f=Z(R,e,o)*d%o;return{pow_p_5_8:Z(f,hr,o)*n%o,b2:a}}function yr(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var on=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dn(n,e){let t=ye,r=I(e*e*e,t),s=I(r*r*e,t),o=mr(n*s).pow_p_5_8,i=I(n*r*o,t),a=I(e*i*i,t),u=i,c=I(i*on,t),d=a===n,l=a===I(-n,t),h=a===I(-n*on,t);return d&&(i=u),(l||h)&&(i=c),se(i,t)&&(i=I(-i,t)),{isValid:d||l,value:i}}var pe=dr(un,{uvRatio:dn}),fe=pe.Fp,xr=pe.Fn;function Rs(n){return lr(pe,ft,Object.assign({adjustScalarBytes:yr,zip215:!0},n))}var _r=Rs({});var xe=(()=>{let n=ye;return pr({P:n,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:r}=mr(e);return I(Z(t,xs,n)*r,n)},adjustScalarBytes:yr})})();var an=on,vs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Es=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ks=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),As=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),gr=n=>dn(oe,n),Ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),cn=n=>fe.create(K(n)&Ss);function br(n){let{d:e}=un,t=ye,r=g=>fe.create(g),s=r(an*n*n),o=r((s+oe)*ks),i=BigInt(-1),a=r((i-e*s)*r(s+e)),{isValid:u,value:c}=dn(o,a),d=r(c*n);se(d,t)||(d=r(-d)),u||(c=d),u||(i=s);let l=r(i*(s-oe)*As-a),h=c*c,p=r((c+c)*a),w=r(l*vs),R=r(oe-h),f=r(oe+h);return new pe(r(p*f),r(R*w),r(w*f),r(p*R))}var he=class n extends At{static BASE=new n(pe.BASE);static ZERO=new n(pe.ZERO);static Fp=fe;static Fn=xr;constructor(e){super(e)}static fromAffine(e){return new n(pe.fromAffine(e))}assertSame(e){if(!(e instanceof n))throw new Error("RistrettoPoint expected")}init(e){return new n(e)}static fromBytes(e){$(e,32);let{a:t,d:r}=un,s=ye,o=k=>fe.create(k),i=cn(e);if(!Vn(fe.toBytes(i),e)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),u=o(oe+t*a),c=o(oe-t*a),d=o(u*u),l=o(c*c),h=o(t*r*d-l),{isValid:p,value:w}=gr(o(h*l)),R=o(w*c),f=o(w*R*h),g=o((i+i)*R);se(g,s)&&(g=o(-g));let y=o(u*f),x=o(g*y);if(!p||se(x,s)||y===ys)throw new Error("invalid ristretto255 encoding 2");return new n(new pe(g,y,oe,x))}static fromHex(e){return n.fromBytes(Pe(e))}toBytes(){let{X:e,Y:t,Z:r,T:s}=this.ep,o=ye,i=f=>fe.create(f),a=i(i(r+t)*i(r-t)),u=i(e*t),c=i(u*u),{value:d}=gr(i(a*c)),l=i(d*a),h=i(d*u),p=i(l*h*s),w;if(se(s*p,o)){let f=i(t*an),g=i(e*an);e=f,t=g,w=i(l*Es)}else w=h;se(e*p,o)&&(t=i(-t));let R=i((r-t)*w);return se(R,o)&&(R=i(-R)),fe.toBytes(R)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:s,Y:o}=e.ep,i=c=>fe.create(c),a=i(t*o)===i(r*s),u=i(r*o)===i(t*s);return a||u}is0(){return this.equals(n.ZERO)}};Object.freeze(he.BASE);Object.freeze(he.ZERO);Object.freeze(he.prototype);Object.freeze(he);var Cs=Object.freeze({Point:he,hashToCurve(n,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=sn(n,t,64,ft);return Cs.deriveToCurve(r)},hashToScalar(n,e={DST:fr}){let t=sn(n,e.DST,64,ft);return xr.create(K(t))},deriveToCurve(n){$(n,64);let e=cn(n.subarray(0,32)),t=br(e),r=cn(n.subarray(32,64)),s=br(r);return new he(t.add(s))}});var Ct=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ue(e),$(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),X(s)}update(e){return ve(this),this.iHash.update(e),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ln=(()=>{let n=((e,t,r)=>new Ct(e,t).update(r).digest());return n.create=(e,t)=>new Ct(e,t),n})();function Bs(n,e,t){return Ue(n),t===void 0&&(t=new Uint8Array(n.outputLen)),ln(n,t,e)}var fn=Uint8Array.of(0),wr=Uint8Array.of();function Ts(n,e,t,r=32){Ue(n),ie(r,"length"),$(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(r/s);t===void 0?t=wr:$(t,void 0,"info");let i=new Uint8Array(o*s),a=ln.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let d=0;d<o;d++)fn[0]=d+1,u.update(d===0?wr:c).update(t).update(fn).digestInto(c),i.set(c,s*d),a._cloneInto(u);return a.destroy(),u.destroy(),X(c,fn),i.slice(0,r)}var Rr=(n,e,t,r,s)=>Ts(n,Bs(n,e,t),r,s);var Os=new TextEncoder().encode("mygate-e2e-sealed-box-v1"),Ve=32,Se=12;function pn(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function hn(n){if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}return new Uint8Array(Buffer.from(n,"base64"))}function Ge(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function _e(n){if(n.length%2!==0)throw new Error("hex length must be even");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function vr(...n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Er(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function kr(){return xe.utils.randomSecretKey()}function gn(n){return xe.getPublicKey(n)}async function Ar(n){if(n.length!==32)throw new Error(`AES-256-GCM key must be 32 bytes, got ${n.length}`);return globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Sr(n,e){let t=await Ar(n),r=Er(Se),s=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,e);return{ciphertext:new Uint8Array(s),nonce:r}}async function Cr(n,e,t){if(t.length!==Se)throw new Error(`AES-GCM nonce must be ${Se} bytes`);let r=await Ar(n),s=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:t},r,e);return new Uint8Array(s)}function Br(n,e,t){return Rr(je,n,vr(e,t),Os,32)}async function Is(n,e){if(n.length!==32)throw new Error("X25519 recipient public key must be 32 bytes");let t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=xe.getSharedSecret(t,n),o=Br(s,r,n),{ciphertext:i,nonce:a}=await Sr(o,e);return vr(r,a,i)}async function Ds(n,e,t){if(t.length<Ve+Se+16)throw new Error("sealed box payload too short");let r=t.slice(0,Ve),s=t.slice(Ve,Ve+Se),o=t.slice(Ve+Se),i=xe.getSharedSecret(n,r),a=Br(i,r,e);return Cr(a,o,s)}async function Tr(n,e){let t=Er(32),{ciphertext:r,nonce:s}=await Sr(t,e),o=await Is(_e(n),t);return{ciphertext_b64:pn(r),wrapped_key_b64:pn(o),payload_iv_b64:pn(s)}}async function Or(n,e){let t=_e(n),r=gn(t),s=await Ds(t,r,hn(e.wrapped_key_b64));return Cr(s,hn(e.ciphertext_b64),hn(e.payload_iv_b64))}var Ir="application/vnd.nodata.command+json",Dr="nodata.command/1";var Hs=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Ls=/^[a-z][a-z0-9_]{0,63}$/;function bn(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not_an_object"};let e=n,t=new Set(["nodata","id","cmd","fields","reply_to","issued_at"]),r=Object.keys(e).filter(i=>!t.has(i));if(r.length)return{ok:!1,reason:`unexpected_keys:${r.join(",")}`};if(e.nodata!==Dr)return{ok:!1,reason:"not_a_command"};if(typeof e.id!="string"||!/^[0-9a-f-]{36}$/i.test(e.id))return{ok:!1,reason:"bad_id"};if(typeof e.cmd!="string"||!Hs.test(e.cmd))return{ok:!1,reason:"bad_cmd"};if(e.reply_to!==null&&(typeof e.reply_to!="string"||!/^[0-9a-f-]{36}$/i.test(e.reply_to)))return{ok:!1,reason:"bad_reply_to"};if(typeof e.issued_at!="string"||Number.isNaN(Date.parse(e.issued_at)))return{ok:!1,reason:"bad_issued_at"};if(!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return{ok:!1,reason:"bad_fields"};let s=e.fields,o=Object.keys(s);if(o.length>64)return{ok:!1,reason:"too_many_fields"};for(let i of o){if(!Ls.test(i))return{ok:!1,reason:`bad_field_name:${i}`};let a=s[i];if(!(a===null||typeof a=="boolean"||typeof a=="number"||typeof a=="string"))return{ok:!1,reason:`field_not_flat:${i}`};if(typeof a=="string"&&a.length>2e3)return{ok:!1,reason:`field_too_long:${i}`}}return{ok:!0,envelope:e}}function Hr(n,e,t=null,r=new Date){let s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():Us();return{nodata:Dr,id:s,cmd:n,fields:e,reply_to:t,issued_at:r.toISOString()}}function Us(){let n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function mn(n){let e=t=>t===null||typeof t!="object"?t:Array.isArray(t)?t.map(e):Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])]));return JSON.stringify(e(n))}var ri={"read-request":{name:"request.json",maxBytes:16384},"read-refused":{name:"refused.json",maxBytes:16384},"folder-projection":{name:"projection.json",maxBytes:48*1024}};var yn={version:1,note:"NoData's public signing keys, pinned. chain_keys sign receipts and epoch seal roots; pack_envelope_signers sign evidence-pack envelopes. Source: https://nodatachat.com/api/chain/pubkey at publish time. A key counts only once a published version of this package lists it. receipt_context_since: when the key began signing receipts in their signing context (server mig 612, read from production 2026-10-19); a context-free receipt it signed after that (+15 min) fails verification.",pinned_from:"https://nodatachat.com/api/chain/pubkey (chain key, read 2026-09-30) \xB7 claude_identities where admin_user_id = the pack-signing identity (envelope signer, read 2026-09-30)",chain_keys:[{kid:"nd-chain-2026-05-03-bc58",ed25519_pubkey_hex:"b525adfa0035d5c7351b514a0316142586de9468ec5ee3b708cff0c4585b5036",ml_dsa65_pubkey_hex:"cc46f06f86d1b4a608a4c1167f1494a4cd1a837d215ff88e7b1aca49e82be3f32e190e1836d477670bae2c8a6f7648d3ce0d93b2f51ab0d3150d7dd45b0cf8217f119388e5a4b3770459654c4b0caab4d8a0ccdafdbc5231cd6c26410c38cd0ec62b21bf73b8e1e82daca3b1e4d520d9d25041917f4fd2b92bb19ffbe50f569ca29fa0185923732949daf5f832805303ef5a020cf3ea9de395d66e54d9bf52a56875087096cd8470918b7f25d623335c8662e7c8e6cefce7b88cc4cc6f7d32ed0f1a00332606af78332e9febb72b7e77b396b9da5ff96167055305595327ead40d2084a50f0d3fcd2423d8ed46edc5459ed1b0ff5a14f142bb38511b99a6da841895ccd65c19ab856bbdee270b48bc01ee8b0243fbc6e806851831409e5ae90d9c3300a9125042fd9b6d381c3eb09d5ee6f33e36bd5b41572bcce0350af8e217963154b550a163c5203f9a38a65312f23088c568d5af720c2ff4e979491109ca9ffdb9edc46f31410939e0264cbc02ea0106f9d6c8616222655e6593f8be5b9fa4423afec46aea9d53e42eb5d3f976cdd86d978a4599b87198d4fb8054bc40828f4d0100131537030053645616ecf48d013f8bbafb3a404735b7ffd6c88273765af340e84207f48be92e909ece357fa6ea2050e085570f413e48179a5aaac2bf216e54714d3ee1102e91fd23305b50b14b133299be4517d074732976b003a6669ecbceb2e40a8a1b2f4ca2b2a25d017b404b21672a0de61a45fd153684d730dc126f30a406d6b06447180258a9659cb3de926abd997b3f740c2783e334dd914ac663abc7f96217844ef0611619c35e30ed55f1563d8183b9f586d6c34715ce68708806105426e897df1473d53da835bed6288951238ed694c154655455ff61e13caeb592cc2857537fe9d2eb723bcad3898396af9673ba5b2f722092f0d2a9388e960ccde7272df5e2fe0ea9e499a909b655a59c85cfa1c622c651c8af20b4fb8bab9ab78d951c621d4b75c812246b2e925bcde42cc6a0a13467b4bcfb9aea5e4949effc71769dccc619eafc6d229cba478e3ad7289dc14b0c4842b4cf0cadd30deb9375fc1659d084779819705a6da7bccbf8d21ecd82391de5b61126d5b872f7d95514717b6fdc218dc0a048364c46142b114ee10d582740668f5b105edc034eb794c7e3906c77a44677e67709dbb1d3078783b488473e83e457e6ab98d2d659cf50066bc7f01190e065a9ef955e0257535bd5fab8ad007673637b2d005349e7f19fea2eeea82597867d5e366e41993775e4f4f70869fb1f9989d6d9902787f8233e9c7e586fe6bcf799ecf2da02ce08232ef1315b4e8857bcdb58bda53991f529d2ff023d0279552396dd0bb0fceaaf5dfb9eda0160bb09dd92b8085bc92c6006c20409cf9a5079072a09df221a76efc5ec13c97d154d22e382018ed8eb767f77aae578121c2231fe964338e637e7c060d555a2574b49c08956c729e79090b917e162488b1c9e962a3a921ac6f98a8c020c48aa2812f2f7a205a2d23aa2be1a953d9e33fbdea94688cf3d44200ed2cb009be8b684e99a96f0bc59eff5490eee0636b8b5665d7ddbb6ad44b90caa62b524f8a1caf6d0dbbc5e2ef0c2e65976d94e80e8dbd5ab8a420fdb638562bd2181c0ca243496582bab2847394e1e2dd4a24d4b24794b770b2475916746fb2bdc50f7994b4b346bfcfc5b4a99266cdf551340903d6994206ae1edb968c15d89f2a4cc6f3cb27b88989489b598f76fb6d1afa52e3a4c73175a216fa30d76acfccade7adb5628a88931b37bcff93c615a78a0b47827e385395e0b53c683f2ff07dd6cc636a086c295f06766570fc7652568676ecc5869378bdc0a63753807f1c7de7e5525d48328fa4103ed2ce9abafe0dc861055be6943cf2a87371ec1f9205c1955ddcf2f2ca982d877040dc92bf64278273c5ebbe3de0ef9d5eae255359e7ac97123b92488ffd0f1ea7deca36110135e02988be06bba4a3bf1b0da067976a6bc0c166ac349b2a853eb204fec6c142cad3decb05da15448f0d82d5faed3bc4beb400c51e05de06d950c128e2d3323a2d47dbf88684970084ed6608b95d7d585c3762c714c063c0a4ce1cacd5b31f261376bd972982957150dbbeb158999c1f60a76c6233a8749c10c016e0ad69bdac19e8c4d28126b7cc79c79aa82c25cef5521afdd759ca198b77c1a4a5f2c0497a4136e9818113c612d109de2cfaba691e05b791474599bf5cb918097f07b95dde658d2c5c01bf2bb6715dcb40c4c5686ec1642f9fd84377a90ea2456561ff91ba798d98211975c3da57be1b1e57a4660f979407e5f8616c4f62730161d2dcd86cf5383665c64cb77abbcf2e1406bc189e9575e3c1407aa6a467e6bd7a8edf7affde32b88dfa178902163a37c6b6c6bacb777a0bfbf46a0324c0ae5de7c2bdb6aad6ce51c0f5b4a5ab7c139d6bcdacc8ea46e37e040b785dbfc3145e408593c6f143dc1b4fde763e32e6d60c32d1a5c6d0bdf2d7d97f2bdeeba4a439abe7c75daced72a7678af1412f6c2917e39d6419c103f3a32e964369136a1183feb8d484712bcde8b14e2e8a7374dfb0dd7ee07dd15727b340005ed98bf5850b9de92b1912639e15f91d16968cd8bc336afc132ec6c93deba843e636de52f32be6e3c1e0ea50fdf03206c8dfa74f4c600e7d4d133c2ccc61ac50ae2f54e4f1ad02dc7ec86d8732cf12f0ac2c2ee10de6829695e539a6f76f9d9a4cda9d2ed1377c7a203baff1b",created_at:"2026-05-03T08:06:17.512936+00:00",retired_at:null,receipt_context_since:"2026-10-19T09:50:04.571Z"}],pack_envelope_signers:[{kid:"pack-signer-2026-04-29",ed25519_pubkey_hex:"853a62cb452a35fd6499d8fedb97448e0e24ef0d071343b2c9652aa2831bbdf6",status:"active",created_at:"2026-04-29T18:20:16.11538+00:00"}]};var wn=[...yn.chain_keys.filter(n=>!n.retired_at).map(n=>n.ed25519_pubkey_hex.toLowerCase()),...yn.pack_envelope_signers.map(n=>n.ed25519_pubkey_hex.toLowerCase())];function Fr(n){return Ge(je(_e(n))).slice(0,16)}var Lr="connect-command",ze=/^[0-9a-f]{16}$/,Fs=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Bt=class extends M{constructor(t,r,s,o){super(o,428,"approval_required");this.approveUrl=t;this.approvalId=r;this.orgApprovalId=s;this.name="FabricApprovalRequired"}};function xn(){return Ge(kr())}var Ke=class{constructor(e){this.http=e}newSecret(){return xn()}async open(e={}){let t=(e.secret??xn()).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("nd.fabric: secret must be 64 hex characters (nd.fabric.newSecret())");let r=Ge(gn(_e(t))),s=await this.http.raw("POST",`/api/v1/relay/enroll${e.replace?"?replace=true":""}`,{ecdh_pubkey_hex:r});if(!s.ok)throw Q("enroll",s);let o=String(s.data.ecdh_kid??"");if(!ze.test(o))throw new M("enroll answered without an address",s.status);if(o!==Fr(r))throw new M("enroll answered an address that is not this key's",s.status,"address_mismatch");return new Tt(this.http,t,o,(e.trustedReceiptKeys??wn).map(i=>i.toLowerCase()))}},Tt=class{constructor(e,t,r,s=wn){this.http=e;this.secret=t;this.address=r;this.trustedReceiptKeys=s}async invite(e={}){let t=await this.http.raw("POST","/api/v1/fabric-grants",{action:"invite",my_kid:this.address,template:"ping",...e.note?{note:e.note}:{},...e.days?{grant_days:e.days}:{},...Pr(e)});if(!t.ok)throw Q("invite",t);return{url:String(t.data.invite_url??""),expiresAt:typeof t.data.expires_at=="string"?t.data.expires_at:null,grantDays:typeof t.data.grant_days=="number"?t.data.grant_days:null}}async accept(e,t={}){let r=e.match(/invite=([^&\s]+)/),s=decodeURIComponent(r?r[1]:e.trim());if(!s.includes("."))throw new Error("nd.fabric.accept: give the invitation link or its token");let o=await this.http.raw("POST","/api/v1/fabric-grants",{action:"accept",token:s,subject_kid:this.address,mutual:t.oneWay!==!0,...t.termsAccepted?{terms_accepted:!0}:{},...Pr(t)});if(!o.ok)throw Q("accept",o);let i=o.data.partner??{};if(!i.sender_kid||!ze.test(i.sender_kid))throw new M("connected, but the invitation named no address of theirs to send to (they invited without one)",o.status,"no_partner_address");return{kid:i.sender_kid,name:i.name??null}}async partners(){let e=await this.http.raw("GET","/api/v1/fabric-grants");if(!e.ok)throw Q("partners",e);return Ms(e.data)}async send(e,t,r={},s={}){if(!Fs.test(t))throw new Error(`nd.fabric.send: '${t}' is not a command name (e.g. order.create)`);let o=await this.addressOf(e),i=Hr(t,r,s.replyTo??null),a=bn(i);if(!a.ok)throw new Error(`nd.fabric.send: not a command (${a.reason})`);let u=mn(i),c=await this.http.raw("GET",`/api/v1/relay/resolve?handle=${encodeURIComponent(o)}`);if(!c.ok)throw Q("resolve",c);let d=String(c.data.recipient_pubkey??"");if(!/^[0-9a-f]{64}$/.test(d))throw new M(`${o} has no public key to seal to`,c.status,"no_public_key");if(Fr(d)!==o)throw new M(`the key the directory gave for ${o} is not that address's key; nothing was sent`,c.status,"key_mismatch");let l=await Tr(d,new TextEncoder().encode(u)),h=await this.http.raw("POST","/api/v1/relay/send",{recipient_kid:o,...l,route_taken:"capsule",content_type_hint:Ir,purpose:Lr,ttl_hours:Math.min(Math.max(s.ttlHours??24,1),720),max_fetches:Math.min(Math.max(s.opens??1,1),20),released_sha256:Ur(u)});if(!h.ok)throw Q("send",h);return{id:String(h.data.id??""),commandId:i.id,to:o}}reply(e,t,r={}){if(!e.commandId)throw new Error("nd.fabric.reply: this message was not an opened command");return this.send(e.from,t,r,{replyTo:e.commandId})}async inbox(e={}){let t=await this.http.raw("GET","/api/v1/relay/inbox");if(!t.ok)throw Q("inbox",t);let r=(t.data.items??[]).filter(i=>i.purpose===Lr),s=e.accept?new Set(e.accept):null,o=[];for(let i of r){let a={relayId:i.id,from:i.sender_kid,fromOrg:i.sender?.org??null},u=await this.http.raw("GET",`/api/v1/relay/fetch/${encodeURIComponent(i.id)}`);if(!u.ok){o.push({...a,status:"unopened",reason:String(u.data.refused??u.data.error??u.status),verified:{committed:null,receiptSignature:null}});continue}let c=Ns(u.data.receipt,this.trustedReceiptKeys),d=null;try{let p=await Or(this.secret,u.data),w=bn(JSON.parse(new TextDecoder().decode(p)));d=w.ok?w.envelope:null}catch{d=null}if(!d){o.push({...a,status:"refused",reason:"not_a_command",verified:{committed:null,receiptSignature:c}});continue}let h={committed:typeof u.data.released_sha256=="string"?Ur(mn(d))===u.data.released_sha256:null,receiptSignature:c};if(s&&!s.has(d.cmd)){o.push({...a,status:"refused",reason:`not_accepted:${d.cmd}`,cmd:d.cmd,commandId:d.id,verified:h});continue}o.push({...a,status:"accepted",cmd:d.cmd,fields:d.fields,replyTo:d.reply_to,commandId:d.id,issuedAt:d.issued_at,verified:h})}return o}async disconnect(e){let t=await this.addressOf(e),r=await this.http.raw("GET","/api/v1/fabric-grants");if(!r.ok)throw Q("partners",r);let s=(r.data.grants??[]).filter(a=>!a.revoked_at&&a.subject_kid===t),o=(r.data.inbound??[]).filter(a=>a.subject_kid===this.address&&(a.allowed_sender_kids??[]).includes(t)),i=0;for(let a of s){let u=await this.http.raw("PATCH","/api/v1/fabric-grants",{grant_id:a.id,reason:"disconnected from the SDK"});if(!u.ok)throw Q("disconnect",u);i++}for(let a of o){let u=await this.http.raw("POST","/api/v1/fabric-grants",{action:"leave",grant_id:a.id});if(!u.ok)throw Q("disconnect",u);i++}return{ended:i}}async addressOf(e){if(typeof e!="string")return e.kid;let t=e.trim().toLowerCase();if(ze.test(t))return t;let r=(await this.partners()).filter(s=>(s.name??"").toLowerCase()===t);if(r.length===1)return r[0].kid;throw new Error(r.length?`nd.fabric: '${e}' names ${r.length} connections; use the address`:`nd.fabric: no connection named '${e}'`)}};function Ms(n){let e=new Map;for(let t of n.grants??[])!t.revoked_at&&ze.test(t.subject_kid)&&e.set(t.subject_kid,{kid:t.subject_kid,name:t.partner_name??null});for(let t of n.inbound??[])for(let r of t.allowed_sender_kids??[]){if(!ze.test(r))continue;let s=e.get(r);e.set(r,{kid:r,name:s?.name??t.partner_name??null})}return[...e.values()]}function Ur(n){return Ge(je(new TextEncoder().encode(n)))}function _n(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return"["+n.map(_n).join(",")+"]";let e=n;return"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+_n(e[t])).join(",")+"}"}function Ns(n,e=wn){let t=n;if(!t?.payload||!t.signature_hex||!t.signing_pubkey_hex)return null;if(!e.includes(t.signing_pubkey_hex.toLowerCase()))return!1;try{return _r.verify(_e(t.signature_hex),new TextEncoder().encode(_n(t.payload)),_e(t.signing_pubkey_hex))}catch{return!1}}function Pr(n){return n.orgApprovalId?{org_approval_id:n.orgApprovalId}:n.approvalId?{approval_id:n.approvalId}:{}}function Q(n,e){let t=e.data;if(e.status===428){let s=typeof t.approval=="object"&&t.approval!==null?t.approval:{},o=typeof t.lock=="object"&&t.lock!==null?t.lock:{};return new Bt((s.approve_url??(typeof t.approve_url=="string"?t.approve_url:null))||null,s.approval_id??null,o.lock_id??null,`${n}: waiting for a person's approval${t.why?` (${String(t.why)})`:""}. Approve it in the browser, then call again with the approval id.`)}let r=String(t.refused??t.error??`HTTP ${e.status}`);return new M(`${n} refused: ${r}${t.reason?` (${String(t.reason)})`:t.why?` (${String(t.why)})`:""}`,e.status,String(t.refused??t.error??""))}var Ot=class{http;_encrypt;capsules;tenants;scan;fabric;engines;_compute;constructor(e){this.http=new Je(e),this._compute=new Le(this.http),this._encrypt=new Re(this.http),this.capsules=new Oe(this.http),this.tenants=new Ie(this.http),this.scan=new De(this.http),this.fabric=new Ke(this.http),this.engines=new He(this.http)}compute(e){return this._compute.run(e)}verify(e){return this._compute.verify(e)}authorize(e){return this.http.post("/api/v1/authorize",e)}get channel(){return this.engines.channel}get webhook(){return this.engines.webhook}get deliver(){return this.engines.deliver}get evidence(){return this.engines.evidence}get vault(){return this.engines.vault}get governance(){return this.engines.governance}agent(e){return new Be(this.http.baseURL,e)}encrypt(e){return this._encrypt.encrypt(e)}decrypt(e){return this._encrypt.decrypt(e)}batchEncrypt(e,t){return this._encrypt.batchEncrypt(e,t)}batchDecrypt(e,t){return this._encrypt.batchDecrypt(e,t)}batchNative(e,t){return this._encrypt.batchNative(e,t)}encryptObject(e,t,r){return this._encrypt.encryptObject(e,t,r)}decryptObject(e,t,r){return this._encrypt.decryptObject(e,t,r)}async ping(){let e=Date.now();return await this.http.get("/api/health"),{success:!0,latencyMs:Date.now()-e}}};function js(n,e,t){let r=new Ot({apiKey:e.apiKey,baseUrl:e.baseUrl}),s=e.encryptFields||[],o=e.decryptFields||[],i=e.skipPaths||[];o.length>0&&n.addHook("preHandler",async a=>{if(i.some(c=>a.url.startsWith(c))||!a.body||typeof a.body!="object"||a.method==="GET")return;if(!e.decryptHeader||a.headers[e.decryptHeader.toLowerCase()])try{a.body=await r.decryptObject(a.body,o,a.headers["x-requester"]||"fastify-plugin")}catch{}}),s.length>0&&n.addHook("onSend",async(a,u,c)=>{if(typeof c!="string")return c;try{let d=JSON.parse(c);if(typeof d=="object"&&d!==null){let l=await r.encryptObject(d,s,e.context);return JSON.stringify(l)}}catch{}return c}),t()}0&&(module.exports={nodataFastify});
1
+ "use strict";var Dt=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var $r=Object.prototype.hasOwnProperty;var Vr=(n,e)=>{for(var t in e)Dt(n,t,{get:e[t],enumerable:!0})},Gr=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of qr(e))!$r.call(n,s)&&s!==t&&Dt(n,s,{get:()=>e[s],enumerable:!(r=jr(e,s))||r.enumerable});return n};var zr=n=>Gr(Dt({},"__esModule",{value:!0}),n);var qs={};Vr(qs,{nodataFastify:()=>js});module.exports=zr(qs);var M=class extends Error{constructor(t,r,s,o){super(t);this.status=r;this.code=s;this.retryAfter=o;this.name="NoDataError"}};var Kr="https://www.nodatacapsule.com",Zr=3e4,Xr=2,Je=class{apiKey;baseUrl;timeout;retries;customHeaders;onRequest;onResponse;onError;constructor(e){if(!e.apiKey)throw new Error("NoData SDK: apiKey is required. Get one at https://www.nodatacapsule.com/developers");this.apiKey=e.apiKey,this.baseUrl=(e.baseUrl||Kr).replace(/\/+$/,""),this.timeout=e.timeout||Zr,this.retries=e.retries??Xr,this.customHeaders=e.headers||{},this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.onError=e.onError}async request(e,t,r,s){let o=`${this.baseUrl}${t}`;if(s){let d=new URLSearchParams(Object.fromEntries(Object.entries(s).filter(([,l])=>l!=null))).toString();d&&(o+=`?${d}`)}let i={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...this.customHeaders},signal:AbortSignal.timeout(this.timeout)};r&&e!=="GET"&&(i.body=JSON.stringify(r)),this.onRequest?.(o,i);let a=null,u=1+this.retries;for(let c=1;c<=u;c++){let d=Date.now();try{let l=await fetch(o,i),h=Date.now()-d;if(this.onResponse?.(o,l.status,h),l.status===429&&c<u){let w=parseInt(l.headers.get("Retry-After")||"5",10);await Lt(w*1e3);continue}if(l.status>=500&&c<u){await Lt(1e3*c);continue}let p=await l.json().catch(()=>({}));if(!l.ok)throw new M(p.error||`HTTP ${l.status}`,l.status,p.code,l.status===429?parseInt(l.headers.get("Retry-After")||"60",10):void 0);return p}catch(l){if(a=l instanceof Error?l:new Error(String(l)),this.onError?.(o,a),l instanceof M)throw l;if(c<u){await Lt(1e3*c);continue}}}throw a||new Error("Request failed")}get baseURL(){return this.baseUrl}get(e,t){return this.request("GET",e,void 0,t)}post(e,t){return this.request("POST",e,t)}del(e,t){return this.request("DELETE",e,t)}async raw(e,t,r){let s=`${this.baseUrl}${t}`,o={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...r!==void 0?{"Content-Type":"application/json"}:{},...this.customHeaders},signal:AbortSignal.timeout(this.timeout),...r!==void 0?{body:JSON.stringify(r)}:{}};this.onRequest?.(s,o);let i=Date.now(),a=await fetch(s,o);this.onResponse?.(s,a.status,Date.now()-i);let u=await a.json().catch(()=>({})),c=u&&typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:u;return{ok:a.ok,status:a.status,data:{...c,...u.error?{error:u.error}:{}}}}};function Lt(n){return new Promise(e=>setTimeout(e,n))}var Re=class{constructor(e){this.http=e}async encrypt(e){return this.http.post("/api/v1/encrypt",{field:e.field,value:e.value,context:e.context})}async decrypt(e){return this.http.post("/api/v1/decrypt",{ciphertext:e.ciphertext,field:e.field,requester:e.requester,purpose:e.purpose})}async batchEncrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.encrypt({...o,context:o.context||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,ciphertext:"",field:e[i].field,audit_id:"",algorithm:"",error:o.reason?.message||"Encryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchDecrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.decrypt({...o,requester:o.requester||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,value:"",field:e[i].field,audit_id:"",error:o.reason?.message||"Decryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchNative(e,t){return this.http.post("/api/v1/batch",{items:e,context:t})}async encryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.encrypt({field:o,value:s,context:r})).ciphertext)}async decryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.decrypt({ciphertext:s,field:o,requester:r})).value)}async processObject(e,t,r){if(e==null)return e;if(Array.isArray(e))return Promise.all(e.map(s=>this.processObject(s,t,r)));if(typeof e=="object"){let s={};for(let[o,i]of Object.entries(e))t.includes(o)&&typeof i=="string"&&i.length>0?s[o]=await r(i,o):typeof i=="object"?s[o]=await this.processObject(i,t,r):s[o]=i;return s}return e}};var Ce=class{constructor(e){this.http=e}async registerTable(e){return this.http.post("/api/v1/governance/tables",{table_name:e.table,encrypted_columns:e.encryptedColumns??[],plaintext_columns:e.plaintextColumns??[],classification_column:e.classificationColumn,hkdf_prefix:e.hkdfPrefix,ui_label:e.uiLabel})}async listTables(){return this.http.get("/api/v1/governance/tables")}async grant(e){return this.http.post("/api/v1/governance/grant",{agent:e.agent,table:e.table,columns:e.columns,where:e.where,classifications:e.classifications,ttl_seconds:e.ttlSeconds})}async revoke(e){return this.http.post("/api/v1/governance/revoke",{handle:e.agent,jti:e.jti,reason:e.reason})}},Be=class{constructor(e,t){this.baseURL=e;this.grantToken=t}async read(e){let t=e.handle??Yr(this.grantToken);if(!t)throw new M("AgentReader.read: could not derive agent handle from token; pass { handle }",400);let r=`${this.baseURL}/api/agents/${encodeURIComponent(t)}/read`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.grantToken}`,"Content-Type":"application/json"},body:JSON.stringify({table:e.table,columns:e.columns,where:e.where,limit:e.limit})}),o=await s.json().catch(()=>({}));if(!s.ok)throw new M(o.error||`HTTP ${s.status}`,s.status,o.reason);return o}};function Yr(n){try{let t=(n.startsWith("ndca-")?n.slice(5):n).split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r)).handle??null}catch{return null}}var Qe=class{constructor(e,t){this.http=e;this.ref=t}add(e){let t=e.sections?.length?e.sections:[{label:e.title||"Document",classification:e.classification||"confidential",text:e.content??""}];return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`,{title:e.title,sections:t,recipients:e.recipients,zero_knowledge:e.zero_knowledge,inherit_access:e.inherit_access})}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`)}},et=class{constructor(e,t){this.http=e;this.ref=t}add(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`)}},tt=class{constructor(e,t){this.http=e;this.ref=t}get(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.limit&&(t.limit=String(e.limit)),this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/audit`,Object.keys(t).length?t:void 0)}},nt=class{constructor(e,t){this.http=e;this.ref=t}grant(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,{action:"revoke",agent_id:e})}read(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-read`,e)}},Te=class{constructor(e,t){this.http=e;this.summary=t;this.documents=new Qe(e,t.slug),this.members=new et(e,t.slug),this.audit=new tt(e,t.slug),this.ai=new nt(e,t.slug)}documents;members;audit;ai;get id(){return this.summary.capsule_id}get slug(){return this.summary.slug}get status(){return this.summary.status}embed(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/embed-token`,e)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/revoke`,{reason:e?.reason})}},Oe=class{constructor(e){this.http=e}async create(e){let t=await this.http.post("/api/v1/capsules",e);return new Te(this.http,t)}async get(e){let t=await this.http.get(`/api/v1/capsules/${encodeURIComponent(e)}`);return new Te(this.http,t)}list(e){return this.http.get("/api/v1/capsules",e?.limit?{limit:String(e.limit)}:void 0)}overview(){return this.http.get("/api/v1/overview")}};var Ie=class{constructor(e){this.http=e}create(e){return this.http.post("/api/v1/tenants",e)}get(e){return this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`)}};var De=class{constructor(e){this.http=e}async orgId(){let e=await this.http.get("/api/v1/partner/me");if(!e?.org_id)throw new Error("nd.scan: could not resolve the org from this API key.");return e.org_id}async enable(e){let t=await this.orgId(),r=await this.http.post(`/api/v1/tenants/${encodeURIComponent(t)}/capsule/install-token`,{}),s=r.install_token??"",o=(e.api_base??this.http.baseURL).replace(/\/+$/,""),i=e.source==="folder"?`--source folder --path ${e.path??"./"}`:e.source==="drive"?`--source drive --folder ${e.folder_id??"<folder-id>"}`:`--source ${e.source}`,a=e.per_customer?` --per-customer ${e.per_customer}`:"";return{ok:!0,scan_id:s.slice(0,12),install_token:s,install_command:`npx @nodatachat/capsule-agent --token ${s} --vault-api --api ${o} ${i}${a}`,expires_at:r.expires_at??null}}async status(){let e=await this.orgId(),t=await this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`);return{deployments:t.capsule?.deployments??[],last_scan_at:t.capsule?.last_scan_at??null,open_findings_count:t.capsule?.open_findings_count??0}}findings(e){let t={};return e?.limit&&(t.limit=String(e.limit)),e?.all&&(t.all="true"),this.http.get("/api/v1/scan/findings",Object.keys(t).length?t:void 0)}approve(e){return this.http.post("/api/v1/scan/approve",{finding_ids:e})}execute(e){return this.http.post("/api/v1/scan/execute",{finding_ids:e})}};var rt=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/secure-channel/init",{label:e.label,ttl:e.ttl||"24h",max_transfers:e.maxTransfers||10,require_verification:e.requireVerification??!1})}async send(e){let t=typeof e.data=="string"?e.data:JSON.stringify(e.data);return this.http.post("/api/secure-channel/upload",{channel_token:e.token,content:t,content_type:e.contentType||"application/json",burn_after_read:e.burnAfterRead??!0})}async receive(e){return this.http.post("/api/secure-channel/download",{channel_token:e.token,verification_code:e.verificationCode})}async verify(e,t){return this.http.post("/api/secure-channel/verify-code",{channel_token:e,code:t})}async proof(e){return this.http.post("/api/secure-channel/delivery-proof",{channel_token:e})}};var st=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/webhook/channel/create",{label:e.label,ttl:e.ttl||"30d",max_events:e.maxEvents||1e4,burn_after_read:e.burnAfterRead??!1})}async events(e,t){return this.http.post("/api/webhook/channel/events",{channel_token:e,limit:t?.limit||50,since:t?.since})}async list(){return this.http.get("/api/webhook/dashboard")}};var ot=class{constructor(e){this.http=e}async send(e){return this.http.post("/api/v1/deliver",{content:e.content,to:e.to,ttl:e.ttl||"24h",burn:e.burn??!0,maxViews:e.maxViews||1})}async burn(e,t){return this.http.post("/api/burn/create",{content:e,ttl_hours:t?.ttlHours||24,burn_after_read:t?.burnAfterRead??!0,available_at:t?.availableAt})}async read(e){return this.http.post("/api/burn/read",{drop_id:e})}};var it=class{constructor(e){this.http=e}async query(e={}){return this.http.get("/api/v1/evidence",{from:e.from||"",to:e.to||"",action:e.action||"",field:e.field||"",limit:String(e.limit||100)})}async certificate(e){return this.http.post("/api/proof-certificate",{audit_id:e})}async verify(e){return this.http.post("/api/receipt/verify",{proof_hash:e})}};var at=class{constructor(e){this.http=e}async create(e){return this.http.post("/api/vault/create",e)}async read(e){return this.http.post("/api/vault/read",{vault_id:e})}async delete(e){return this.http.post("/api/vault/delete",{vault_id:e})}async status(){return this.http.get("/api/vault/status")}};var Le=class{governance;blindRelay;channel;deliver;evidence;vault;webhook;constructor(e){this.governance=new Ce(e),this.blindRelay=new Re(e),this.channel=new rt(e),this.deliver=new ot(e),this.evidence=new it(e),this.vault=new at(e),this.webhook=new st(e)}};var He=class{constructor(e){this.http=e}async run(e){let t=await this.http.post("/api/v1/documents/compute",{question:e.question,clearance:e.clearance??"internal",...e.sections?{sections:e.sections}:{},...e.text?{text:e.text}:{}}),r=(t.sections??[]).map(s=>({title:s.title??"",classification:s.classification??"internal",sent:!!s.sent}));return{decision:t.decision??(r.some(s=>s.sent)?"allow":"deny"),answer:t.answer??null,model:t.model??null,sections:r,proof:{id:t.proof?.receipt_id??t.proof?.id??null,hash:t.proof?.hash??null,persisted:!!t.proof?.persisted}}}async verify(e){let t=await this.http.post("/api/access/verify",{proof_id:e});return{authentic:!!t.authentic,unaltered:!!t.unaltered,signer:t.signer,surface:t.surface,decision:t.decision,issuedAt:t.issued_at}}};function Ht(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ie(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof n}`)}if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${n}`)}}function $(n,e,t=""){let r=Ht(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",u=r?`length=${s}`:`type=${typeof n}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):new TypeError(c)}return n}function Ue(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ie(n.outputLen),ie(n.blockLen),n.outputLen<1)throw new Error('"outputLen" must be >= 1');if(n.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ve(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function ct(n,e){$(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function X(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function ut(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Y(n,e){return n<<32-e|n>>>e}var Bn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Wr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function dt(n){if($(n),Bn)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Wr[n[t]];return e}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cn(n){if(n>=ee._0&&n<=ee._9)return n-ee._0;if(n>=ee.A&&n<=ee.F)return n-(ee.A-10);if(n>=ee.a&&n<=ee.f)return n-(ee.a-10)}function Pe(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Bn)try{return Uint8Array.fromHex(n)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=Cn(n.charCodeAt(o)),a=Cn(n.charCodeAt(o+1));if(i===void 0||a===void 0){let u=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+a}return r}function Ut(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];$(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function Pt(n,e={}){let t=(s,o)=>n(o).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Tn(n=32){ie(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Ft=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function On(n,e,t){return n&e^~n&t}function In(n,e,t){return n&e^n&t^e&t}var Fe=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){ve(this),$(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let u=ut(e);for(;s<=o-i;i+=s)this.process(u,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let l=i;l<s;l++)t[l]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let a=ut(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var N=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var lt=BigInt(4294967295),Dn=BigInt(32);function Jr(n,e=!1){return e?{h:Number(n&lt),l:Number(n>>Dn&lt)}:{h:Number(n>>Dn&lt)|0,l:Number(n&lt)|0}}function Ln(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Jr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Mt=(n,e,t)=>n>>>t,Nt=(n,e,t)=>n<<32-t|e>>>t,ge=(n,e,t)=>n>>>t|e<<32-t,be=(n,e,t)=>n<<32-t|e>>>t,Me=(n,e,t)=>n<<64-t|e>>>t-32,Ne=(n,e,t)=>n>>>t-32|e<<64-t;function W(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Hn=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),Un=(n,e,t,r)=>e+t+r+(n/2**32|0)|0,Pn=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Fn=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,Mn=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),Nn=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;var es=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ae=new Uint32Array(64),jt=class extends Fe{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:u}=this;return[e,t,r,s,o,i,a,u]}set(e,t,r,s,o,i,a,u){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let l=0;l<16;l++,t+=4)ae[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let h=ae[l-15],p=ae[l-2],w=Y(h,7)^Y(h,18)^h>>>3,R=Y(p,17)^Y(p,19)^p>>>10;ae[l]=R+ae[l-7]+w+ae[l-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:u,G:c,H:d}=this;for(let l=0;l<64;l++){let h=Y(a,6)^Y(a,11)^Y(a,25),p=d+h+On(a,u,c)+es[l]+ae[l]|0,R=(Y(r,2)^Y(r,13)^Y(r,22))+In(r,s,o)|0;d=c,c=u,u=a,a=i+p|0,i=o,o=s,s=r,r=p+R|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(r,s,o,i,a,u,c,d)}roundClean(){X(ae)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),X(this.buffer)}},qt=class extends jt{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var jn=Ln(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),ts=jn[0],ns=jn[1],ce=new Uint32Array(80),ue=new Uint32Array(80),$t=class extends Fe{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:u,Eh:c,El:d,Fh:l,Fl:h,Gh:p,Gl:w,Hh:R,Hl:f}=this;return[e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f]}set(e,t,r,s,o,i,a,u,c,d,l,h,p,w,R,f){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=h|0,this.Gh=p|0,this.Gl=w|0,this.Hh=R|0,this.Hl=f|0}process(e,t){for(let x=0;x<16;x++,t+=4)ce[x]=e.getUint32(t),ue[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let k=ce[x-15]|0,A=ue[x-15]|0,B=ge(k,A,1)^ge(k,A,8)^Mt(k,A,7),E=be(k,A,1)^be(k,A,8)^Nt(k,A,7),C=ce[x-2]|0,S=ue[x-2]|0,D=ge(C,S,19)^Me(C,S,61)^Mt(C,S,6),L=be(C,S,19)^Ne(C,S,61)^Nt(C,S,6),b=Pn(E,L,ue[x-7],ue[x-16]),_=Fn(b,B,D,ce[x-7],ce[x-16]);ce[x]=_|0,ue[x]=b|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:u,Dh:c,Dl:d,Eh:l,El:h,Fh:p,Fl:w,Gh:R,Gl:f,Hh:g,Hl:y}=this;for(let x=0;x<80;x++){let k=ge(l,h,14)^ge(l,h,18)^Me(l,h,41),A=be(l,h,14)^be(l,h,18)^Ne(l,h,41),B=l&p^~l&R,E=h&w^~h&f,C=Mn(y,A,E,ns[x],ue[x]),S=Nn(C,g,k,B,ts[x],ce[x]),D=C|0,L=ge(r,s,28)^Me(r,s,34)^Me(r,s,39),b=be(r,s,28)^Ne(r,s,34)^Ne(r,s,39),_=r&o^r&a^o&a,m=s&i^s&u^i&u;g=R|0,y=f|0,R=p|0,f=w|0,p=l|0,w=h|0,{h:l,l:h}=W(c|0,d|0,S|0,D|0),c=a|0,d=u|0,a=o|0,u=i|0,o=r|0,i=s|0;let v=Hn(D,b,m);r=Un(v,S,L,_),s=v|0}({h:r,l:s}=W(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=W(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:u}=W(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l:d}=W(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:h}=W(this.Eh|0,this.El|0,l|0,h|0),{h:p,l:w}=W(this.Fh|0,this.Fl|0,p|0,w|0),{h:R,l:f}=W(this.Gh|0,this.Gl|0,R|0,f|0),{h:g,l:y}=W(this.Hh|0,this.Hl|0,g|0,y|0),this.set(r,s,o,i,a,u,c,d,l,h,p,w,R,f,g,y)}roundClean(){X(ce,ue)}destroy(){this.destroyed=!0,X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Vt=class extends $t{Ah=N[0]|0;Al=N[1]|0;Bh=N[2]|0;Bl=N[3]|0;Ch=N[4]|0;Cl=N[5]|0;Dh=N[6]|0;Dl=N[7]|0;Eh=N[8]|0;El=N[9]|0;Fh=N[10]|0;Fl=N[11]|0;Gh=N[12]|0;Gl=N[13]|0;Hh=N[14]|0;Hl=N[15]|0;constructor(){super(64)}};var je=Pt(()=>new qt,Ft(1));var ft=Pt(()=>new Vt,Ft(3));var O=(n,e,t)=>$(n,e,t),zt=ie,Kt=dt,J=(...n)=>Ut(...n),qn=n=>Pe(n),gt=Ht,bt=n=>Tn(n),ht=BigInt(0),Gt=BigInt(1);function Ee(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof n)}return n}function rs(n){if(typeof n=="bigint"){if(!pt(n))throw new RangeError("positive bigint expected, got "+n)}else zt(n);return n}function ne(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function $n(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?ht:BigInt("0x"+n)}function Zt(n){return $n(dt(n))}function K(n){return $n(dt(de($(n)).reverse()))}function Xt(n,e){if(ie(e),e===0)throw new RangeError("zero length");n=rs(n);let t=n.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pe(t.padStart(e*2,"0"))}function mt(n,e){return Xt(n,e).reverse()}function Vn(n,e){if(n=O(n),e=O(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function de(n){return Uint8Array.from(O(n))}function yt(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var pt=n=>typeof n=="bigint"&&ht<=n;function ss(n,e,t){return pt(n)&&pt(e)&&pt(t)&&e<=n&&n<t}function ke(n,e,t,r){if(!ss(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Yt(n){if(n<ht)throw new Error("expected non-negative bigint, got "+n);let e;for(e=0;n>ht;n>>=Gt,e+=1);return e}var Gn=n=>(Gt<<BigInt(n))-Gt;function re(n,e={},t={}){if(Object.prototype.toString.call(n)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(n,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=n[o];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${c}`)}let s=(o,i)=>Object.entries(o).forEach(([a,u])=>r(a,u,i));s(e,!1),s(t,!0)}var Wt=()=>{throw new Error("not implemented")};var j=BigInt(0),P=BigInt(1),me=BigInt(2),Xn=BigInt(3),Yn=BigInt(4),Wn=BigInt(5),os=BigInt(7),Jn=BigInt(8),is=BigInt(9),Qn=BigInt(16);function I(n,e){if(e<=j)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=j?t:e+t}function Z(n,e,t){if(e<j)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >j;)r*=r,r%=t;return r}function zn(n,e){if(n===j)throw new Error("invert: expected non-zero number");if(e<=j)throw new Error("invert: expected positive modulus, got "+e);let t=I(n,e),r=e,s=j,o=P,i=P,a=j;for(;t!==j;){let c=r/t,d=r-t*c,l=s-i*c,h=o-a*c;r=t,t=d,s=i,o=a,i=l,a=h}if(r!==P)throw new Error("invert: does not exist");return I(s,e)}function Jt(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function er(n,e){let t=n,r=(t.ORDER+P)/Yn,s=t.pow(e,r);return Jt(t,s,e),s}function as(n,e){let t=n,r=(t.ORDER-Wn)/Jn,s=t.mul(e,me),o=t.pow(s,r),i=t.mul(e,o),a=t.mul(t.mul(i,me),o),u=t.mul(i,t.sub(a,t.ONE));return Jt(t,u,e),u}function cs(n){let e=wt(n),t=tr(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+os)/Qn;return((a,u)=>{let c=a,d=c.pow(u,i),l=c.mul(d,r),h=c.mul(d,s),p=c.mul(d,o),w=c.eql(c.sqr(l),u),R=c.eql(c.sqr(h),u);d=c.cmov(d,l,w),l=c.cmov(p,h,R);let f=c.eql(c.sqr(l),u),g=c.cmov(d,l,f);return Jt(c,g,u),g})}function tr(n){if(n<Xn)throw new Error("sqrt is not defined for small field");let e=n-P,t=0;for(;e%me===j;)e/=me,t++;let r=me,s=wt(n);for(;Kn(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return er;let o=s.pow(r,e),i=(e+P)/me;return function(u,c){let d=u;if(d.is0(c))return c;if(Kn(d,c)!==1)throw new Error("Cannot find square root");let l=t,h=d.mul(d.ONE,o),p=d.pow(c,e),w=d.pow(c,i);for(;!d.eql(p,d.ONE);){if(d.is0(p))return d.ZERO;let R=1,f=d.sqr(p);for(;!d.eql(f,d.ONE);)if(R++,f=d.sqr(f),R===l)throw new Error("Cannot find square root");let g=P<<BigInt(l-R-1),y=d.pow(h,g);l=R,h=d.sqr(y),p=d.mul(p,h),w=d.mul(w,y)}return w}}function us(n){return n%Yn===Xn?er:n%Jn===Wn?as:n%Qn===is?cs(n):tr(n)}var se=(n,e)=>(I(n,e)&P)===P,ds=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nr(n){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ds.reduce((r,s)=>(r[s]="function",r),e);if(re(n,t),ne(n.BYTES,"BYTES"),ne(n.BITS,"BITS"),n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ls(n,e,t){let r=n;if(t<j)throw new Error("invalid exponent, negatives unsupported");if(t===j)return r.ONE;if(t===P)return e;let s=r.ONE,o=e;for(;t>j;)t&P&&(s=r.mul(s,o)),o=r.sqr(o),t>>=P;return s}function _t(n,e,t=!1){let r=n,s=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,u,c)=>r.is0(u)?a:(s[c]=a,r.mul(a,u)),r.ONE),i=r.inv(o);return e.reduceRight((a,u,c)=>r.is0(u)?a:(s[c]=r.mul(a,s[c]),r.mul(a,u)),i),s}function Kn(n,e){let t=n,r=(t.ORDER-P)/me,s=t.pow(e,r),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function fs(n,e){if(e!==void 0&&zt(e),n<=j)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Yt(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}var Zn=new WeakMap,xt=class{ORDER;BITS;BYTES;isLE;ZERO=j;ONE=P;_lengths;_mod;constructor(e,t={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=fs(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return I(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return j<=e&&e<this.ORDER}is0(e){return e===j}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&P)===P}neg(e){return I(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return I(e*e,this.ORDER)}add(e,t){return I(e+t,this.ORDER)}sub(e,t){return I(e-t,this.ORDER)}mul(e,t){return I(e*t,this.ORDER)}pow(e,t){return ls(this,e,t)}div(e,t){return I(e*zn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return zn(e,this.ORDER)}sqrt(e){let t=Zn.get(this);return t||Zn.set(this,t=us(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?mt(e,this.BYTES):Xt(e,this.BYTES)}fromBytes(e,t=!1){O(e);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let u=o?K(e):Zt(e);if(a&&(u=I(u,i)),!t&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return _t(this,e)}cmov(e,t,r){return Ee(r,"condition"),r?t:e}};Object.freeze(xt.prototype);function wt(n,e={}){return new xt(n,e)}var Rt=BigInt(0),nn=BigInt(1);function rr(n,e){let t=e.negate();return n?t:e}function Et(n,e){let t=_t(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function ar(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Qt(n,e){ar(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=Gn(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function sr(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),u=n>>i;a>r&&(a-=o,u+=nn);let c=e*r,d=c+Math.abs(a)-1,l=a===0,h=a<0,p=e%2!==0;return{nextN:u,offset:d,isZero:l,isNeg:h,isNegF:p,offsetF:c}}var en=new WeakMap,cr=new WeakMap;function tn(n){return cr.get(n)||1}function or(n){if(n!==Rt)throw new Error("invalid wNAF")}var vt=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Rt;)t&nn&&(r=r.add(s)),s=s.double(),t>>=nn;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Qt(t,this.bits),o=[],i=e,a=i;for(let u=0;u<r;u++){a=i,o.push(a);for(let c=1;c<s;c++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Qt(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:d,isNeg:l,isNegF:h,offsetF:p}=sr(r,a,i);r=u,d?o=o.add(rr(h,t[p])):s=s.add(rr(l,t[c]))}return or(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Qt(e,this.bits);for(let i=0;i<o.windows&&r!==Rt;i++){let{nextN:a,offset:u,isZero:c,isNeg:d}=sr(r,i,o);if(r=a,!c){let l=t[u];s=s.add(d?l.negate():l)}}return or(r),s}getPrecomputes(e,t,r){let s=en.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),en.set(t,s))),s}cached(e,t,r){let s=tn(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=tn(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){ar(t,this.bits),cr.set(e,t),en.delete(e)}hasCache(e){return tn(e)!==1}};function ir(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nr(e),e}else return wt(n,{isLE:t})}function ur(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let u of["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Rt))throw new Error(`CURVE.${u} must be positive bigint`)}let s=ir(e.p,t.Fp,r),o=ir(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let u of a)if(!s.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function kt(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var le=BigInt(0),F=BigInt(1),rn=BigInt(2),ps=BigInt(8);function hs(n,e,t,r){let s=n.sqr(t),o=n.sqr(r),i=n.add(n.mul(e.a,s),o),a=n.add(n.ONE,n.mul(e.d,n.mul(s,o)));return n.eql(i,a)}function dr(n,e={}){let t=e,r=ur("edwards",n,t,t.FpFnLE),{Fp:s,Fn:o}=r,i=r.CURVE,{h:a}=i;re(t,{},{uvRatio:"function"});let u=rn<<BigInt(o.BYTES*8)-F,c=R=>s.create(R),d=t.uvRatio===void 0?(R,f)=>{try{return{isValid:!0,value:s.sqrt(s.div(R,f))}}catch{return{isValid:!1,value:le}}}:t.uvRatio;if(!hs(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function l(R,f,g=!1){let y=g?F:le;return ke("coordinate "+R,f,y,u),f}function h(R){if(!(R instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,F,c(i.Gx*i.Gy));static ZERO=new p(le,F,F,le);static Fp=s;static Fn=o;X;Y;Z;T;constructor(f,g,y,x){this.X=l("x",f),this.Y=l("y",g),this.Z=l("z",y,!0),this.T=l("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(f){if(f instanceof p)throw new Error("extended point not allowed");let{x:g,y}=f||{};return l("x",g),l("y",y),new p(g,y,F,c(g*y))}static fromBytes(f,g=!1){let y=s.BYTES,{a:x,d:k}=i;f=de(O(f,y,"point")),Ee(g,"zip215");let A=de(f),B=f[y-1];A[y-1]=B&-129;let E=K(A),C=g?u:s.ORDER;ke("point.y",E,le,C);let S=c(E*E),D=c(S-F),L=c(k*S-x),{isValid:b,value:_}=d(D,L);if(!b)throw new Error("bad point: invalid y coordinate");let m=(_&F)===F,v=(B&128)!==0;if(!g&&_===le&&v)throw new Error("bad point: x=0 and x_0=1");return v!==m&&(_=c(-_)),p.fromAffine({x:_,y:E})}static fromHex(f,g=!1){return p.fromBytes(qn(f),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,g=!0){return w.createCache(this,f),g||this.multiply(rn),this}assertValidity(){let f=this,{a:g,d:y}=i;if(f.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:A,T:B}=f,E=c(x*x),C=c(k*k),S=c(A*A),D=c(S*S),L=c(E*g),b=c(S*c(L+C)),_=c(D+c(y*c(E*C)));if(b!==_)throw new Error("bad point: equation left != right (1)");let m=c(x*k),v=c(A*B);if(m!==v)throw new Error("bad point: equation left != right (2)")}equals(f){h(f);let{X:g,Y:y,Z:x}=this,{X:k,Y:A,Z:B}=f,E=c(g*B),C=c(k*x),S=c(y*B),D=c(A*x);return E===C&&S===D}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:f}=i,{X:g,Y:y,Z:x}=this,k=c(g*g),A=c(y*y),B=c(rn*c(x*x)),E=c(f*k),C=g+y,S=c(c(C*C)-k-A),D=E+A,L=D-B,b=E-A,_=c(S*L),m=c(D*b),v=c(S*b),T=c(L*D);return new p(_,m,T,v)}add(f){h(f);let{a:g,d:y}=i,{X:x,Y:k,Z:A,T:B}=this,{X:E,Y:C,Z:S,T:D}=f,L=c(x*E),b=c(k*C),_=c(B*y*D),m=c(A*S),v=c((x+k)*(E+C)-L-b),T=m-_,H=m+_,U=c(b-g*L),q=c(v*T),V=c(H*U),G=c(v*U),z=c(T*H);return new p(q,V,z,G)}subtract(f){return h(f),this.add(f.negate())}multiply(f){if(!o.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:y}=w.cached(this,f,x=>Et(p,x));return Et(p,[g,y])[0]}multiplyUnsafe(f){if(!o.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===le?p.ZERO:this.is0()||f===F?this:w.unsafe(this,f,g=>Et(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(f){let g=this,y=f,{X:x,Y:k,Z:A}=g,B=g.is0();y==null&&(y=B?ps:s.inv(A));let E=c(x*y),C=c(k*y),S=s.mul(A,y);if(B)return{x:le,y:F};if(S!==F)throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===F?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:g}=this.toAffine(),y=s.toBytes(g);return y[y.length-1]|=f&F?128:0,y}toHex(){return Kt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new vt(p,o.BITS);return o.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Wt()}static fromHex(e){Wt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Kt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function lr(n,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,s=t;re(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:u}=n,c=r.outputLen,d=2*a.BYTES;if(c!==void 0&&(ne(c,"hash.outputLen"),c!==d))throw new Error(`hash.outputLen must be ${d}, got ${c}`);let l=s.randomBytes===void 0?bt:s.randomBytes,h=s.adjustScalarBytes===void 0?b=>b:s.adjustScalarBytes,p=s.domain===void 0?(b,_,m)=>{if(Ee(m,"phflag"),_.length||m)throw new Error("Contexts/pre-hash are not supported");return b}:s.domain;function w(b){return u.create(K(b))}function R(b){let _=E.secretKey;O(b,E.secretKey,"secretKey");let m=O(r(b),2*_,"hashedSecretKey"),v=h(m.slice(0,_)),T=m.slice(_,2*_),H=w(v);return{head:v,prefix:T,scalar:H}}function f(b){let{head:_,prefix:m,scalar:v}=R(b),T=i.multiply(v),H=T.toBytes();return{head:_,prefix:m,scalar:v,point:T,pointBytes:H}}function g(b){return f(b).pointBytes}function y(b=Uint8Array.of(),..._){let m=J(..._);return w(r(p(m,O(b,void 0,"context"),!!o)))}function x(b,_,m={}){b=O(b,void 0,"message"),o&&(b=o(b));let{prefix:v,scalar:T,pointBytes:H}=f(_),U=y(m.context,v,b),q=i.multiply(U).toBytes(),V=y(m.context,q,H,b),G=u.create(U+V*T);if(!u.isValid(G))throw new Error("sign failed: invalid s");let z=J(q,u.toBytes(G));return O(z,E.signature,"result")}let k={zip215:s.zip215};function A(b,_,m,v=k){let{context:T}=v,H=v.zip215===void 0?!!k.zip215:v.zip215,U=E.signature;b=O(b,U,"signature"),_=O(_,void 0,"message"),m=O(m,E.publicKey,"publicKey"),H!==void 0&&Ee(H,"zip215"),o&&(_=o(_));let q=U/2,V=b.subarray(0,q),G=K(b.subarray(q,U)),z,Ze,we;try{z=n.fromBytes(m,H),Ze=n.fromBytes(V,H),we=i.multiplyUnsafe(G)}catch{return!1}if(!H&&z.isSmallOrder())return!1;let Xe=y(T,V,m,_);return Ze.add(z.multiplyUnsafe(Xe)).subtract(we).clearCofactor().is0()}let B=a.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function C(b){return b=b===void 0?l(E.seed):b,O(b,E.seed,"seed")}function S(b){return gt(b)&&b.length===E.secretKey}function D(b,_){try{return!!n.fromBytes(b,_===void 0?k.zip215:_)}catch{return!1}}let L={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:S,isValidPublicKey:D,toMontgomery(b){let{y:_}=n.fromBytes(b),m=E.publicKey,v=m===32;if(!v&&m!==57)throw new Error("only defined for 25519 and 448");let T=v?a.div(F+_,F-_):a.div(_-F,_+F);return a.toBytes(T)},toMontgomerySecret(b){let _=E.secretKey;O(b,_);let m=r(b.subarray(0,_));return h(m).subarray(0,_)}};return Object.freeze(E),Object.freeze(L),Object.freeze({keygen:kt(C,g),getPublicKey:g,sign:x,verify:A,utils:L,Point:n,lengths:E})}function qe(n,e){if(ne(n),ne(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(n<0||n>2**(8*e)-1)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function gs(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function bs(n){if(!gt(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof n=="string"?yt(n):n;if(e.length===0)throw new Error("DST must be non-empty");return e}function sn(n,e,t,r){O(n),ne(t),e=bs(e),e.length>255&&(e=r(J(yt("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=r,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=J(e,qe(e.length,1)),u=new Uint8Array(o),c=qe(t,2),d=new Array(i),l=r(J(u,n,c,qe(0,1),a));d[0]=r(J(l,qe(1,1),a));for(let p=1;p<i;p++){let w=[gs(l,d[p-1]),qe(p+1,1),a];d[p]=r(J(...w))}return J(...d).slice(0,t)}var fr="HashToScalar-";var $e=BigInt(0),Ae=BigInt(1),St=BigInt(2);function ms(n){return re(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...n})}function pr(n){let e=ms(n),{P:t,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");let u=i===void 0?bt:i,c=a?255:448,d=a?32:56,l=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?St**BigInt(254):St**BigInt(447),w=a?BigInt(8)*St**BigInt(251)-Ae:BigInt(4)*St**BigInt(445)-Ae,R=p+w+Ae,f=m=>I(m,t),g=y(l);function y(m){return mt(f(m),d)}function x(m){let v=de(O(m,d,"uCoordinate"));return a&&(v[31]&=127),f(K(v))}function k(m){return K(s(de(O(m,d,"scalar"))))}function A(m,v){let T=D(x(v),k(m));if(T===$e)throw new Error("invalid private or public key received");return y(T)}function B(m){return A(m,g)}let E=B,C=A;function S(m,v,T){let H=f(m*(v-T));return v=f(v-H),T=f(T+H),{x_2:v,x_3:T}}function D(m,v){ke("u",m,$e,t),ke("scalar",v,p,R);let T=v,H=m,U=Ae,q=$e,V=m,G=Ae,z=$e;for(let we=BigInt(c-1);we>=$e;we--){let Xe=T>>we&Ae;z^=Xe,{x_2:U,x_3:V}=S(z,U,V),{x_2:q,x_3:G}=S(z,q,G),z=Xe;let Ye=U+q,We=f(Ye*Ye),It=U-q,Rn=f(It*It),vn=We-Rn,Mr=V+G,Nr=V-G,En=f(Nr*Ye),kn=f(Mr*It),An=En+kn,Sn=En-kn;V=f(An*An),G=f(H*f(Sn*Sn)),U=f(We*Rn),q=f(vn*(We+f(h*vn)))}({x_2:U,x_3:V}=S(z,U,V)),{x_2:q,x_3:G}=S(z,q,G);let Ze=o(q);return f(U*Ze)}let L={secretKey:d,publicKey:d,seed:d},b=m=>(m=m===void 0?u(d):m,O(m,L.seed,"seed"),m),_={randomSecretKey:b};return Object.freeze(L),Object.freeze(_),Object.freeze({keygen:kt(b,E),getSharedSecret:C,getPublicKey:E,scalarMult:A,scalarMultBase:B,utils:_,GuBytes:g.slice(),lengths:L})}var ys=BigInt(0),oe=BigInt(1),hr=BigInt(2),xs=BigInt(3),_s=BigInt(5),ws=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),un={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:ws,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function mr(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),o=ye,a=n*n%o*n%o,u=Z(a,hr,o)*a%o,c=Z(u,oe,o)*n%o,d=Z(c,_s,o)*c%o,l=Z(d,e,o)*d%o,h=Z(l,t,o)*l%o,p=Z(h,r,o)*h%o,w=Z(p,s,o)*p%o,R=Z(w,s,o)*p%o,f=Z(R,e,o)*d%o;return{pow_p_5_8:Z(f,hr,o)*n%o,b2:a}}function yr(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var on=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function dn(n,e){let t=ye,r=I(e*e*e,t),s=I(r*r*e,t),o=mr(n*s).pow_p_5_8,i=I(n*r*o,t),a=I(e*i*i,t),u=i,c=I(i*on,t),d=a===n,l=a===I(-n,t),h=a===I(-n*on,t);return d&&(i=u),(l||h)&&(i=c),se(i,t)&&(i=I(-i,t)),{isValid:d||l,value:i}}var pe=dr(un,{uvRatio:dn}),fe=pe.Fp,xr=pe.Fn;function Rs(n){return lr(pe,ft,Object.assign({adjustScalarBytes:yr,zip215:!0},n))}var _r=Rs({});var xe=(()=>{let n=ye;return pr({P:n,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:r}=mr(e);return I(Z(t,xs,n)*r,n)},adjustScalarBytes:yr})})();var an=on,vs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Es=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ks=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),As=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),gr=n=>dn(oe,n),Ss=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),cn=n=>fe.create(K(n)&Ss);function br(n){let{d:e}=un,t=ye,r=g=>fe.create(g),s=r(an*n*n),o=r((s+oe)*ks),i=BigInt(-1),a=r((i-e*s)*r(s+e)),{isValid:u,value:c}=dn(o,a),d=r(c*n);se(d,t)||(d=r(-d)),u||(c=d),u||(i=s);let l=r(i*(s-oe)*As-a),h=c*c,p=r((c+c)*a),w=r(l*vs),R=r(oe-h),f=r(oe+h);return new pe(r(p*f),r(R*w),r(w*f),r(p*R))}var he=class n extends At{static BASE=new n(pe.BASE);static ZERO=new n(pe.ZERO);static Fp=fe;static Fn=xr;constructor(e){super(e)}static fromAffine(e){return new n(pe.fromAffine(e))}assertSame(e){if(!(e instanceof n))throw new Error("RistrettoPoint expected")}init(e){return new n(e)}static fromBytes(e){$(e,32);let{a:t,d:r}=un,s=ye,o=k=>fe.create(k),i=cn(e);if(!Vn(fe.toBytes(i),e)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),u=o(oe+t*a),c=o(oe-t*a),d=o(u*u),l=o(c*c),h=o(t*r*d-l),{isValid:p,value:w}=gr(o(h*l)),R=o(w*c),f=o(w*R*h),g=o((i+i)*R);se(g,s)&&(g=o(-g));let y=o(u*f),x=o(g*y);if(!p||se(x,s)||y===ys)throw new Error("invalid ristretto255 encoding 2");return new n(new pe(g,y,oe,x))}static fromHex(e){return n.fromBytes(Pe(e))}toBytes(){let{X:e,Y:t,Z:r,T:s}=this.ep,o=ye,i=f=>fe.create(f),a=i(i(r+t)*i(r-t)),u=i(e*t),c=i(u*u),{value:d}=gr(i(a*c)),l=i(d*a),h=i(d*u),p=i(l*h*s),w;if(se(s*p,o)){let f=i(t*an),g=i(e*an);e=f,t=g,w=i(l*Es)}else w=h;se(e*p,o)&&(t=i(-t));let R=i((r-t)*w);return se(R,o)&&(R=i(-R)),fe.toBytes(R)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:s,Y:o}=e.ep,i=c=>fe.create(c),a=i(t*o)===i(r*s),u=i(r*o)===i(t*s);return a||u}is0(){return this.equals(n.ZERO)}};Object.freeze(he.BASE);Object.freeze(he.ZERO);Object.freeze(he.prototype);Object.freeze(he);var Cs=Object.freeze({Point:he,hashToCurve(n,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=sn(n,t,64,ft);return Cs.deriveToCurve(r)},hashToScalar(n,e={DST:fr}){let t=sn(n,e.DST,64,ft);return xr.create(K(t))},deriveToCurve(n){$(n,64);let e=cn(n.subarray(0,32)),t=br(e),r=cn(n.subarray(32,64)),s=br(r);return new he(t.add(s))}});var Ct=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ue(e),$(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),X(s)}update(e){return ve(this),this.iHash.update(e),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},ln=(()=>{let n=((e,t,r)=>new Ct(e,t).update(r).digest());return n.create=(e,t)=>new Ct(e,t),n})();function Bs(n,e,t){return Ue(n),t===void 0&&(t=new Uint8Array(n.outputLen)),ln(n,t,e)}var fn=Uint8Array.of(0),wr=Uint8Array.of();function Ts(n,e,t,r=32){Ue(n),ie(r,"length"),$(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(r/s);t===void 0?t=wr:$(t,void 0,"info");let i=new Uint8Array(o*s),a=ln.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let d=0;d<o;d++)fn[0]=d+1,u.update(d===0?wr:c).update(t).update(fn).digestInto(c),i.set(c,s*d),a._cloneInto(u);return a.destroy(),u.destroy(),X(c,fn),i.slice(0,r)}var Rr=(n,e,t,r,s)=>Ts(n,Bs(n,e,t),r,s);var Os=new TextEncoder().encode("mygate-e2e-sealed-box-v1"),Ve=32,Se=12;function pn(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function hn(n){if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}return new Uint8Array(Buffer.from(n,"base64"))}function Ge(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function _e(n){if(n.length%2!==0)throw new Error("hex length must be even");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function vr(...n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Er(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function kr(){return xe.utils.randomSecretKey()}function gn(n){return xe.getPublicKey(n)}async function Ar(n){if(n.length!==32)throw new Error(`AES-256-GCM key must be 32 bytes, got ${n.length}`);return globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function Sr(n,e){let t=await Ar(n),r=Er(Se),s=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,e);return{ciphertext:new Uint8Array(s),nonce:r}}async function Cr(n,e,t){if(t.length!==Se)throw new Error(`AES-GCM nonce must be ${Se} bytes`);let r=await Ar(n),s=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:t},r,e);return new Uint8Array(s)}function Br(n,e,t){return Rr(je,n,vr(e,t),Os,32)}async function Is(n,e){if(n.length!==32)throw new Error("X25519 recipient public key must be 32 bytes");let t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=xe.getSharedSecret(t,n),o=Br(s,r,n),{ciphertext:i,nonce:a}=await Sr(o,e);return vr(r,a,i)}async function Ds(n,e,t){if(t.length<Ve+Se+16)throw new Error("sealed box payload too short");let r=t.slice(0,Ve),s=t.slice(Ve,Ve+Se),o=t.slice(Ve+Se),i=xe.getSharedSecret(n,r),a=Br(i,r,e);return Cr(a,o,s)}async function Tr(n,e){let t=Er(32),{ciphertext:r,nonce:s}=await Sr(t,e),o=await Is(_e(n),t);return{ciphertext_b64:pn(r),wrapped_key_b64:pn(o),payload_iv_b64:pn(s)}}async function Or(n,e){let t=_e(n),r=gn(t),s=await Ds(t,r,hn(e.wrapped_key_b64));return Cr(s,hn(e.ciphertext_b64),hn(e.payload_iv_b64))}var Ir="application/vnd.nodata.command+json",Dr="nodata.command/1";var Ls=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Hs=/^[a-z][a-z0-9_]{0,63}$/;function bn(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not_an_object"};let e=n,t=new Set(["nodata","id","cmd","fields","reply_to","issued_at"]),r=Object.keys(e).filter(i=>!t.has(i));if(r.length)return{ok:!1,reason:`unexpected_keys:${r.join(",")}`};if(e.nodata!==Dr)return{ok:!1,reason:"not_a_command"};if(typeof e.id!="string"||!/^[0-9a-f-]{36}$/i.test(e.id))return{ok:!1,reason:"bad_id"};if(typeof e.cmd!="string"||!Ls.test(e.cmd))return{ok:!1,reason:"bad_cmd"};if(e.reply_to!==null&&(typeof e.reply_to!="string"||!/^[0-9a-f-]{36}$/i.test(e.reply_to)))return{ok:!1,reason:"bad_reply_to"};if(typeof e.issued_at!="string"||Number.isNaN(Date.parse(e.issued_at)))return{ok:!1,reason:"bad_issued_at"};if(!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return{ok:!1,reason:"bad_fields"};let s=e.fields,o=Object.keys(s);if(o.length>64)return{ok:!1,reason:"too_many_fields"};for(let i of o){if(!Hs.test(i))return{ok:!1,reason:`bad_field_name:${i}`};let a=s[i];if(!(a===null||typeof a=="boolean"||typeof a=="number"||typeof a=="string"))return{ok:!1,reason:`field_not_flat:${i}`};if(typeof a=="string"&&a.length>2e3)return{ok:!1,reason:`field_too_long:${i}`}}return{ok:!0,envelope:e}}function Lr(n,e,t=null,r=new Date){let s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():Us();return{nodata:Dr,id:s,cmd:n,fields:e,reply_to:t,issued_at:r.toISOString()}}function Us(){let n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function mn(n){let e=t=>t===null||typeof t!="object"?t:Array.isArray(t)?t.map(e):Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])]));return JSON.stringify(e(n))}var ri={"read-request":{name:"request.json",maxBytes:16384},"read-refused":{name:"refused.json",maxBytes:16384},"folder-projection":{name:"projection.json",maxBytes:48*1024}};var yn={version:1,note:"NoData's public signing keys, pinned. chain_keys sign receipts and epoch seal roots; pack_envelope_signers sign evidence-pack envelopes. Source: https://nodatachat.com/api/chain/pubkey at publish time. A key counts only once a published version of this package lists it. receipt_context_since: when the key began signing receipts in their signing context (server mig 612, read from production 2026-10-19); a context-free receipt it signed after that (+15 min) fails verification.",pinned_from:"https://nodatachat.com/api/chain/pubkey (chain key, read 2026-09-30) \xB7 claude_identities where admin_user_id = the pack-signing identity (envelope signer, read 2026-09-30)",chain_keys:[{kid:"nd-chain-2026-05-03-bc58",ed25519_pubkey_hex:"b525adfa0035d5c7351b514a0316142586de9468ec5ee3b708cff0c4585b5036",ml_dsa65_pubkey_hex:"cc46f06f86d1b4a608a4c1167f1494a4cd1a837d215ff88e7b1aca49e82be3f32e190e1836d477670bae2c8a6f7648d3ce0d93b2f51ab0d3150d7dd45b0cf8217f119388e5a4b3770459654c4b0caab4d8a0ccdafdbc5231cd6c26410c38cd0ec62b21bf73b8e1e82daca3b1e4d520d9d25041917f4fd2b92bb19ffbe50f569ca29fa0185923732949daf5f832805303ef5a020cf3ea9de395d66e54d9bf52a56875087096cd8470918b7f25d623335c8662e7c8e6cefce7b88cc4cc6f7d32ed0f1a00332606af78332e9febb72b7e77b396b9da5ff96167055305595327ead40d2084a50f0d3fcd2423d8ed46edc5459ed1b0ff5a14f142bb38511b99a6da841895ccd65c19ab856bbdee270b48bc01ee8b0243fbc6e806851831409e5ae90d9c3300a9125042fd9b6d381c3eb09d5ee6f33e36bd5b41572bcce0350af8e217963154b550a163c5203f9a38a65312f23088c568d5af720c2ff4e979491109ca9ffdb9edc46f31410939e0264cbc02ea0106f9d6c8616222655e6593f8be5b9fa4423afec46aea9d53e42eb5d3f976cdd86d978a4599b87198d4fb8054bc40828f4d0100131537030053645616ecf48d013f8bbafb3a404735b7ffd6c88273765af340e84207f48be92e909ece357fa6ea2050e085570f413e48179a5aaac2bf216e54714d3ee1102e91fd23305b50b14b133299be4517d074732976b003a6669ecbceb2e40a8a1b2f4ca2b2a25d017b404b21672a0de61a45fd153684d730dc126f30a406d6b06447180258a9659cb3de926abd997b3f740c2783e334dd914ac663abc7f96217844ef0611619c35e30ed55f1563d8183b9f586d6c34715ce68708806105426e897df1473d53da835bed6288951238ed694c154655455ff61e13caeb592cc2857537fe9d2eb723bcad3898396af9673ba5b2f722092f0d2a9388e960ccde7272df5e2fe0ea9e499a909b655a59c85cfa1c622c651c8af20b4fb8bab9ab78d951c621d4b75c812246b2e925bcde42cc6a0a13467b4bcfb9aea5e4949effc71769dccc619eafc6d229cba478e3ad7289dc14b0c4842b4cf0cadd30deb9375fc1659d084779819705a6da7bccbf8d21ecd82391de5b61126d5b872f7d95514717b6fdc218dc0a048364c46142b114ee10d582740668f5b105edc034eb794c7e3906c77a44677e67709dbb1d3078783b488473e83e457e6ab98d2d659cf50066bc7f01190e065a9ef955e0257535bd5fab8ad007673637b2d005349e7f19fea2eeea82597867d5e366e41993775e4f4f70869fb1f9989d6d9902787f8233e9c7e586fe6bcf799ecf2da02ce08232ef1315b4e8857bcdb58bda53991f529d2ff023d0279552396dd0bb0fceaaf5dfb9eda0160bb09dd92b8085bc92c6006c20409cf9a5079072a09df221a76efc5ec13c97d154d22e382018ed8eb767f77aae578121c2231fe964338e637e7c060d555a2574b49c08956c729e79090b917e162488b1c9e962a3a921ac6f98a8c020c48aa2812f2f7a205a2d23aa2be1a953d9e33fbdea94688cf3d44200ed2cb009be8b684e99a96f0bc59eff5490eee0636b8b5665d7ddbb6ad44b90caa62b524f8a1caf6d0dbbc5e2ef0c2e65976d94e80e8dbd5ab8a420fdb638562bd2181c0ca243496582bab2847394e1e2dd4a24d4b24794b770b2475916746fb2bdc50f7994b4b346bfcfc5b4a99266cdf551340903d6994206ae1edb968c15d89f2a4cc6f3cb27b88989489b598f76fb6d1afa52e3a4c73175a216fa30d76acfccade7adb5628a88931b37bcff93c615a78a0b47827e385395e0b53c683f2ff07dd6cc636a086c295f06766570fc7652568676ecc5869378bdc0a63753807f1c7de7e5525d48328fa4103ed2ce9abafe0dc861055be6943cf2a87371ec1f9205c1955ddcf2f2ca982d877040dc92bf64278273c5ebbe3de0ef9d5eae255359e7ac97123b92488ffd0f1ea7deca36110135e02988be06bba4a3bf1b0da067976a6bc0c166ac349b2a853eb204fec6c142cad3decb05da15448f0d82d5faed3bc4beb400c51e05de06d950c128e2d3323a2d47dbf88684970084ed6608b95d7d585c3762c714c063c0a4ce1cacd5b31f261376bd972982957150dbbeb158999c1f60a76c6233a8749c10c016e0ad69bdac19e8c4d28126b7cc79c79aa82c25cef5521afdd759ca198b77c1a4a5f2c0497a4136e9818113c612d109de2cfaba691e05b791474599bf5cb918097f07b95dde658d2c5c01bf2bb6715dcb40c4c5686ec1642f9fd84377a90ea2456561ff91ba798d98211975c3da57be1b1e57a4660f979407e5f8616c4f62730161d2dcd86cf5383665c64cb77abbcf2e1406bc189e9575e3c1407aa6a467e6bd7a8edf7affde32b88dfa178902163a37c6b6c6bacb777a0bfbf46a0324c0ae5de7c2bdb6aad6ce51c0f5b4a5ab7c139d6bcdacc8ea46e37e040b785dbfc3145e408593c6f143dc1b4fde763e32e6d60c32d1a5c6d0bdf2d7d97f2bdeeba4a439abe7c75daced72a7678af1412f6c2917e39d6419c103f3a32e964369136a1183feb8d484712bcde8b14e2e8a7374dfb0dd7ee07dd15727b340005ed98bf5850b9de92b1912639e15f91d16968cd8bc336afc132ec6c93deba843e636de52f32be6e3c1e0ea50fdf03206c8dfa74f4c600e7d4d133c2ccc61ac50ae2f54e4f1ad02dc7ec86d8732cf12f0ac2c2ee10de6829695e539a6f76f9d9a4cda9d2ed1377c7a203baff1b",created_at:"2026-05-03T08:06:17.512936+00:00",retired_at:null,receipt_context_since:"2026-10-19T09:50:04.571Z"}],pack_envelope_signers:[{kid:"pack-signer-2026-04-29",ed25519_pubkey_hex:"853a62cb452a35fd6499d8fedb97448e0e24ef0d071343b2c9652aa2831bbdf6",status:"active",created_at:"2026-04-29T18:20:16.11538+00:00"}]};var wn=[...yn.chain_keys.filter(n=>!n.retired_at).map(n=>n.ed25519_pubkey_hex.toLowerCase()),...yn.pack_envelope_signers.map(n=>n.ed25519_pubkey_hex.toLowerCase())];function Fr(n){return Ge(je(_e(n))).slice(0,16)}var Hr="connect-command",ze=/^[0-9a-f]{16}$/,Fs=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Bt=class extends M{constructor(t,r,s,o){super(o,428,"approval_required");this.approveUrl=t;this.approvalId=r;this.orgApprovalId=s;this.name="FabricApprovalRequired"}};function xn(){return Ge(kr())}var Ke=class{constructor(e){this.http=e}newSecret(){return xn()}async open(e={}){let t=(e.secret??xn()).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("nd.fabric: secret must be 64 hex characters (nd.fabric.newSecret())");let r=Ge(gn(_e(t))),s=await this.http.raw("POST",`/api/v1/relay/enroll${e.replace?"?replace=true":""}`,{ecdh_pubkey_hex:r});if(!s.ok)throw Q("enroll",s);let o=String(s.data.ecdh_kid??"");if(!ze.test(o))throw new M("enroll answered without an address",s.status);if(o!==Fr(r))throw new M("enroll answered an address that is not this key's",s.status,"address_mismatch");return new Tt(this.http,t,o,(e.trustedReceiptKeys??wn).map(i=>i.toLowerCase()))}},Tt=class{constructor(e,t,r,s=wn){this.http=e;this.secret=t;this.address=r;this.trustedReceiptKeys=s}async invite(e={}){let t=await this.http.raw("POST","/api/v1/fabric-grants",{action:"invite",my_kid:this.address,template:"ping",...e.note?{note:e.note}:{},...e.days?{grant_days:e.days}:{},...Pr(e)});if(!t.ok)throw Q("invite",t);return{url:String(t.data.invite_url??""),expiresAt:typeof t.data.expires_at=="string"?t.data.expires_at:null,grantDays:typeof t.data.grant_days=="number"?t.data.grant_days:null}}async accept(e,t={}){let r=e.match(/invite=([^&\s]+)/),s=decodeURIComponent(r?r[1]:e.trim());if(!s.includes("."))throw new Error("nd.fabric.accept: give the invitation link or its token");let o=await this.http.raw("POST","/api/v1/fabric-grants",{action:"accept",token:s,subject_kid:this.address,mutual:t.oneWay!==!0,...t.termsAccepted?{terms_accepted:!0}:{},...Pr(t)});if(!o.ok)throw Q("accept",o);let i=o.data.partner??{};if(!i.sender_kid||!ze.test(i.sender_kid))throw new M("connected, but the invitation named no address of theirs to send to (they invited without one)",o.status,"no_partner_address");return{kid:i.sender_kid,name:i.name??null}}async partners(){let e=await this.http.raw("GET","/api/v1/fabric-grants");if(!e.ok)throw Q("partners",e);return Ms(e.data)}async send(e,t,r={},s={}){if(!Fs.test(t))throw new Error(`nd.fabric.send: '${t}' is not a command name (e.g. order.create)`);let o=await this.addressOf(e),i=Lr(t,r,s.replyTo??null),a=bn(i);if(!a.ok)throw new Error(`nd.fabric.send: not a command (${a.reason})`);let u=mn(i),c=await this.http.raw("GET",`/api/v1/relay/resolve?handle=${encodeURIComponent(o)}`);if(!c.ok)throw Q("resolve",c);let d=String(c.data.recipient_pubkey??"");if(!/^[0-9a-f]{64}$/.test(d))throw new M(`${o} has no public key to seal to`,c.status,"no_public_key");if(Fr(d)!==o)throw new M(`the key the directory gave for ${o} is not that address's key; nothing was sent`,c.status,"key_mismatch");let l=await Tr(d,new TextEncoder().encode(u)),h=await this.http.raw("POST","/api/v1/relay/send",{recipient_kid:o,...l,route_taken:"capsule",content_type_hint:Ir,purpose:Hr,ttl_hours:Math.min(Math.max(s.ttlHours??24,1),720),max_fetches:Math.min(Math.max(s.opens??1,1),20),released_sha256:Ur(u)});if(!h.ok)throw Q("send",h);return{id:String(h.data.id??""),commandId:i.id,to:o}}reply(e,t,r={}){if(!e.commandId)throw new Error("nd.fabric.reply: this message was not an opened command");return this.send(e.from,t,r,{replyTo:e.commandId})}async inbox(e={}){let t=await this.http.raw("GET","/api/v1/relay/inbox");if(!t.ok)throw Q("inbox",t);let r=(t.data.items??[]).filter(i=>i.purpose===Hr),s=e.accept?new Set(e.accept):null,o=[];for(let i of r){let a={relayId:i.id,from:i.sender_kid,fromOrg:i.sender?.org??null},u=await this.http.raw("GET",`/api/v1/relay/fetch/${encodeURIComponent(i.id)}`);if(!u.ok){o.push({...a,status:"unopened",reason:String(u.data.refused??u.data.error??u.status),verified:{committed:null,receiptSignature:null}});continue}let c=Ns(u.data.receipt,this.trustedReceiptKeys),d=null;try{let p=await Or(this.secret,u.data),w=bn(JSON.parse(new TextDecoder().decode(p)));d=w.ok?w.envelope:null}catch{d=null}if(!d){o.push({...a,status:"refused",reason:"not_a_command",verified:{committed:null,receiptSignature:c}});continue}let h={committed:typeof u.data.released_sha256=="string"?Ur(mn(d))===u.data.released_sha256:null,receiptSignature:c};if(s&&!s.has(d.cmd)){o.push({...a,status:"refused",reason:`not_accepted:${d.cmd}`,cmd:d.cmd,commandId:d.id,verified:h});continue}o.push({...a,status:"accepted",cmd:d.cmd,fields:d.fields,replyTo:d.reply_to,commandId:d.id,issuedAt:d.issued_at,verified:h})}return o}onCommand(e,t={}){let r=Math.max(t.everyMs??5e3,250),s=new Set,o=!1,i=null,a=()=>{o=!0,i?.()};t.signal?.aborted&&(o=!0),t.signal?.addEventListener("abort",a,{once:!0});let u=()=>new Promise(d=>{let l=setTimeout(d,r);i=()=>{clearTimeout(l),d()}}),c=(async()=>{for(;!o;){try{for(let d of await this.inbox({accept:t.accept})){if(o)break;if(!(d.status==="unopened"||s.has(d.relayId))){s.add(d.relayId),s.size>5e3&&s.delete(s.values().next().value);try{d.status==="accepted"?await e(d):await t.onRefused?.(d)}catch(l){await t.onError?.(l)}}}}catch(d){await t.onError?.(d)}o||await u()}})();return{stop:async()=>{a(),await c},get running(){return!o}}}async disconnect(e){let t=await this.addressOf(e),r=await this.http.raw("GET","/api/v1/fabric-grants");if(!r.ok)throw Q("partners",r);let s=(r.data.grants??[]).filter(a=>!a.revoked_at&&a.subject_kid===t),o=(r.data.inbound??[]).filter(a=>a.subject_kid===this.address&&(a.allowed_sender_kids??[]).includes(t)),i=0;for(let a of s){let u=await this.http.raw("PATCH","/api/v1/fabric-grants",{grant_id:a.id,reason:"disconnected from the SDK"});if(!u.ok)throw Q("disconnect",u);i++}for(let a of o){let u=await this.http.raw("POST","/api/v1/fabric-grants",{action:"leave",grant_id:a.id});if(!u.ok)throw Q("disconnect",u);i++}return{ended:i}}async addressOf(e){if(typeof e!="string")return e.kid;let t=e.trim().toLowerCase();if(ze.test(t))return t;let r=(await this.partners()).filter(s=>(s.name??"").toLowerCase()===t);if(r.length===1)return r[0].kid;throw new Error(r.length?`nd.fabric: '${e}' names ${r.length} connections; use the address`:`nd.fabric: no connection named '${e}'`)}};function Ms(n){let e=new Map;for(let t of n.grants??[])!t.revoked_at&&ze.test(t.subject_kid)&&e.set(t.subject_kid,{kid:t.subject_kid,name:t.partner_name??null});for(let t of n.inbound??[])for(let r of t.allowed_sender_kids??[]){if(!ze.test(r))continue;let s=e.get(r);e.set(r,{kid:r,name:s?.name??t.partner_name??null})}return[...e.values()]}function Ur(n){return Ge(je(new TextEncoder().encode(n)))}function _n(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return"["+n.map(_n).join(",")+"]";let e=n;return"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+_n(e[t])).join(",")+"}"}function Ns(n,e=wn){let t=n;if(!t?.payload||!t.signature_hex||!t.signing_pubkey_hex)return null;if(!e.includes(t.signing_pubkey_hex.toLowerCase()))return!1;try{return _r.verify(_e(t.signature_hex),new TextEncoder().encode(_n(t.payload)),_e(t.signing_pubkey_hex))}catch{return!1}}function Pr(n){return n.orgApprovalId?{org_approval_id:n.orgApprovalId}:n.approvalId?{approval_id:n.approvalId}:{}}function Q(n,e){let t=e.data;if(e.status===428){let s=typeof t.approval=="object"&&t.approval!==null?t.approval:{},o=typeof t.lock=="object"&&t.lock!==null?t.lock:{};return new Bt((s.approve_url??(typeof t.approve_url=="string"?t.approve_url:null))||null,s.approval_id??null,o.lock_id??null,`${n}: waiting for a person's approval${t.why?` (${String(t.why)})`:""}. Approve it in the browser, then call again with the approval id.`)}let r=String(t.refused??t.error??`HTTP ${e.status}`);return new M(`${n} refused: ${r}${t.reason?` (${String(t.reason)})`:t.why?` (${String(t.why)})`:""}`,e.status,String(t.refused??t.error??""))}var Ot=class{http;_encrypt;capsules;tenants;scan;fabric;engines;_compute;constructor(e){this.http=new Je(e),this._compute=new He(this.http),this._encrypt=new Re(this.http),this.capsules=new Oe(this.http),this.tenants=new Ie(this.http),this.scan=new De(this.http),this.fabric=new Ke(this.http),this.engines=new Le(this.http)}compute(e){return this._compute.run(e)}verify(e){return this._compute.verify(e)}authorize(e){return this.http.post("/api/v1/authorize",e)}get channel(){return this.engines.channel}get webhook(){return this.engines.webhook}get deliver(){return this.engines.deliver}get evidence(){return this.engines.evidence}get vault(){return this.engines.vault}get governance(){return this.engines.governance}agent(e){return new Be(this.http.baseURL,e)}encrypt(e){return this._encrypt.encrypt(e)}decrypt(e){return this._encrypt.decrypt(e)}batchEncrypt(e,t){return this._encrypt.batchEncrypt(e,t)}batchDecrypt(e,t){return this._encrypt.batchDecrypt(e,t)}batchNative(e,t){return this._encrypt.batchNative(e,t)}encryptObject(e,t,r){return this._encrypt.encryptObject(e,t,r)}decryptObject(e,t,r){return this._encrypt.decryptObject(e,t,r)}async ping(){let e=Date.now();return await this.http.get("/api/health"),{success:!0,latencyMs:Date.now()-e}}};function js(n,e,t){let r=new Ot({apiKey:e.apiKey,baseUrl:e.baseUrl}),s=e.encryptFields||[],o=e.decryptFields||[],i=e.skipPaths||[];o.length>0&&n.addHook("preHandler",async a=>{if(i.some(c=>a.url.startsWith(c))||!a.body||typeof a.body!="object"||a.method==="GET")return;if(!e.decryptHeader||a.headers[e.decryptHeader.toLowerCase()])try{a.body=await r.decryptObject(a.body,o,a.headers["x-requester"]||"fastify-plugin")}catch{}}),s.length>0&&n.addHook("onSend",async(a,u,c)=>{if(typeof c!="string")return c;try{let d=JSON.parse(c);if(typeof d=="object"&&d!==null){let l=await r.encryptObject(d,s,e.context);return JSON.stringify(l)}}catch{}return c}),t()}0&&(module.exports={nodataFastify});
2
2
  /*! Bundled license information:
3
3
 
4
4
  @noble/curves/utils.js:
@@ -1 +1 @@
1
- import{r as d}from"../chunk-R62LOWK3.mjs";function f(a,e,i){let o=new d({apiKey:e.apiKey,baseUrl:e.baseUrl}),s=e.encryptFields||[],y=e.decryptFields||[],p=e.skipPaths||[];y.length>0&&a.addHook("preHandler",async t=>{if(p.some(r=>t.url.startsWith(r))||!t.body||typeof t.body!="object"||t.method==="GET")return;if(!e.decryptHeader||t.headers[e.decryptHeader.toLowerCase()])try{t.body=await o.decryptObject(t.body,y,t.headers["x-requester"]||"fastify-plugin")}catch{}}),s.length>0&&a.addHook("onSend",async(t,c,r)=>{if(typeof r!="string")return r;try{let n=JSON.parse(r);if(typeof n=="object"&&n!==null){let l=await o.encryptObject(n,s,e.context);return JSON.stringify(l)}}catch{}return r}),i()}export{f as nodataFastify};
1
+ import{r as d}from"../chunk-AMJ6QDQ3.mjs";function f(a,e,i){let o=new d({apiKey:e.apiKey,baseUrl:e.baseUrl}),s=e.encryptFields||[],y=e.decryptFields||[],p=e.skipPaths||[];y.length>0&&a.addHook("preHandler",async t=>{if(p.some(r=>t.url.startsWith(r))||!t.body||typeof t.body!="object"||t.method==="GET")return;if(!e.decryptHeader||t.headers[e.decryptHeader.toLowerCase()])try{t.body=await o.decryptObject(t.body,y,t.headers["x-requester"]||"fastify-plugin")}catch{}}),s.length>0&&a.addHook("onSend",async(t,c,r)=>{if(typeof r!="string")return r;try{let n=JSON.parse(r);if(typeof n=="object"&&n!==null){let l=await o.encryptObject(n,s,e.context);return JSON.stringify(l)}}catch{}return r}),i()}export{f as nodataFastify};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodatachat/sdk",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "description": "NoData SDK for the Information Access Processor: one call decides whether an identity may access information and returns a signed proof.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -1,11 +0,0 @@
1
- var F=class extends Error{constructor(t,r,s,o){super(t);this.status=r;this.code=s;this.retryAfter=o;this.name="NoDataError"}};var qr="https://www.nodatacapsule.com",Nr=3e4,jr=2,Qe=class{apiKey;baseUrl;timeout;retries;customHeaders;onRequest;onResponse;onError;constructor(e){if(!e.apiKey)throw new Error("NoData SDK: apiKey is required. Get one at https://www.nodatacapsule.com/developers");this.apiKey=e.apiKey,this.baseUrl=(e.baseUrl||qr).replace(/\/+$/,""),this.timeout=e.timeout||Nr,this.retries=e.retries??jr,this.customHeaders=e.headers||{},this.onRequest=e.onRequest,this.onResponse=e.onResponse,this.onError=e.onError}async request(e,t,r,s){let o=`${this.baseUrl}${t}`;if(s){let l=new URLSearchParams(Object.fromEntries(Object.entries(s).filter(([,d])=>d!=null))).toString();l&&(o+=`?${l}`)}let i={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json","User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...this.customHeaders},signal:AbortSignal.timeout(this.timeout)};r&&e!=="GET"&&(i.body=JSON.stringify(r)),this.onRequest?.(o,i);let a=null,u=1+this.retries;for(let c=1;c<=u;c++){let l=Date.now();try{let d=await fetch(o,i),h=Date.now()-l;if(this.onResponse?.(o,d.status,h),d.status===429&&c<u){let w=parseInt(d.headers.get("Retry-After")||"5",10);await It(w*1e3);continue}if(d.status>=500&&c<u){await It(1e3*c);continue}let p=await d.json().catch(()=>({}));if(!d.ok)throw new F(p.error||`HTTP ${d.status}`,d.status,p.code,d.status===429?parseInt(d.headers.get("Retry-After")||"60",10):void 0);return p}catch(d){if(a=d instanceof Error?d:new Error(String(d)),this.onError?.(o,a),d instanceof F)throw d;if(c<u){await It(1e3*c);continue}}}throw a||new Error("Request failed")}get baseURL(){return this.baseUrl}get(e,t){return this.request("GET",e,void 0,t)}post(e,t){return this.request("POST",e,t)}del(e,t){return this.request("DELETE",e,t)}async raw(e,t,r){let s=`${this.baseUrl}${t}`,o={method:e,headers:{Authorization:`Bearer ${this.apiKey}`,"User-Agent":"@nodatachat/sdk/1.0.0","X-SDK-Version":"1.0.0",...r!==void 0?{"Content-Type":"application/json"}:{},...this.customHeaders},signal:AbortSignal.timeout(this.timeout),...r!==void 0?{body:JSON.stringify(r)}:{}};this.onRequest?.(s,o);let i=Date.now(),a=await fetch(s,o);this.onResponse?.(s,a.status,Date.now()-i);let u=await a.json().catch(()=>({})),c=u&&typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:u;return{ok:a.ok,status:a.status,data:{...c,...u.error?{error:u.error}:{}}}}};function It(n){return new Promise(e=>setTimeout(e,n))}var Re=class{constructor(e){this.http=e}async encrypt(e){return this.http.post("/api/v1/encrypt",{field:e.field,value:e.value,context:e.context})}async decrypt(e){return this.http.post("/api/v1/decrypt",{ciphertext:e.ciphertext,field:e.field,requester:e.requester,purpose:e.purpose})}async batchEncrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.encrypt({...o,context:o.context||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,ciphertext:"",field:e[i].field,audit_id:"",algorithm:"",error:o.reason?.message||"Encryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchDecrypt(e,t){let s=(await Promise.allSettled(e.map(o=>this.decrypt({...o,requester:o.requester||t})))).map((o,i)=>o.status==="fulfilled"?o.value:{success:!1,value:"",field:e[i].field,audit_id:"",error:o.reason?.message||"Decryption failed"});return{success:s.every(o=>o.success),results:s,ok:s.filter(o=>o.success).length,failed:s.filter(o=>!o.success).length}}async batchNative(e,t){return this.http.post("/api/v1/batch",{items:e,context:t})}async encryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.encrypt({field:o,value:s,context:r})).ciphertext)}async decryptObject(e,t,r){return this.processObject(e,t,async(s,o)=>(await this.decrypt({ciphertext:s,field:o,requester:r})).value)}async processObject(e,t,r){if(e==null)return e;if(Array.isArray(e))return Promise.all(e.map(s=>this.processObject(s,t,r)));if(typeof e=="object"){let s={};for(let[o,i]of Object.entries(e))t.includes(o)&&typeof i=="string"&&i.length>0?s[o]=await r(i,o):typeof i=="object"?s[o]=await this.processObject(i,t,r):s[o]=i;return s}return e}};var Ce=class{constructor(e){this.http=e}async registerTable(e){return this.http.post("/api/v1/governance/tables",{table_name:e.table,encrypted_columns:e.encryptedColumns??[],plaintext_columns:e.plaintextColumns??[],classification_column:e.classificationColumn,hkdf_prefix:e.hkdfPrefix,ui_label:e.uiLabel})}async listTables(){return this.http.get("/api/v1/governance/tables")}async grant(e){return this.http.post("/api/v1/governance/grant",{agent:e.agent,table:e.table,columns:e.columns,where:e.where,classifications:e.classifications,ttl_seconds:e.ttlSeconds})}async revoke(e){return this.http.post("/api/v1/governance/revoke",{handle:e.agent,jti:e.jti,reason:e.reason})}},Be=class{constructor(e,t){this.baseURL=e;this.grantToken=t}async read(e){let t=e.handle??$r(this.grantToken);if(!t)throw new F("AgentReader.read: could not derive agent handle from token; pass { handle }",400);let r=`${this.baseURL}/api/agents/${encodeURIComponent(t)}/read`,s=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${this.grantToken}`,"Content-Type":"application/json"},body:JSON.stringify({table:e.table,columns:e.columns,where:e.where,limit:e.limit})}),o=await s.json().catch(()=>({}));if(!s.ok)throw new F(o.error||`HTTP ${s.status}`,s.status,o.reason);return o}};function $r(n){try{let t=(n.startsWith("ndca-")?n.slice(5):n).split(".")[1];if(!t)return null;let r=t.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(r)).handle??null}catch{return null}}var Je=class{constructor(e,t){this.http=e;this.ref=t}add(e){let t=e.sections?.length?e.sections:[{label:e.title||"Document",classification:e.classification||"confidential",text:e.content??""}];return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`,{title:e.title,sections:t,recipients:e.recipients,zero_knowledge:e.zero_knowledge})}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/documents`)}},et=class{constructor(e,t){this.http=e;this.ref=t}add(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/members`)}},tt=class{constructor(e,t){this.http=e;this.ref=t}get(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.limit&&(t.limit=String(e.limit)),this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/audit`,Object.keys(t).length?t:void 0)}},nt=class{constructor(e,t){this.http=e;this.ref=t}grant(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,e)}list(){return this.http.get(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-grants`,{action:"revoke",agent_id:e})}read(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.ref)}/ai-read`,e)}},Te=class{constructor(e,t){this.http=e;this.summary=t;this.documents=new Je(e,t.slug),this.members=new et(e,t.slug),this.audit=new tt(e,t.slug),this.ai=new nt(e,t.slug)}documents;members;audit;ai;get id(){return this.summary.capsule_id}get slug(){return this.summary.slug}get status(){return this.summary.status}embed(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/embed-token`,e)}revoke(e){return this.http.post(`/api/v1/capsules/${encodeURIComponent(this.slug)}/revoke`,{reason:e?.reason})}},Oe=class{constructor(e){this.http=e}async create(e){let t=await this.http.post("/api/v1/capsules",e);return new Te(this.http,t)}async get(e){let t=await this.http.get(`/api/v1/capsules/${encodeURIComponent(e)}`);return new Te(this.http,t)}list(e){return this.http.get("/api/v1/capsules",e?.limit?{limit:String(e.limit)}:void 0)}overview(){return this.http.get("/api/v1/overview")}};var Ie=class{constructor(e){this.http=e}create(e){return this.http.post("/api/v1/tenants",e)}get(e){return this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`)}};var De=class{constructor(e){this.http=e}async orgId(){let e=await this.http.get("/api/v1/partner/me");if(!e?.org_id)throw new Error("nd.scan: could not resolve the org from this API key.");return e.org_id}async enable(e){let t=await this.orgId(),r=await this.http.post(`/api/v1/tenants/${encodeURIComponent(t)}/capsule/install-token`,{}),s=r.install_token??"",o=(e.api_base??this.http.baseURL).replace(/\/+$/,""),i=e.source==="folder"?`--source folder --path ${e.path??"./"}`:e.source==="drive"?`--source drive --folder ${e.folder_id??"<folder-id>"}`:`--source ${e.source}`,a=e.per_customer?` --per-customer ${e.per_customer}`:"";return{ok:!0,scan_id:s.slice(0,12),install_token:s,install_command:`npx @nodatachat/capsule-agent --token ${s} --vault-api --api ${o} ${i}${a}`,expires_at:r.expires_at??null}}async status(){let e=await this.orgId(),t=await this.http.get(`/api/v1/tenants/${encodeURIComponent(e)}`);return{deployments:t.capsule?.deployments??[],last_scan_at:t.capsule?.last_scan_at??null,open_findings_count:t.capsule?.open_findings_count??0}}findings(e){let t={};return e?.limit&&(t.limit=String(e.limit)),e?.all&&(t.all="true"),this.http.get("/api/v1/scan/findings",Object.keys(t).length?t:void 0)}approve(e){return this.http.post("/api/v1/scan/approve",{finding_ids:e})}execute(e){return this.http.post("/api/v1/scan/execute",{finding_ids:e})}};var rt=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/secure-channel/init",{label:e.label,ttl:e.ttl||"24h",max_transfers:e.maxTransfers||10,require_verification:e.requireVerification??!1})}async send(e){let t=typeof e.data=="string"?e.data:JSON.stringify(e.data);return this.http.post("/api/secure-channel/upload",{channel_token:e.token,content:t,content_type:e.contentType||"application/json",burn_after_read:e.burnAfterRead??!0})}async receive(e){return this.http.post("/api/secure-channel/download",{channel_token:e.token,verification_code:e.verificationCode})}async verify(e,t){return this.http.post("/api/secure-channel/verify-code",{channel_token:e,code:t})}async proof(e){return this.http.post("/api/secure-channel/delivery-proof",{channel_token:e})}};var st=class{constructor(e){this.http=e}async create(e={}){return this.http.post("/api/webhook/channel/create",{label:e.label,ttl:e.ttl||"30d",max_events:e.maxEvents||1e4,burn_after_read:e.burnAfterRead??!1})}async events(e,t){return this.http.post("/api/webhook/channel/events",{channel_token:e,limit:t?.limit||50,since:t?.since})}async list(){return this.http.get("/api/webhook/dashboard")}};var ot=class{constructor(e){this.http=e}async send(e){return this.http.post("/api/v1/deliver",{content:e.content,to:e.to,ttl:e.ttl||"24h",burn:e.burn??!0,maxViews:e.maxViews||1})}async burn(e,t){return this.http.post("/api/burn/create",{content:e,ttl_hours:t?.ttlHours||24,burn_after_read:t?.burnAfterRead??!0,available_at:t?.availableAt})}async read(e){return this.http.post("/api/burn/read",{drop_id:e})}};var it=class{constructor(e){this.http=e}async query(e={}){return this.http.get("/api/v1/evidence",{from:e.from||"",to:e.to||"",action:e.action||"",field:e.field||"",limit:String(e.limit||100)})}async certificate(e){return this.http.post("/api/proof-certificate",{audit_id:e})}async verify(e){return this.http.post("/api/receipt/verify",{proof_hash:e})}};var at=class{constructor(e){this.http=e}async create(e){return this.http.post("/api/vault/create",e)}async read(e){return this.http.post("/api/vault/read",{vault_id:e})}async delete(e){return this.http.post("/api/vault/delete",{vault_id:e})}async status(){return this.http.get("/api/vault/status")}};var Le=class{governance;blindRelay;channel;deliver;evidence;vault;webhook;constructor(e){this.governance=new Ce(e),this.blindRelay=new Re(e),this.channel=new rt(e),this.deliver=new ot(e),this.evidence=new it(e),this.vault=new at(e),this.webhook=new st(e)}};var He=class{constructor(e){this.http=e}async run(e){let t=await this.http.post("/api/v1/documents/compute",{question:e.question,clearance:e.clearance??"internal",...e.sections?{sections:e.sections}:{},...e.text?{text:e.text}:{}}),r=(t.sections??[]).map(s=>({title:s.title??"",classification:s.classification??"internal",sent:!!s.sent}));return{decision:t.decision??(r.some(s=>s.sent)?"allow":"deny"),answer:t.answer??null,model:t.model??null,sections:r,proof:{id:t.proof?.receipt_id??t.proof?.id??null,hash:t.proof?.hash??null,persisted:!!t.proof?.persisted}}}async verify(e){let t=await this.http.post("/api/access/verify",{proof_id:e});return{authentic:!!t.authentic,unaltered:!!t.unaltered,signer:t.signer,surface:t.surface,decision:t.decision,issuedAt:t.issued_at}}};function Dt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ie(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(`${t}expected number, got ${typeof n}`)}if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new RangeError(`${t}expected integer >= 0, got ${n}`)}}function $(n,e,t=""){let r=Dt(n),s=n?.length,o=e!==void 0;if(!r||o&&s!==e){let i=t&&`"${t}" `,a=o?` of length ${e}`:"",u=r?`length=${s}`:`type=${typeof n}`,c=i+"expected Uint8Array"+a+", got "+u;throw r?new RangeError(c):new TypeError(c)}return n}function Ue(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(ie(n.outputLen),ie(n.blockLen),n.outputLen<1)throw new Error('"outputLen" must be >= 1');if(n.blockLen<1)throw new Error('"blockLen" must be >= 1')}function ve(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function ct(n,e){$(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length<t)throw new RangeError('"digestInto() output" expected to be of length >='+t)}function X(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function ut(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Y(n,e){return n<<32-e|n>>>e}var Sn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function lt(n){if($(n),Sn)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Vr[n[t]];return e}var ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function An(n){if(n>=ee._0&&n<=ee._9)return n-ee._0;if(n>=ee.A&&n<=ee.F)return n-(ee.A-10);if(n>=ee.a&&n<=ee.f)return n-(ee.a-10)}function Pe(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Sn)try{return Uint8Array.fromHex(n)}catch(s){throw s instanceof SyntaxError?new RangeError(s.message):s}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){let i=An(n.charCodeAt(o)),a=An(n.charCodeAt(o+1));if(i===void 0||a===void 0){let u=n[o]+n[o+1];throw new RangeError('hex string expected, got non-hex character "'+u+'" at index '+o)}r[s]=i*16+a}return r}function Lt(...n){let e=0;for(let r=0;r<n.length;r++){let s=n[r];$(s),e+=s.length}let t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){let o=n[r];t.set(o,s),s+=o.length}return t}function Ht(n,e={}){let t=(s,o)=>n(o).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.canXOF=r.canXOF,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Cn(n=32){ie(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var Ut=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function Bn(n,e,t){return n&e^~n&t}function Tn(n,e,t){return n&e^n&t^e&t}var Me=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){ve(this),$(e);let{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let i=0;i<o;){let a=Math.min(s-this.pos,o-i);if(a===s){let u=ut(e);for(;s<=o-i;i+=s)this.process(u,i);continue}r.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:s,isLE:o}=this,{pos:i}=this;t[i++]=128,X(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(r,0),i=0);for(let d=i;d<s;d++)t[d]=0;r.setBigUint64(s-8,BigInt(this.length*8),o),this.process(r,0);let a=ut(e),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=u/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:s,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=s,e.pos=a,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var q=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var dt=BigInt(4294967295),On=BigInt(32);function Gr(n,e=!1){return e?{h:Number(n&dt),l:Number(n>>On&dt)}:{h:Number(n>>On&dt)|0,l:Number(n&dt)|0}}function In(n,e=!1){let t=n.length,r=new Uint32Array(t),s=new Uint32Array(t);for(let o=0;o<t;o++){let{h:i,l:a}=Gr(n[o],e);[r[o],s[o]]=[i,a]}return[r,s]}var Pt=(n,e,t)=>n>>>t,Mt=(n,e,t)=>n<<32-t|e>>>t,ge=(n,e,t)=>n>>>t|e<<32-t,be=(n,e,t)=>n<<32-t|e>>>t,Fe=(n,e,t)=>n<<64-t|e>>>t-32,qe=(n,e,t)=>n>>>t-32|e<<64-t;function W(n,e,t,r){let s=(e>>>0)+(r>>>0);return{h:n+t+(s/2**32|0)|0,l:s|0}}var Dn=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),Ln=(n,e,t,r)=>e+t+r+(n/2**32|0)|0,Hn=(n,e,t,r)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0),Un=(n,e,t,r,s)=>e+t+r+s+(n/2**32|0)|0,Pn=(n,e,t,r,s)=>(n>>>0)+(e>>>0)+(t>>>0)+(r>>>0)+(s>>>0),Mn=(n,e,t,r,s,o)=>e+t+r+s+o+(n/2**32|0)|0;var Kr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ae=new Uint32Array(64),Ft=class extends Me{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:s,E:o,F:i,G:a,H:u}=this;return[e,t,r,s,o,i,a,u]}set(e,t,r,s,o,i,a,u){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=u|0}process(e,t){for(let d=0;d<16;d++,t+=4)ae[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=ae[d-15],p=ae[d-2],w=Y(h,7)^Y(h,18)^h>>>3,R=Y(p,17)^Y(p,19)^p>>>10;ae[d]=R+ae[d-7]+w+ae[d-16]|0}let{A:r,B:s,C:o,D:i,E:a,F:u,G:c,H:l}=this;for(let d=0;d<64;d++){let h=Y(a,6)^Y(a,11)^Y(a,25),p=l+h+Bn(a,u,c)+Kr[d]+ae[d]|0,R=(Y(r,2)^Y(r,13)^Y(r,22))+Tn(r,s,o)|0;l=c,c=u,u=a,a=i+p|0,i=o,o=s,s=r,r=p+R|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,u=u+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,s,o,i,a,u,c,l)}roundClean(){X(ae)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),X(this.buffer)}},qt=class extends Ft{A=te[0]|0;B=te[1]|0;C=te[2]|0;D=te[3]|0;E=te[4]|0;F=te[5]|0;G=te[6]|0;H=te[7]|0;constructor(){super(32)}};var Fn=In(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),Zr=Fn[0],Xr=Fn[1],ce=new Uint32Array(80),ue=new Uint32Array(80),Nt=class extends Me{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:s,Ch:o,Cl:i,Dh:a,Dl:u,Eh:c,El:l,Fh:d,Fl:h,Gh:p,Gl:w,Hh:R,Hl:f}=this;return[e,t,r,s,o,i,a,u,c,l,d,h,p,w,R,f]}set(e,t,r,s,o,i,a,u,c,l,d,h,p,w,R,f){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=s|0,this.Ch=o|0,this.Cl=i|0,this.Dh=a|0,this.Dl=u|0,this.Eh=c|0,this.El=l|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=w|0,this.Hh=R|0,this.Hl=f|0}process(e,t){for(let x=0;x<16;x++,t+=4)ce[x]=e.getUint32(t),ue[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let k=ce[x-15]|0,A=ue[x-15]|0,B=ge(k,A,1)^ge(k,A,8)^Pt(k,A,7),E=be(k,A,1)^be(k,A,8)^Mt(k,A,7),C=ce[x-2]|0,S=ue[x-2]|0,D=ge(C,S,19)^Fe(C,S,61)^Pt(C,S,6),L=be(C,S,19)^qe(C,S,61)^Mt(C,S,6),b=Hn(E,L,ue[x-7],ue[x-16]),_=Un(b,B,D,ce[x-7],ce[x-16]);ce[x]=_|0,ue[x]=b|0}let{Ah:r,Al:s,Bh:o,Bl:i,Ch:a,Cl:u,Dh:c,Dl:l,Eh:d,El:h,Fh:p,Fl:w,Gh:R,Gl:f,Hh:g,Hl:y}=this;for(let x=0;x<80;x++){let k=ge(d,h,14)^ge(d,h,18)^Fe(d,h,41),A=be(d,h,14)^be(d,h,18)^qe(d,h,41),B=d&p^~d&R,E=h&w^~h&f,C=Pn(y,A,E,Xr[x],ue[x]),S=Mn(C,g,k,B,Zr[x],ce[x]),D=C|0,L=ge(r,s,28)^Fe(r,s,34)^Fe(r,s,39),b=be(r,s,28)^qe(r,s,34)^qe(r,s,39),_=r&o^r&a^o&a,m=s&i^s&u^i&u;g=R|0,y=f|0,R=p|0,f=w|0,p=d|0,w=h|0,{h:d,l:h}=W(c|0,l|0,S|0,D|0),c=a|0,l=u|0,a=o|0,u=i|0,o=r|0,i=s|0;let v=Dn(D,b,m);r=Ln(v,S,L,_),s=v|0}({h:r,l:s}=W(this.Ah|0,this.Al|0,r|0,s|0)),{h:o,l:i}=W(this.Bh|0,this.Bl|0,o|0,i|0),{h:a,l:u}=W(this.Ch|0,this.Cl|0,a|0,u|0),{h:c,l}=W(this.Dh|0,this.Dl|0,c|0,l|0),{h:d,l:h}=W(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:w}=W(this.Fh|0,this.Fl|0,p|0,w|0),{h:R,l:f}=W(this.Gh|0,this.Gl|0,R|0,f|0),{h:g,l:y}=W(this.Hh|0,this.Hl|0,g|0,y|0),this.set(r,s,o,i,a,u,c,l,d,h,p,w,R,f,g,y)}roundClean(){X(ce,ue)}destroy(){this.destroyed=!0,X(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},jt=class extends Nt{Ah=q[0]|0;Al=q[1]|0;Bh=q[2]|0;Bl=q[3]|0;Ch=q[4]|0;Cl=q[5]|0;Dh=q[6]|0;Dl=q[7]|0;Eh=q[8]|0;El=q[9]|0;Fh=q[10]|0;Fl=q[11]|0;Gh=q[12]|0;Gl=q[13]|0;Hh=q[14]|0;Hl=q[15]|0;constructor(){super(64)}};var Ne=Ht(()=>new qt,Ut(1));var ft=Ht(()=>new jt,Ut(3));var O=(n,e,t)=>$(n,e,t),Vt=ie,Gt=lt,Q=(...n)=>Lt(...n),qn=n=>Pe(n),gt=Dt,bt=n=>Cn(n),ht=BigInt(0),$t=BigInt(1);function Ee(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new TypeError(t+"expected boolean, got type="+typeof n)}return n}function Yr(n){if(typeof n=="bigint"){if(!pt(n))throw new RangeError("positive bigint expected, got "+n)}else Vt(n);return n}function ne(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function Nn(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?ht:BigInt("0x"+n)}function zt(n){return Nn(lt(n))}function K(n){return Nn(lt(le($(n)).reverse()))}function Kt(n,e){if(ie(e),e===0)throw new RangeError("zero length");n=Yr(n);let t=n.toString(16);if(t.length>e*2)throw new RangeError("number too large");return Pe(t.padStart(e*2,"0"))}function mt(n,e){return Kt(n,e).reverse()}function jn(n,e){if(n=O(n),e=O(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function le(n){return Uint8Array.from(O(n))}function yt(n){if(typeof n!="string")throw new TypeError("ascii string expected, got "+typeof n);return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new RangeError(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var pt=n=>typeof n=="bigint"&&ht<=n;function Wr(n,e,t){return pt(n)&&pt(e)&&pt(t)&&e<=n&&n<t}function ke(n,e,t,r){if(!Wr(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function Zt(n){if(n<ht)throw new Error("expected non-negative bigint, got "+n);let e;for(e=0;n>ht;n>>=$t,e+=1);return e}var $n=n=>($t<<BigInt(n))-$t;function re(n,e={},t={}){if(Object.prototype.toString.call(n)!=="[object Object]")throw new TypeError("expected valid options object");function r(o,i,a){if(!a&&i!=="function"&&!Object.hasOwn(n,o))throw new TypeError(`param "${o}" is invalid: expected own property`);let u=n[o];if(a&&u===void 0)return;let c=typeof u;if(c!==i||u===null)throw new TypeError(`param "${o}" is invalid: expected ${i}, got ${c}`)}let s=(o,i)=>Object.entries(o).forEach(([a,u])=>r(a,u,i));s(e,!1),s(t,!0)}var Xt=()=>{throw new Error("not implemented")};var N=BigInt(0),P=BigInt(1),me=BigInt(2),Kn=BigInt(3),Zn=BigInt(4),Xn=BigInt(5),Qr=BigInt(7),Yn=BigInt(8),Jr=BigInt(9),Wn=BigInt(16);function I(n,e){if(e<=N)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=N?t:e+t}function Z(n,e,t){if(e<N)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >N;)r*=r,r%=t;return r}function Vn(n,e){if(n===N)throw new Error("invert: expected non-zero number");if(e<=N)throw new Error("invert: expected positive modulus, got "+e);let t=I(n,e),r=e,s=N,o=P,i=P,a=N;for(;t!==N;){let c=r/t,l=r-t*c,d=s-i*c,h=o-a*c;r=t,t=l,s=i,o=a,i=d,a=h}if(r!==P)throw new Error("invert: does not exist");return I(s,e)}function Yt(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function Qn(n,e){let t=n,r=(t.ORDER+P)/Zn,s=t.pow(e,r);return Yt(t,s,e),s}function es(n,e){let t=n,r=(t.ORDER-Xn)/Yn,s=t.mul(e,me),o=t.pow(s,r),i=t.mul(e,o),a=t.mul(t.mul(i,me),o),u=t.mul(i,t.sub(a,t.ONE));return Yt(t,u,e),u}function ts(n){let e=wt(n),t=Jn(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),i=(n+Qr)/Wn;return((a,u)=>{let c=a,l=c.pow(u,i),d=c.mul(l,r),h=c.mul(l,s),p=c.mul(l,o),w=c.eql(c.sqr(d),u),R=c.eql(c.sqr(h),u);l=c.cmov(l,d,w),d=c.cmov(p,h,R);let f=c.eql(c.sqr(d),u),g=c.cmov(l,d,f);return Yt(c,g,u),g})}function Jn(n){if(n<Kn)throw new Error("sqrt is not defined for small field");let e=n-P,t=0;for(;e%me===N;)e/=me,t++;let r=me,s=wt(n);for(;Gn(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Qn;let o=s.pow(r,e),i=(e+P)/me;return function(u,c){let l=u;if(l.is0(c))return c;if(Gn(l,c)!==1)throw new Error("Cannot find square root");let d=t,h=l.mul(l.ONE,o),p=l.pow(c,e),w=l.pow(c,i);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let R=1,f=l.sqr(p);for(;!l.eql(f,l.ONE);)if(R++,f=l.sqr(f),R===d)throw new Error("Cannot find square root");let g=P<<BigInt(d-R-1),y=l.pow(h,g);d=R,h=l.sqr(y),p=l.mul(p,h),w=l.mul(w,y)}return w}}function ns(n){return n%Zn===Kn?Qn:n%Yn===Xn?es:n%Wn===Jr?ts(n):Jn(n)}var se=(n,e)=>(I(n,e)&P)===P,rs=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function er(n){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=rs.reduce((r,s)=>(r[s]="function",r),e);if(re(n,t),ne(n.BYTES,"BYTES"),ne(n.BITS,"BITS"),n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=P)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function ss(n,e,t){let r=n;if(t<N)throw new Error("invalid exponent, negatives unsupported");if(t===N)return r.ONE;if(t===P)return e;let s=r.ONE,o=e;for(;t>N;)t&P&&(s=r.mul(s,o)),o=r.sqr(o),t>>=P;return s}function _t(n,e,t=!1){let r=n,s=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((a,u,c)=>r.is0(u)?a:(s[c]=a,r.mul(a,u)),r.ONE),i=r.inv(o);return e.reduceRight((a,u,c)=>r.is0(u)?a:(s[c]=r.mul(a,s[c]),r.mul(a,u)),i),s}function Gn(n,e){let t=n,r=(t.ORDER-P)/me,s=t.pow(e,r),o=t.eql(s,t.ONE),i=t.eql(s,t.ZERO),a=t.eql(s,t.neg(t.ONE));if(!o&&!i&&!a)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function os(n,e){if(e!==void 0&&Vt(e),n<=N)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Zt(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected bit length (${t}) >= n.length (${e})`);let r=e!==void 0?e:t,s=Math.ceil(r/8);return{nBitLength:r,nByteLength:s}}var zn=new WeakMap,xt=class{ORDER;BITS;BYTES;isLE;ZERO=N;ONE=P;_lengths;_mod;constructor(e,t={}){if(e<=P)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:o}=os(e,r);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=o,Object.freeze(this)}create(e){return I(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return N<=e&&e<this.ORDER}is0(e){return e===N}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&P)===P}neg(e){return I(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return I(e*e,this.ORDER)}add(e,t){return I(e+t,this.ORDER)}sub(e,t){return I(e-t,this.ORDER)}mul(e,t){return I(e*t,this.ORDER)}pow(e,t){return ss(this,e,t)}div(e,t){return I(e*Vn(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Vn(e,this.ORDER)}sqrt(e){let t=zn.get(this);return t||zn.set(this,t=ns(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?mt(e,this.BYTES):Kt(e,this.BYTES)}fromBytes(e,t=!1){O(e);let{_lengths:r,BYTES:s,isLE:o,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>s)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,o?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let u=o?K(e):zt(e);if(a&&(u=I(u,i)),!t&&!this.isValid(u))throw new Error("invalid field element: outside of range 0..ORDER");return u}invertBatch(e){return _t(this,e)}cmov(e,t,r){return Ee(r,"condition"),r?t:e}};Object.freeze(xt.prototype);function wt(n,e={}){return new xt(n,e)}var Rt=BigInt(0),en=BigInt(1);function tr(n,e){let t=e.negate();return n?t:e}function Et(n,e){let t=_t(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function or(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function Wt(n,e){or(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=$n(n),i=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:i}}function nr(n,e,t){let{windowSize:r,mask:s,maxNumber:o,shiftBy:i}=t,a=Number(n&s),u=n>>i;a>r&&(a-=o,u+=en);let c=e*r,l=c+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:u,offset:l,isZero:d,isNeg:h,isNegF:p,offsetF:c}}var Qt=new WeakMap,ir=new WeakMap;function Jt(n){return ir.get(n)||1}function rr(n){if(n!==Rt)throw new Error("invalid wNAF")}var vt=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Rt;)t&en&&(r=r.add(s)),s=s.double(),t>>=en;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=Wt(t,this.bits),o=[],i=e,a=i;for(let u=0;u<r;u++){a=i,o.push(a);for(let c=1;c<s;c++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE,i=Wt(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:u,offset:c,isZero:l,isNeg:d,isNegF:h,offsetF:p}=nr(r,a,i);r=u,l?o=o.add(tr(h,t[p])):s=s.add(tr(d,t[c]))}return rr(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){let o=Wt(e,this.bits);for(let i=0;i<o.windows&&r!==Rt;i++){let{nextN:a,offset:u,isZero:c,isNeg:l}=nr(r,i,o);if(r=a,!c){let d=t[u];s=s.add(l?d.negate():d)}}return rr(r),s}getPrecomputes(e,t,r){let s=Qt.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),Qt.set(t,s))),s}cached(e,t,r){let s=Jt(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){let o=Jt(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){or(t,this.bits),ir.set(e,t),Qt.delete(e)}hasCache(e){return Jt(e)!==1}};function sr(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return er(e),e}else return wt(n,{isLE:t})}function ar(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let u of["p","n","h"]){let c=e[u];if(!(typeof c=="bigint"&&c>Rt))throw new Error(`CURVE.${u} must be positive bigint`)}let s=sr(e.p,t.Fp,r),o=sr(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let u of a)if(!s.isValid(e[u]))throw new Error(`CURVE.${u} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:o}}function kt(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var de=BigInt(0),M=BigInt(1),tn=BigInt(2),is=BigInt(8);function as(n,e,t,r){let s=n.sqr(t),o=n.sqr(r),i=n.add(n.mul(e.a,s),o),a=n.add(n.ONE,n.mul(e.d,n.mul(s,o)));return n.eql(i,a)}function cr(n,e={}){let t=e,r=ar("edwards",n,t,t.FpFnLE),{Fp:s,Fn:o}=r,i=r.CURVE,{h:a}=i;re(t,{},{uvRatio:"function"});let u=tn<<BigInt(o.BYTES*8)-M,c=R=>s.create(R),l=t.uvRatio===void 0?(R,f)=>{try{return{isValid:!0,value:s.sqrt(s.div(R,f))}}catch{return{isValid:!1,value:de}}}:t.uvRatio;if(!as(s,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(R,f,g=!1){let y=g?M:de;return ke("coordinate "+R,f,y,u),f}function h(R){if(!(R instanceof p))throw new Error("EdwardsPoint expected")}class p{static BASE=new p(i.Gx,i.Gy,M,c(i.Gx*i.Gy));static ZERO=new p(de,M,M,de);static Fp=s;static Fn=o;X;Y;Z;T;constructor(f,g,y,x){this.X=d("x",f),this.Y=d("y",g),this.Z=d("z",y,!0),this.T=d("t",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(f){if(f instanceof p)throw new Error("extended point not allowed");let{x:g,y}=f||{};return d("x",g),d("y",y),new p(g,y,M,c(g*y))}static fromBytes(f,g=!1){let y=s.BYTES,{a:x,d:k}=i;f=le(O(f,y,"point")),Ee(g,"zip215");let A=le(f),B=f[y-1];A[y-1]=B&-129;let E=K(A),C=g?u:s.ORDER;ke("point.y",E,de,C);let S=c(E*E),D=c(S-M),L=c(k*S-x),{isValid:b,value:_}=l(D,L);if(!b)throw new Error("bad point: invalid y coordinate");let m=(_&M)===M,v=(B&128)!==0;if(!g&&_===de&&v)throw new Error("bad point: x=0 and x_0=1");return v!==m&&(_=c(-_)),p.fromAffine({x:_,y:E})}static fromHex(f,g=!1){return p.fromBytes(qn(f),g)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,g=!0){return w.createCache(this,f),g||this.multiply(tn),this}assertValidity(){let f=this,{a:g,d:y}=i;if(f.is0())throw new Error("bad point: ZERO");let{X:x,Y:k,Z:A,T:B}=f,E=c(x*x),C=c(k*k),S=c(A*A),D=c(S*S),L=c(E*g),b=c(S*c(L+C)),_=c(D+c(y*c(E*C)));if(b!==_)throw new Error("bad point: equation left != right (1)");let m=c(x*k),v=c(A*B);if(m!==v)throw new Error("bad point: equation left != right (2)")}equals(f){h(f);let{X:g,Y:y,Z:x}=this,{X:k,Y:A,Z:B}=f,E=c(g*B),C=c(k*x),S=c(y*B),D=c(A*x);return E===C&&S===D}is0(){return this.equals(p.ZERO)}negate(){return new p(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:f}=i,{X:g,Y:y,Z:x}=this,k=c(g*g),A=c(y*y),B=c(tn*c(x*x)),E=c(f*k),C=g+y,S=c(c(C*C)-k-A),D=E+A,L=D-B,b=E-A,_=c(S*L),m=c(D*b),v=c(S*b),T=c(L*D);return new p(_,m,T,v)}add(f){h(f);let{a:g,d:y}=i,{X:x,Y:k,Z:A,T:B}=this,{X:E,Y:C,Z:S,T:D}=f,L=c(x*E),b=c(k*C),_=c(B*y*D),m=c(A*S),v=c((x+k)*(E+C)-L-b),T=m-_,H=m+_,U=c(b-g*L),j=c(v*T),V=c(H*U),G=c(v*U),z=c(T*H);return new p(j,V,z,G)}subtract(f){return h(f),this.add(f.negate())}multiply(f){if(!o.isValidNot0(f))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:g,f:y}=w.cached(this,f,x=>Et(p,x));return Et(p,[g,y])[0]}multiplyUnsafe(f){if(!o.isValid(f))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return f===de?p.ZERO:this.is0()||f===M?this:w.unsafe(this,f,g=>Et(p,g))}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.unsafe(this,i.n).is0()}toAffine(f){let g=this,y=f,{X:x,Y:k,Z:A}=g,B=g.is0();y==null&&(y=B?is:s.inv(A));let E=c(x*y),C=c(k*y),S=s.mul(A,y);if(B)return{x:de,y:M};if(S!==M)throw new Error("invZ was invalid");return{x:E,y:C}}clearCofactor(){return a===M?this:this.multiplyUnsafe(a)}toBytes(){let{x:f,y:g}=this.toAffine(),y=s.toBytes(g);return y[y.length-1]|=f&M?128:0,y}toHex(){return Gt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=new vt(p,o.BITS);return o.BITS>=8&&p.BASE.precompute(8),Object.freeze(p.prototype),Object.freeze(p),p}var At=class{static BASE;static ZERO;static Fp;static Fn;ep;constructor(e){this.ep=e}static fromBytes(e){Xt()}static fromHex(e){Xt()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Gt(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.ep.precompute(e,t),this}};function ur(n,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');let r=e,s=t;re(s,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function"});let{prehash:o}=s,{BASE:i,Fp:a,Fn:u}=n,c=r.outputLen,l=2*a.BYTES;if(c!==void 0&&(ne(c,"hash.outputLen"),c!==l))throw new Error(`hash.outputLen must be ${l}, got ${c}`);let d=s.randomBytes===void 0?bt:s.randomBytes,h=s.adjustScalarBytes===void 0?b=>b:s.adjustScalarBytes,p=s.domain===void 0?(b,_,m)=>{if(Ee(m,"phflag"),_.length||m)throw new Error("Contexts/pre-hash are not supported");return b}:s.domain;function w(b){return u.create(K(b))}function R(b){let _=E.secretKey;O(b,E.secretKey,"secretKey");let m=O(r(b),2*_,"hashedSecretKey"),v=h(m.slice(0,_)),T=m.slice(_,2*_),H=w(v);return{head:v,prefix:T,scalar:H}}function f(b){let{head:_,prefix:m,scalar:v}=R(b),T=i.multiply(v),H=T.toBytes();return{head:_,prefix:m,scalar:v,point:T,pointBytes:H}}function g(b){return f(b).pointBytes}function y(b=Uint8Array.of(),..._){let m=Q(..._);return w(r(p(m,O(b,void 0,"context"),!!o)))}function x(b,_,m={}){b=O(b,void 0,"message"),o&&(b=o(b));let{prefix:v,scalar:T,pointBytes:H}=f(_),U=y(m.context,v,b),j=i.multiply(U).toBytes(),V=y(m.context,j,H,b),G=u.create(U+V*T);if(!u.isValid(G))throw new Error("sign failed: invalid s");let z=Q(j,u.toBytes(G));return O(z,E.signature,"result")}let k={zip215:s.zip215};function A(b,_,m,v=k){let{context:T}=v,H=v.zip215===void 0?!!k.zip215:v.zip215,U=E.signature;b=O(b,U,"signature"),_=O(_,void 0,"message"),m=O(m,E.publicKey,"publicKey"),H!==void 0&&Ee(H,"zip215"),o&&(_=o(_));let j=U/2,V=b.subarray(0,j),G=K(b.subarray(j,U)),z,Ze,we;try{z=n.fromBytes(m,H),Ze=n.fromBytes(V,H),we=i.multiplyUnsafe(G)}catch{return!1}if(!H&&z.isSmallOrder())return!1;let Xe=y(T,V,m,_);return Ze.add(z.multiplyUnsafe(Xe)).subtract(we).clearCofactor().is0()}let B=a.BYTES,E={secretKey:B,publicKey:B,signature:2*B,seed:B};function C(b){return b=b===void 0?d(E.seed):b,O(b,E.seed,"seed")}function S(b){return gt(b)&&b.length===E.secretKey}function D(b,_){try{return!!n.fromBytes(b,_===void 0?k.zip215:_)}catch{return!1}}let L={getExtendedPublicKey:f,randomSecretKey:C,isValidSecretKey:S,isValidPublicKey:D,toMontgomery(b){let{y:_}=n.fromBytes(b),m=E.publicKey,v=m===32;if(!v&&m!==57)throw new Error("only defined for 25519 and 448");let T=v?a.div(M+_,M-_):a.div(_-M,_+M);return a.toBytes(T)},toMontgomerySecret(b){let _=E.secretKey;O(b,_);let m=r(b.subarray(0,_));return h(m).subarray(0,_)}};return Object.freeze(E),Object.freeze(L),Object.freeze({keygen:kt(C,g),getPublicKey:g,sign:x,verify:A,utils:L,Point:n,lengths:E})}function je(n,e){if(ne(n),ne(e),e<0||e>4)throw new Error("invalid I2OSP length: "+e);if(n<0||n>2**(8*e)-1)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function cs(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function us(n){if(!gt(n)&&typeof n!="string")throw new Error("DST must be Uint8Array or ascii string");let e=typeof n=="string"?yt(n):n;if(e.length===0)throw new Error("DST must be non-empty");return e}function nn(n,e,t,r){O(n),ne(t),e=us(e),e.length>255&&(e=r(Q(yt("H2C-OVERSIZE-DST-"),e)));let{outputLen:s,blockLen:o}=r,i=Math.ceil(t/s);if(t>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=Q(e,je(e.length,1)),u=new Uint8Array(o),c=je(t,2),l=new Array(i),d=r(Q(u,n,c,je(0,1),a));l[0]=r(Q(d,je(1,1),a));for(let p=1;p<i;p++){let w=[cs(d,l[p-1]),je(p+1,1),a];l[p]=r(Q(...w))}return Q(...l).slice(0,t)}var lr="HashToScalar-";var $e=BigInt(0),Ae=BigInt(1),St=BigInt(2);function ls(n){return re(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function"}),Object.freeze({...n})}function dr(n){let e=ls(n),{P:t,type:r,adjustScalarBytes:s,powPminus2:o,randomBytes:i}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");let u=i===void 0?bt:i,c=a?255:448,l=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?St**BigInt(254):St**BigInt(447),w=a?BigInt(8)*St**BigInt(251)-Ae:BigInt(4)*St**BigInt(445)-Ae,R=p+w+Ae,f=m=>I(m,t),g=y(d);function y(m){return mt(f(m),l)}function x(m){let v=le(O(m,l,"uCoordinate"));return a&&(v[31]&=127),f(K(v))}function k(m){return K(s(le(O(m,l,"scalar"))))}function A(m,v){let T=D(x(v),k(m));if(T===$e)throw new Error("invalid private or public key received");return y(T)}function B(m){return A(m,g)}let E=B,C=A;function S(m,v,T){let H=f(m*(v-T));return v=f(v-H),T=f(T+H),{x_2:v,x_3:T}}function D(m,v){ke("u",m,$e,t),ke("scalar",v,p,R);let T=v,H=m,U=Ae,j=$e,V=m,G=Ae,z=$e;for(let we=BigInt(c-1);we>=$e;we--){let Xe=T>>we&Ae;z^=Xe,{x_2:U,x_3:V}=S(z,U,V),{x_2:j,x_3:G}=S(z,j,G),z=Xe;let Ye=U+j,We=f(Ye*Ye),Ot=U-j,_n=f(Ot*Ot),wn=We-_n,Mr=V+G,Fr=V-G,Rn=f(Fr*Ye),vn=f(Mr*Ot),En=Rn+vn,kn=Rn-vn;V=f(En*En),G=f(H*f(kn*kn)),U=f(We*_n),j=f(wn*(We+f(h*wn)))}({x_2:U,x_3:V}=S(z,U,V)),{x_2:j,x_3:G}=S(z,j,G);let Ze=o(j);return f(U*Ze)}let L={secretKey:l,publicKey:l,seed:l},b=m=>(m=m===void 0?u(l):m,O(m,L.seed,"seed"),m),_={randomSecretKey:b};return Object.freeze(L),Object.freeze(_),Object.freeze({keygen:kt(b,E),getSharedSecret:C,getPublicKey:E,scalarMult:A,scalarMultBase:B,utils:_,GuBytes:g.slice(),lengths:L})}var ds=BigInt(0),oe=BigInt(1),fr=BigInt(2),fs=BigInt(3),ps=BigInt(5),hs=BigInt(8),ye=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),an={p:ye,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:hs,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function gr(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),s=BigInt(80),o=ye,a=n*n%o*n%o,u=Z(a,fr,o)*a%o,c=Z(u,oe,o)*n%o,l=Z(c,ps,o)*c%o,d=Z(l,e,o)*l%o,h=Z(d,t,o)*d%o,p=Z(h,r,o)*h%o,w=Z(p,s,o)*p%o,R=Z(w,s,o)*p%o,f=Z(R,e,o)*l%o;return{pow_p_5_8:Z(f,fr,o)*n%o,b2:a}}function br(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}var rn=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function cn(n,e){let t=ye,r=I(e*e*e,t),s=I(r*r*e,t),o=gr(n*s).pow_p_5_8,i=I(n*r*o,t),a=I(e*i*i,t),u=i,c=I(i*rn,t),l=a===n,d=a===I(-n,t),h=a===I(-n*rn,t);return l&&(i=u),(d||h)&&(i=c),se(i,t)&&(i=I(-i,t)),{isValid:l||d,value:i}}var pe=cr(an,{uvRatio:cn}),fe=pe.Fp,mr=pe.Fn;function gs(n){return ur(pe,ft,Object.assign({adjustScalarBytes:br,zip215:!0},n))}var yr=gs({});var xe=(()=>{let n=ye;return dr({P:n,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:r}=gr(e);return I(Z(t,fs,n)*r,n)},adjustScalarBytes:br})})();var sn=rn,bs=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ms=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ys=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),xs=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),pr=n=>cn(oe,n),_s=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),on=n=>fe.create(K(n)&_s);function hr(n){let{d:e}=an,t=ye,r=g=>fe.create(g),s=r(sn*n*n),o=r((s+oe)*ys),i=BigInt(-1),a=r((i-e*s)*r(s+e)),{isValid:u,value:c}=cn(o,a),l=r(c*n);se(l,t)||(l=r(-l)),u||(c=l),u||(i=s);let d=r(i*(s-oe)*xs-a),h=c*c,p=r((c+c)*a),w=r(d*bs),R=r(oe-h),f=r(oe+h);return new pe(r(p*f),r(R*w),r(w*f),r(p*R))}var he=class n extends At{static BASE=new n(pe.BASE);static ZERO=new n(pe.ZERO);static Fp=fe;static Fn=mr;constructor(e){super(e)}static fromAffine(e){return new n(pe.fromAffine(e))}assertSame(e){if(!(e instanceof n))throw new Error("RistrettoPoint expected")}init(e){return new n(e)}static fromBytes(e){$(e,32);let{a:t,d:r}=an,s=ye,o=k=>fe.create(k),i=on(e);if(!jn(fe.toBytes(i),e)||se(i,s))throw new Error("invalid ristretto255 encoding 1");let a=o(i*i),u=o(oe+t*a),c=o(oe-t*a),l=o(u*u),d=o(c*c),h=o(t*r*l-d),{isValid:p,value:w}=pr(o(h*d)),R=o(w*c),f=o(w*R*h),g=o((i+i)*R);se(g,s)&&(g=o(-g));let y=o(u*f),x=o(g*y);if(!p||se(x,s)||y===ds)throw new Error("invalid ristretto255 encoding 2");return new n(new pe(g,y,oe,x))}static fromHex(e){return n.fromBytes(Pe(e))}toBytes(){let{X:e,Y:t,Z:r,T:s}=this.ep,o=ye,i=f=>fe.create(f),a=i(i(r+t)*i(r-t)),u=i(e*t),c=i(u*u),{value:l}=pr(i(a*c)),d=i(l*a),h=i(l*u),p=i(d*h*s),w;if(se(s*p,o)){let f=i(t*sn),g=i(e*sn);e=f,t=g,w=i(d*ms)}else w=h;se(e*p,o)&&(t=i(-t));let R=i((r-t)*w);return se(R,o)&&(R=i(-R)),fe.toBytes(R)}equals(e){this.assertSame(e);let{X:t,Y:r}=this.ep,{X:s,Y:o}=e.ep,i=c=>fe.create(c),a=i(t*o)===i(r*s),u=i(r*o)===i(t*s);return a||u}is0(){return this.equals(n.ZERO)}};Object.freeze(he.BASE);Object.freeze(he.ZERO);Object.freeze(he.prototype);Object.freeze(he);var ws=Object.freeze({Point:he,hashToCurve(n,e){let t=e?.DST===void 0?"ristretto255_XMD:SHA-512_R255MAP_RO_":e.DST,r=nn(n,t,64,ft);return ws.deriveToCurve(r)},hashToScalar(n,e={DST:lr}){let t=nn(n,e.DST,64,ft);return mr.create(K(t))},deriveToCurve(n){$(n,64);let e=on(n.subarray(0,32)),t=hr(e),r=on(n.subarray(32,64)),s=hr(r);return new he(t.add(s))}});var Ct=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Ue(e),$(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),X(s)}update(e){return ve(this),this.iHash.update(e),this}digestInto(e){ve(this),ct(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},un=(()=>{let n=((e,t,r)=>new Ct(e,t).update(r).digest());return n.create=(e,t)=>new Ct(e,t),n})();function Rs(n,e,t){return Ue(n),t===void 0&&(t=new Uint8Array(n.outputLen)),un(n,t,e)}var ln=Uint8Array.of(0),xr=Uint8Array.of();function vs(n,e,t,r=32){Ue(n),ie(r,"length"),$(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let o=Math.ceil(r/s);t===void 0?t=xr:$(t,void 0,"info");let i=new Uint8Array(o*s),a=un.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let l=0;l<o;l++)ln[0]=l+1,u.update(l===0?xr:c).update(t).update(ln).digestInto(c),i.set(c,s*l),a._cloneInto(u);return a.destroy(),u.destroy(),X(c,ln),i.slice(0,r)}var _r=(n,e,t,r,s)=>vs(n,Rs(n,e,t),r,s);var Es=new TextEncoder().encode("mygate-e2e-sealed-box-v1"),Ve=32,Se=12;function dn(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return typeof btoa<"u"?btoa(e):Buffer.from(e,"binary").toString("base64")}function fn(n){if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}return new Uint8Array(Buffer.from(n,"base64"))}function Ge(n){return Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")}function _e(n){if(n.length%2!==0)throw new Error("hex length must be even");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function wr(...n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}function Rr(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function vr(){return xe.utils.randomSecretKey()}function pn(n){return xe.getPublicKey(n)}async function Er(n){if(n.length!==32)throw new Error(`AES-256-GCM key must be 32 bytes, got ${n.length}`);return globalThis.crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function kr(n,e){let t=await Er(n),r=Rr(Se),s=await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:r},t,e);return{ciphertext:new Uint8Array(s),nonce:r}}async function Ar(n,e,t){if(t.length!==Se)throw new Error(`AES-GCM nonce must be ${Se} bytes`);let r=await Er(n),s=await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:t},r,e);return new Uint8Array(s)}function Sr(n,e,t){return _r(Ne,n,wr(e,t),Es,32)}async function ks(n,e){if(n.length!==32)throw new Error("X25519 recipient public key must be 32 bytes");let t=xe.utils.randomSecretKey(),r=xe.getPublicKey(t),s=xe.getSharedSecret(t,n),o=Sr(s,r,n),{ciphertext:i,nonce:a}=await kr(o,e);return wr(r,a,i)}async function As(n,e,t){if(t.length<Ve+Se+16)throw new Error("sealed box payload too short");let r=t.slice(0,Ve),s=t.slice(Ve,Ve+Se),o=t.slice(Ve+Se),i=xe.getSharedSecret(n,r),a=Sr(i,r,e);return Ar(a,o,s)}async function Cr(n,e){let t=Rr(32),{ciphertext:r,nonce:s}=await kr(t,e),o=await ks(_e(n),t);return{ciphertext_b64:dn(r),wrapped_key_b64:dn(o),payload_iv_b64:dn(s)}}async function Br(n,e){let t=_e(n),r=pn(t),s=await As(t,r,fn(e.wrapped_key_b64));return Ar(s,fn(e.ciphertext_b64),fn(e.payload_iv_b64))}var Tr="application/vnd.nodata.command+json",Or="nodata.command/1";var Ss=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Cs=/^[a-z][a-z0-9_]{0,63}$/;function hn(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,reason:"not_an_object"};let e=n,t=new Set(["nodata","id","cmd","fields","reply_to","issued_at"]),r=Object.keys(e).filter(i=>!t.has(i));if(r.length)return{ok:!1,reason:`unexpected_keys:${r.join(",")}`};if(e.nodata!==Or)return{ok:!1,reason:"not_a_command"};if(typeof e.id!="string"||!/^[0-9a-f-]{36}$/i.test(e.id))return{ok:!1,reason:"bad_id"};if(typeof e.cmd!="string"||!Ss.test(e.cmd))return{ok:!1,reason:"bad_cmd"};if(e.reply_to!==null&&(typeof e.reply_to!="string"||!/^[0-9a-f-]{36}$/i.test(e.reply_to)))return{ok:!1,reason:"bad_reply_to"};if(typeof e.issued_at!="string"||Number.isNaN(Date.parse(e.issued_at)))return{ok:!1,reason:"bad_issued_at"};if(!e.fields||typeof e.fields!="object"||Array.isArray(e.fields))return{ok:!1,reason:"bad_fields"};let s=e.fields,o=Object.keys(s);if(o.length>64)return{ok:!1,reason:"too_many_fields"};for(let i of o){if(!Cs.test(i))return{ok:!1,reason:`bad_field_name:${i}`};let a=s[i];if(!(a===null||typeof a=="boolean"||typeof a=="number"||typeof a=="string"))return{ok:!1,reason:`field_not_flat:${i}`};if(typeof a=="string"&&a.length>2e3)return{ok:!1,reason:`field_too_long:${i}`}}return{ok:!0,envelope:e}}function Ir(n,e,t=null,r=new Date){let s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():Bs();return{nodata:Or,id:s,cmd:n,fields:e,reply_to:t,issued_at:r.toISOString()}}function Bs(){let n=new Uint8Array(16);globalThis.crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n,t=>t.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function gn(n){let e=t=>t===null||typeof t!="object"?t:Array.isArray(t)?t.map(e):Object.fromEntries(Object.keys(t).sort().map(r=>[r,e(t[r])]));return JSON.stringify(e(n))}var Ko={"read-request":{name:"request.json",maxBytes:16384},"read-refused":{name:"refused.json",maxBytes:16384},"folder-projection":{name:"projection.json",maxBytes:48*1024}};var bn={version:1,note:"NoData's public signing keys, pinned. chain_keys sign receipts and epoch seal roots; pack_envelope_signers sign evidence-pack envelopes. Source: https://nodatachat.com/api/chain/pubkey at publish time. A key counts only once a published version of this package lists it. receipt_context_since: when the key began signing receipts in their signing context (server mig 612, read from production 2026-10-19); a context-free receipt it signed after that (+15 min) fails verification.",pinned_from:"https://nodatachat.com/api/chain/pubkey (chain key, read 2026-09-30) \xB7 claude_identities where admin_user_id = the pack-signing identity (envelope signer, read 2026-09-30)",chain_keys:[{kid:"nd-chain-2026-05-03-bc58",ed25519_pubkey_hex:"b525adfa0035d5c7351b514a0316142586de9468ec5ee3b708cff0c4585b5036",ml_dsa65_pubkey_hex:"cc46f06f86d1b4a608a4c1167f1494a4cd1a837d215ff88e7b1aca49e82be3f32e190e1836d477670bae2c8a6f7648d3ce0d93b2f51ab0d3150d7dd45b0cf8217f119388e5a4b3770459654c4b0caab4d8a0ccdafdbc5231cd6c26410c38cd0ec62b21bf73b8e1e82daca3b1e4d520d9d25041917f4fd2b92bb19ffbe50f569ca29fa0185923732949daf5f832805303ef5a020cf3ea9de395d66e54d9bf52a56875087096cd8470918b7f25d623335c8662e7c8e6cefce7b88cc4cc6f7d32ed0f1a00332606af78332e9febb72b7e77b396b9da5ff96167055305595327ead40d2084a50f0d3fcd2423d8ed46edc5459ed1b0ff5a14f142bb38511b99a6da841895ccd65c19ab856bbdee270b48bc01ee8b0243fbc6e806851831409e5ae90d9c3300a9125042fd9b6d381c3eb09d5ee6f33e36bd5b41572bcce0350af8e217963154b550a163c5203f9a38a65312f23088c568d5af720c2ff4e979491109ca9ffdb9edc46f31410939e0264cbc02ea0106f9d6c8616222655e6593f8be5b9fa4423afec46aea9d53e42eb5d3f976cdd86d978a4599b87198d4fb8054bc40828f4d0100131537030053645616ecf48d013f8bbafb3a404735b7ffd6c88273765af340e84207f48be92e909ece357fa6ea2050e085570f413e48179a5aaac2bf216e54714d3ee1102e91fd23305b50b14b133299be4517d074732976b003a6669ecbceb2e40a8a1b2f4ca2b2a25d017b404b21672a0de61a45fd153684d730dc126f30a406d6b06447180258a9659cb3de926abd997b3f740c2783e334dd914ac663abc7f96217844ef0611619c35e30ed55f1563d8183b9f586d6c34715ce68708806105426e897df1473d53da835bed6288951238ed694c154655455ff61e13caeb592cc2857537fe9d2eb723bcad3898396af9673ba5b2f722092f0d2a9388e960ccde7272df5e2fe0ea9e499a909b655a59c85cfa1c622c651c8af20b4fb8bab9ab78d951c621d4b75c812246b2e925bcde42cc6a0a13467b4bcfb9aea5e4949effc71769dccc619eafc6d229cba478e3ad7289dc14b0c4842b4cf0cadd30deb9375fc1659d084779819705a6da7bccbf8d21ecd82391de5b61126d5b872f7d95514717b6fdc218dc0a048364c46142b114ee10d582740668f5b105edc034eb794c7e3906c77a44677e67709dbb1d3078783b488473e83e457e6ab98d2d659cf50066bc7f01190e065a9ef955e0257535bd5fab8ad007673637b2d005349e7f19fea2eeea82597867d5e366e41993775e4f4f70869fb1f9989d6d9902787f8233e9c7e586fe6bcf799ecf2da02ce08232ef1315b4e8857bcdb58bda53991f529d2ff023d0279552396dd0bb0fceaaf5dfb9eda0160bb09dd92b8085bc92c6006c20409cf9a5079072a09df221a76efc5ec13c97d154d22e382018ed8eb767f77aae578121c2231fe964338e637e7c060d555a2574b49c08956c729e79090b917e162488b1c9e962a3a921ac6f98a8c020c48aa2812f2f7a205a2d23aa2be1a953d9e33fbdea94688cf3d44200ed2cb009be8b684e99a96f0bc59eff5490eee0636b8b5665d7ddbb6ad44b90caa62b524f8a1caf6d0dbbc5e2ef0c2e65976d94e80e8dbd5ab8a420fdb638562bd2181c0ca243496582bab2847394e1e2dd4a24d4b24794b770b2475916746fb2bdc50f7994b4b346bfcfc5b4a99266cdf551340903d6994206ae1edb968c15d89f2a4cc6f3cb27b88989489b598f76fb6d1afa52e3a4c73175a216fa30d76acfccade7adb5628a88931b37bcff93c615a78a0b47827e385395e0b53c683f2ff07dd6cc636a086c295f06766570fc7652568676ecc5869378bdc0a63753807f1c7de7e5525d48328fa4103ed2ce9abafe0dc861055be6943cf2a87371ec1f9205c1955ddcf2f2ca982d877040dc92bf64278273c5ebbe3de0ef9d5eae255359e7ac97123b92488ffd0f1ea7deca36110135e02988be06bba4a3bf1b0da067976a6bc0c166ac349b2a853eb204fec6c142cad3decb05da15448f0d82d5faed3bc4beb400c51e05de06d950c128e2d3323a2d47dbf88684970084ed6608b95d7d585c3762c714c063c0a4ce1cacd5b31f261376bd972982957150dbbeb158999c1f60a76c6233a8749c10c016e0ad69bdac19e8c4d28126b7cc79c79aa82c25cef5521afdd759ca198b77c1a4a5f2c0497a4136e9818113c612d109de2cfaba691e05b791474599bf5cb918097f07b95dde658d2c5c01bf2bb6715dcb40c4c5686ec1642f9fd84377a90ea2456561ff91ba798d98211975c3da57be1b1e57a4660f979407e5f8616c4f62730161d2dcd86cf5383665c64cb77abbcf2e1406bc189e9575e3c1407aa6a467e6bd7a8edf7affde32b88dfa178902163a37c6b6c6bacb777a0bfbf46a0324c0ae5de7c2bdb6aad6ce51c0f5b4a5ab7c139d6bcdacc8ea46e37e040b785dbfc3145e408593c6f143dc1b4fde763e32e6d60c32d1a5c6d0bdf2d7d97f2bdeeba4a439abe7c75daced72a7678af1412f6c2917e39d6419c103f3a32e964369136a1183feb8d484712bcde8b14e2e8a7374dfb0dd7ee07dd15727b340005ed98bf5850b9de92b1912639e15f91d16968cd8bc336afc132ec6c93deba843e636de52f32be6e3c1e0ea50fdf03206c8dfa74f4c600e7d4d133c2ccc61ac50ae2f54e4f1ad02dc7ec86d8732cf12f0ac2c2ee10de6829695e539a6f76f9d9a4cda9d2ed1377c7a203baff1b",created_at:"2026-05-03T08:06:17.512936+00:00",retired_at:null,receipt_context_since:"2026-10-19T09:50:04.571Z"}],pack_envelope_signers:[{kid:"pack-signer-2026-04-29",ed25519_pubkey_hex:"853a62cb452a35fd6499d8fedb97448e0e24ef0d071343b2c9652aa2831bbdf6",status:"active",created_at:"2026-04-29T18:20:16.11538+00:00"}]};var xn=[...bn.chain_keys.filter(n=>!n.retired_at).map(n=>n.ed25519_pubkey_hex.toLowerCase()),...bn.pack_envelope_signers.map(n=>n.ed25519_pubkey_hex.toLowerCase())];function Ur(n){return Ge(Ne(_e(n))).slice(0,16)}var Dr="connect-command",ze=/^[0-9a-f]{16}$/,Os=/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){1,3}$/,Bt=class extends F{constructor(t,r,s,o){super(o,428,"approval_required");this.approveUrl=t;this.approvalId=r;this.orgApprovalId=s;this.name="FabricApprovalRequired"}};function mn(){return Ge(vr())}var Ke=class{constructor(e){this.http=e}newSecret(){return mn()}async open(e={}){let t=(e.secret??mn()).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(t))throw new Error("nd.fabric: secret must be 64 hex characters (nd.fabric.newSecret())");let r=Ge(pn(_e(t))),s=await this.http.raw("POST",`/api/v1/relay/enroll${e.replace?"?replace=true":""}`,{ecdh_pubkey_hex:r});if(!s.ok)throw J("enroll",s);let o=String(s.data.ecdh_kid??"");if(!ze.test(o))throw new F("enroll answered without an address",s.status);if(o!==Ur(r))throw new F("enroll answered an address that is not this key's",s.status,"address_mismatch");return new Tt(this.http,t,o,(e.trustedReceiptKeys??xn).map(i=>i.toLowerCase()))}},Tt=class{constructor(e,t,r,s=xn){this.http=e;this.secret=t;this.address=r;this.trustedReceiptKeys=s}async invite(e={}){let t=await this.http.raw("POST","/api/v1/fabric-grants",{action:"invite",my_kid:this.address,template:"ping",...e.note?{note:e.note}:{},...e.days?{grant_days:e.days}:{},...Hr(e)});if(!t.ok)throw J("invite",t);return{url:String(t.data.invite_url??""),expiresAt:typeof t.data.expires_at=="string"?t.data.expires_at:null,grantDays:typeof t.data.grant_days=="number"?t.data.grant_days:null}}async accept(e,t={}){let r=e.match(/invite=([^&\s]+)/),s=decodeURIComponent(r?r[1]:e.trim());if(!s.includes("."))throw new Error("nd.fabric.accept: give the invitation link or its token");let o=await this.http.raw("POST","/api/v1/fabric-grants",{action:"accept",token:s,subject_kid:this.address,mutual:t.oneWay!==!0,...t.termsAccepted?{terms_accepted:!0}:{},...Hr(t)});if(!o.ok)throw J("accept",o);let i=o.data.partner??{};if(!i.sender_kid||!ze.test(i.sender_kid))throw new F("connected, but the invitation named no address of theirs to send to (they invited without one)",o.status,"no_partner_address");return{kid:i.sender_kid,name:i.name??null}}async partners(){let e=await this.http.raw("GET","/api/v1/fabric-grants");if(!e.ok)throw J("partners",e);return Is(e.data)}async send(e,t,r={},s={}){if(!Os.test(t))throw new Error(`nd.fabric.send: '${t}' is not a command name (e.g. order.create)`);let o=await this.addressOf(e),i=Ir(t,r,s.replyTo??null),a=hn(i);if(!a.ok)throw new Error(`nd.fabric.send: not a command (${a.reason})`);let u=gn(i),c=await this.http.raw("GET",`/api/v1/relay/resolve?handle=${encodeURIComponent(o)}`);if(!c.ok)throw J("resolve",c);let l=String(c.data.recipient_pubkey??"");if(!/^[0-9a-f]{64}$/.test(l))throw new F(`${o} has no public key to seal to`,c.status,"no_public_key");if(Ur(l)!==o)throw new F(`the key the directory gave for ${o} is not that address's key; nothing was sent`,c.status,"key_mismatch");let d=await Cr(l,new TextEncoder().encode(u)),h=await this.http.raw("POST","/api/v1/relay/send",{recipient_kid:o,...d,route_taken:"capsule",content_type_hint:Tr,purpose:Dr,ttl_hours:Math.min(Math.max(s.ttlHours??24,1),720),max_fetches:Math.min(Math.max(s.opens??1,1),20),released_sha256:Lr(u)});if(!h.ok)throw J("send",h);return{id:String(h.data.id??""),commandId:i.id,to:o}}reply(e,t,r={}){if(!e.commandId)throw new Error("nd.fabric.reply: this message was not an opened command");return this.send(e.from,t,r,{replyTo:e.commandId})}async inbox(e={}){let t=await this.http.raw("GET","/api/v1/relay/inbox");if(!t.ok)throw J("inbox",t);let r=(t.data.items??[]).filter(i=>i.purpose===Dr),s=e.accept?new Set(e.accept):null,o=[];for(let i of r){let a={relayId:i.id,from:i.sender_kid,fromOrg:i.sender?.org??null},u=await this.http.raw("GET",`/api/v1/relay/fetch/${encodeURIComponent(i.id)}`);if(!u.ok){o.push({...a,status:"unopened",reason:String(u.data.refused??u.data.error??u.status),verified:{committed:null,receiptSignature:null}});continue}let c=Ds(u.data.receipt,this.trustedReceiptKeys),l=null;try{let p=await Br(this.secret,u.data),w=hn(JSON.parse(new TextDecoder().decode(p)));l=w.ok?w.envelope:null}catch{l=null}if(!l){o.push({...a,status:"refused",reason:"not_a_command",verified:{committed:null,receiptSignature:c}});continue}let h={committed:typeof u.data.released_sha256=="string"?Lr(gn(l))===u.data.released_sha256:null,receiptSignature:c};if(s&&!s.has(l.cmd)){o.push({...a,status:"refused",reason:`not_accepted:${l.cmd}`,cmd:l.cmd,commandId:l.id,verified:h});continue}o.push({...a,status:"accepted",cmd:l.cmd,fields:l.fields,replyTo:l.reply_to,commandId:l.id,issuedAt:l.issued_at,verified:h})}return o}async disconnect(e){let t=await this.addressOf(e),r=await this.http.raw("GET","/api/v1/fabric-grants");if(!r.ok)throw J("partners",r);let s=(r.data.grants??[]).filter(a=>!a.revoked_at&&a.subject_kid===t),o=(r.data.inbound??[]).filter(a=>a.subject_kid===this.address&&(a.allowed_sender_kids??[]).includes(t)),i=0;for(let a of s){let u=await this.http.raw("PATCH","/api/v1/fabric-grants",{grant_id:a.id,reason:"disconnected from the SDK"});if(!u.ok)throw J("disconnect",u);i++}for(let a of o){let u=await this.http.raw("POST","/api/v1/fabric-grants",{action:"leave",grant_id:a.id});if(!u.ok)throw J("disconnect",u);i++}return{ended:i}}async addressOf(e){if(typeof e!="string")return e.kid;let t=e.trim().toLowerCase();if(ze.test(t))return t;let r=(await this.partners()).filter(s=>(s.name??"").toLowerCase()===t);if(r.length===1)return r[0].kid;throw new Error(r.length?`nd.fabric: '${e}' names ${r.length} connections; use the address`:`nd.fabric: no connection named '${e}'`)}};function Is(n){let e=new Map;for(let t of n.grants??[])!t.revoked_at&&ze.test(t.subject_kid)&&e.set(t.subject_kid,{kid:t.subject_kid,name:t.partner_name??null});for(let t of n.inbound??[])for(let r of t.allowed_sender_kids??[]){if(!ze.test(r))continue;let s=e.get(r);e.set(r,{kid:r,name:s?.name??t.partner_name??null})}return[...e.values()]}function Lr(n){return Ge(Ne(new TextEncoder().encode(n)))}function yn(n){if(n===null||typeof n!="object")return JSON.stringify(n);if(Array.isArray(n))return"["+n.map(yn).join(",")+"]";let e=n;return"{"+Object.keys(e).sort().map(t=>JSON.stringify(t)+":"+yn(e[t])).join(",")+"}"}function Ds(n,e=xn){let t=n;if(!t?.payload||!t.signature_hex||!t.signing_pubkey_hex)return null;if(!e.includes(t.signing_pubkey_hex.toLowerCase()))return!1;try{return yr.verify(_e(t.signature_hex),new TextEncoder().encode(yn(t.payload)),_e(t.signing_pubkey_hex))}catch{return!1}}function Hr(n){return n.orgApprovalId?{org_approval_id:n.orgApprovalId}:n.approvalId?{approval_id:n.approvalId}:{}}function J(n,e){let t=e.data;if(e.status===428){let s=typeof t.approval=="object"&&t.approval!==null?t.approval:{},o=typeof t.lock=="object"&&t.lock!==null?t.lock:{};return new Bt((s.approve_url??(typeof t.approve_url=="string"?t.approve_url:null))||null,s.approval_id??null,o.lock_id??null,`${n}: waiting for a person's approval${t.why?` (${String(t.why)})`:""}. Approve it in the browser, then call again with the approval id.`)}let r=String(t.refused??t.error??`HTTP ${e.status}`);return new F(`${n} refused: ${r}${t.reason?` (${String(t.reason)})`:t.why?` (${String(t.why)})`:""}`,e.status,String(t.refused??t.error??""))}var Pr=class{http;_encrypt;capsules;tenants;scan;fabric;engines;_compute;constructor(e){this.http=new Qe(e),this._compute=new He(this.http),this._encrypt=new Re(this.http),this.capsules=new Oe(this.http),this.tenants=new Ie(this.http),this.scan=new De(this.http),this.fabric=new Ke(this.http),this.engines=new Le(this.http)}compute(e){return this._compute.run(e)}verify(e){return this._compute.verify(e)}authorize(e){return this.http.post("/api/v1/authorize",e)}get channel(){return this.engines.channel}get webhook(){return this.engines.webhook}get deliver(){return this.engines.deliver}get evidence(){return this.engines.evidence}get vault(){return this.engines.vault}get governance(){return this.engines.governance}agent(e){return new Be(this.http.baseURL,e)}encrypt(e){return this._encrypt.encrypt(e)}decrypt(e){return this._encrypt.decrypt(e)}batchEncrypt(e,t){return this._encrypt.batchEncrypt(e,t)}batchDecrypt(e,t){return this._encrypt.batchDecrypt(e,t)}batchNative(e,t){return this._encrypt.batchNative(e,t)}encryptObject(e,t,r){return this._encrypt.encryptObject(e,t,r)}decryptObject(e,t,r){return this._encrypt.decryptObject(e,t,r)}async ping(){let e=Date.now();return await this.http.get("/api/health"),{success:!0,latencyMs:Date.now()-e}}};export{F as a,Ce as b,Be as c,Je as d,et as e,tt as f,nt as g,Te as h,Oe as i,Ie as j,De as k,Le as l,He as m,Bt as n,mn as o,Ke as p,Tt as q,Pr as r};
2
- /*! Bundled license information:
3
-
4
- @noble/curves/utils.js:
5
- @noble/curves/abstract/modular.js:
6
- @noble/curves/abstract/curve.js:
7
- @noble/curves/abstract/edwards.js:
8
- @noble/curves/abstract/montgomery.js:
9
- @noble/curves/ed25519.js:
10
- (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
11
- */