@catena/cli 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-B0Z9INg1.mjs";import{D as a,E as o,O as s}from"./dist-w03V0QPF.mjs";import{defineCommand as c,renderUsage as l,runMain as u}from"citty";import*as d from"valibot";import{ECDH as f,createECDH as p,createHash as m,createPrivateKey as h,randomBytes as g,sign as _}from"node:crypto";import{execFile as v,spawn as y}from"node:child_process";import{accessSync as b,chmodSync as x,constants as S,existsSync as C,mkdirSync as w,readFileSync as T,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as ee}from"node:os";import{dirname as j,isAbsolute as M,join as te,resolve as ne}from"node:path";import{createServer as re}from"node:http";import{constants as N,isUtf8 as ie}from"node:buffer";import ae from"semver";var P=`@catena/cli`,oe=`0.11.0`;function se(e){return e instanceof Error?e.message:String(e)}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function le(e){if(!ce(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var ue=class{container;constructor(e){this.container=e}};function de(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&n.enumerable===!0&&`value`in n}function fe(e){if(Object.getOwnPropertySymbols(e).length>0)return null;let t=Object.getOwnPropertyNames(e);for(let n of t)if(!de(e,n))return null;return t}function pe(e){if(Object.getPrototypeOf(e)!==Array.prototype||Object.getOwnPropertySymbols(e).length>0)return!1;let t=Object.getOwnPropertyNames(e);if(t.length!==e.length+1)return!1;for(let n=0;n<e.length;n++)if(t[n]!==String(n)||!de(e,t[n]))return!1;return!0}function me(e){let t=new Set,n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(e instanceof ue){t.delete(e.container),n.add(e.container);continue}if(e===null||typeof e==`string`||typeof e==`boolean`)continue;if(typeof e==`number`){if(!Number.isFinite(e))return!1;continue}if(Array.isArray(e)){if(t.has(e))return!1;if(n.has(e))continue;if(!pe(e))return!1;t.add(e),r.push(new ue(e));for(let t of e)r.push(t);continue}if(!le(e)||Object.hasOwn(e,`__proto__`)||t.has(e))return!1;if(n.has(e))continue;let i=fe(e);if(i===null)return!1;t.add(e),r.push(new ue(e));for(let t of i)r.push(e[t])}return!0}function he(e){return t=>{try{return e(t)}catch{return!1}}}d.custom(he(me),`Expected a JSON value`),d.custom(he(e=>le(e)&&me(e)),`Expected a JSON object`),d.custom(he(e=>Array.isArray(e)&&me(e)),`Expected a JSON array`);function F(e){return _e(I(e))}function ge(e,t){let n=e.padStart(Math.ceil(e.length/2)*2,`0`);return F(a(n,t).reduce((e,t)=>e+String.fromCharCode(t),``))}function _e(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function I(e){if(arguments.length===0)throw TypeError(`1 argument required, but only 0 present.`);let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)throw Error(`InvalidCharacterError: found code point greater than 255:${e.charCodeAt(t)} at position ${t}`);let n=``;for(t=0;t<e.length;t+=3){let r=[void 0,void 0,void 0,void 0];r[0]=e.charCodeAt(t)>>2,r[1]=(e.charCodeAt(t)&3)<<4,e.length>t+1&&(r[1]|=e.charCodeAt(t+1)>>4,r[2]=(e.charCodeAt(t+1)&15)<<2),e.length>t+2&&(r[2]|=e.charCodeAt(t+2)>>6,r[3]=e.charCodeAt(t+2)&63);for(let e=0;e<r.length;e++)r[e]===void 0?n+=`=`:n+=ve(r[e])}return n}function ve(e){if(e>=0&&e<64)return`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`[e]}var L=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],ye=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(this.buffer_size*2,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var n=t.substring(1),r=parseInt(n)/8;this.resize_if_necessary(r);var i=t[0]===`f`?`setFloat${n}`:t[0]===`i`?`setInt${n}`:`setUint${n}`;this.view[i](this.offset,e,!0),this.offset+=r},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),be=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error(`Error in schema, the buffer is smaller than expected`)},e.prototype.consume_value=function(e){var t=e.substring(1),n=parseInt(t)/8;this.assert_enough_buffer(n);var r=e[0]===`f`?`getFloat${t}`:e[0]===`i`?`getInt${t}`:`getUint${t}`,i=this.view[r](this.offset,!0);return this.offset+=n,i},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),xe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();function Se(e){return Array.isArray(e)||!!e&&typeof e==`object`&&`length`in e&&typeof e.length==`number`&&(e.length===0||e.length>0&&e.length-1 in e)}function R(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function z(e,t){var n=[`number`,`string`,`bigint`,`boolean`].includes(typeof e),r=typeof e==`object`&&!!e&&`toString`in e;if(!n&&!r)throw Error(`Expected bigint, number, boolean or string not ${typeof e}(${e}) at ${t.join(`.`)}`)}function Ce(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function we(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}L.concat([`bool`,`string`]),function(e){xe(t,e);function t(t,n){var r=`Invalid schema: ${JSON.stringify(t)} expected ${n}`;return e.call(this,r)||this}return t}(Error),function(){function e(e){this.encoded=new ye,this.fieldPath=[`value`],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if(typeof t==`string`){if(L.includes(t))return this.encode_integer(e,t);if(t===`string`)return this.encode_string(e);if(t===`bool`)return this.encode_boolean(e)}if(typeof t==`object`){if(`option`in t)return this.encode_option(e,t);if(`enum`in t)return this.encode_enum(e,t);if(`array`in t)return this.encode_array(e,t);if(`set`in t)return this.encode_set(e,t);if(`map`in t)return this.encode_map(e,t);if(`struct`in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var n=parseInt(t.substring(1));n<=32||t==`f64`?(this.checkTypes&&R(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&z(e,this.fieldPath),this.encode_bigint(BigInt(e),n))},e.prototype.encode_bigint=function(e,t){for(var n=t/8,r=new Uint8Array(n),i=0;i<n;i++)r[i]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(r))},e.prototype.encode_string=function(e){this.checkTypes&&R(e,`string`,this.fieldPath);for(var t=e,n=[],r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):i<55296||i>=57344?n.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|t.charCodeAt(r)&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}this.encoded.store_value(n.length,`u32`),this.encoded.store_bytes(new Uint8Array(n))},e.prototype.encode_boolean=function(e){this.checkTypes&&R(e,`boolean`,this.fieldPath),this.encoded.store_value(+!!e,`u8`)},e.prototype.encode_option=function(e,t){e==null?this.encoded.store_value(0,`u8`):(this.encoded.store_value(1,`u8`),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&we(e,this.fieldPath);for(var n=Object.keys(e)[0],r=0;r<t.enum.length;r++){var i=t.enum[r];if(n===Object.keys(i.struct)[0])return this.encoded.store_value(r,`u8`),this.encode_struct(e,i)}throw Error(`Enum key (${n}) not found in enum schema: ${JSON.stringify(t)} at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_array=function(e,t){if(Se(e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error(`Expected Array-like not ${typeof e}(${e}) at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_arraylike=function(e,t){t.array.len?Ce(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,`u32`);for(var n=0;n<e.length;n++)this.encode_value(e[n],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?Ce(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,`u32`),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&R(e,`object`,this.fieldPath);var n=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(n.length,`u32`);for(var r=0,i=n;r<i.length;r++){var a=i[r];this.encode_value(a,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&R(e,`object`,this.fieldPath);var n=e instanceof Map,r=n?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(r.length,`u32`);for(var i=0,a=r;i<a.length;i++){var o=a[i];this.encode_value(o,t.map.key),this.encode_value(n?e.get(o):e[o],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&R(e,`object`,this.fieldPath);for(var n=0,r=Object.keys(t.struct);n<r.length;n++){var i=r[n];this.fieldPath.push(i),this.encode_value(e[i],t.struct[i]),this.fieldPath.pop()}},e}(),function(){function e(e){this.buffer=new be(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(L.includes(e))return this.decode_integer(e);if(e===`string`)return this.decode_string();if(e===`bool`)return this.decode_boolean()}if(typeof e==`object`){if(`option`in e)return this.decode_option(e);if(`enum`in e)return this.decode_enum(e);if(`array`in e)return this.decode_array(e);if(`set`in e)return this.decode_set(e);if(`map`in e)return this.decode_map(e);if(`struct`in e)return this.decode_struct(e)}throw Error(`Unsupported type: ${e}`)},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||e==`f64`?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith(`i`))},e.prototype.decode_bigint=function(e,t){t===void 0&&(t=!1);var n=e/8,r=new Uint8Array(this.buffer.consume_bytes(n)),i=r.reduceRight(function(e,t){return e+t.toString(16).padStart(2,`0`)},``);return t&&r[n-1]?BigInt.asIntN(e,BigInt(`0x${i}`)):BigInt(`0x${i}`)},e.prototype.decode_string=function(){for(var e=this.decode_integer(`u32`),t=new Uint8Array(this.buffer.consume_bytes(e)),n=[],r=0;r<e;++r){var i=t[r];if(i<128)n.push(i);else if(i<224)n.push((i&31)<<6|t[++r]&63);else if(i<240)n.push((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);else{var a=(i&7)<<18|(t[++r]&63)<<12|(t[++r]&63)<<6|t[++r]&63;n.push(a)}}return String.fromCodePoint.apply(String,n)},e.prototype.decode_boolean=function(){return this.buffer.consume_value(`u8`)>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value(`u8`);if(t===1)return this.decode_value(e.option);if(t!==0)throw Error(`Invalid option ${t}`);return null},e.prototype.decode_enum=function(e){var t,n=this.buffer.consume_value(`u8`);if(n>e.enum.length)throw Error(`Enum option ${n} is not available`);var r=e.enum[n].struct,i=Object.keys(r)[0];return t={},t[i]=this.decode_value(r[i]),t},e.prototype.decode_array=function(e){for(var t=[],n=e.array.len?e.array.len:this.decode_integer(`u32`),r=0;r<n;++r)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer(`u32`),n=new Set,r=0;r<t;++r)n.add(this.decode_value(e.set));return n},e.prototype.decode_map=function(e){for(var t=this.decode_integer(`u32`),n=new Map,r=0;r<t;++r){var i=this.decode_value(e.map.key),a=this.decode_value(e.map.value);n.set(i,a)}return n},e.prototype.decode_struct=function(e){var t={};for(var n in e.struct)t[n]=this.decode_value(e.struct[n]);return t},e}(),new Uint8Array([75,69,77,0,16]),new Uint8Array([72,80,75,69,0,16,0,1,0,2]),new Uint8Array([72,80,75,69,45,118,49]),new Uint8Array([115,101,99,114,101,116]),new Uint8Array([101,97,101,95,112,114,107]),new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),new Uint8Array([0,32,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,107,101,121,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([0,12,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,98,97,115,101,95,110,111,110,99,101,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([113,111,115,95,101,110,99,114,121,112,116,105,111,110,95,104,109,97,99,95,109,101,115,115,97,103,101]);const Te=e=>{let t=a(e);if(t.length<2)throw Error(`failed to convert DER-encoded signature: insufficient length`);if(t[0]!==48)throw Error(`failed to convert DER-encoded signature: invalid format (missing SEQUENCE tag)`);let n=1,r=t[n];if(r<=127){if(t.length<2+r)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);n+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);n++;let i=t[n];if(i>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);n++;let s=t.slice(n,n+i);if(n+=i,t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);n++;let c=t[n];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);n++;let l=t.slice(n,n+c),u=o(s,32),d=o(l,32);return new Uint8Array([...u,...d])};var Ee;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(Ee||={});var De=i(((e,t)=>{(function(e,n){var r=2**-24,i=2**32,a=2**53;function o(e){var t=new ArrayBuffer(256),r=new DataView(t),o,s=0;function c(e){for(var n=t.byteLength,i=s+e;n<i;)n*=2;if(n!==t.byteLength){var a=r;t=new ArrayBuffer(n),r=new DataView(t);for(var c=s+3>>2,l=0;l<c;++l)r.setUint32(l*4,a.getUint32(l*4))}return o=e,r}function l(){s+=o}function u(e){l(c(8).setFloat64(s,e))}function d(e){l(c(1).setUint8(s,e))}function f(e){for(var t=c(e.length),n=0;n<e.length;++n)t.setUint8(s+n,e[n]);l()}function p(e){l(c(2).setUint16(s,e))}function m(e){l(c(4).setUint32(s,e))}function h(e){var t=e%i,n=(e-t)/i,r=c(8);r.setUint32(s,n),r.setUint32(s+4,t),l()}function g(e,t){t<24?d(e<<5|t):t<256?(d(e<<5|24),d(t)):t<65536?(d(e<<5|25),p(t)):t<4294967296?(d(e<<5|26),m(t)):(d(e<<5|27),h(t))}function _(e){var t;if(e===!1)return d(244);if(e===!0)return d(245);if(e===null)return d(246);if(e===n)return d(247);switch(typeof e){case`number`:if(Math.floor(e)===e){if(0<=e&&e<=a)return g(0,e);if(-a<=e&&e<0)return g(1,-(e+1))}return d(251),u(e);case`string`:var r=[];for(t=0;t<e.length;++t){var i=e.charCodeAt(t);i<128?r.push(i):i<2048?(r.push(192|i>>6),r.push(128|i&63)):i<55296?(r.push(224|i>>12),r.push(128|i>>6&63),r.push(128|i&63)):(i=(i&1023)<<10,i|=e.charCodeAt(++t)&1023,i+=65536,r.push(240|i>>18),r.push(128|i>>12&63),r.push(128|i>>6&63),r.push(128|i&63))}return g(3,r.length),f(r);default:var o;if(Array.isArray(e))for(o=e.length,g(4,o),t=0;t<o;++t)_(e[t]);else if(e instanceof Uint8Array)g(2,e.length),f(e);else{var s=Object.keys(e);for(o=s.length,g(5,o),t=0;t<o;++t){var c=s[t];_(c),_(e[c])}}}}if(_(e),`slice`in t)return t.slice(0,s);for(var v=new ArrayBuffer(s),y=new DataView(v),b=0;b<s;++b)y.setUint8(b,r.getUint8(b));return v}function s(e,t,a){var o=new DataView(e),s=0;typeof t!=`function`&&(t=function(e){return e}),typeof a!=`function`&&(a=function(){return n});function c(e,t){return s+=t,e}function l(t){return c(new Uint8Array(e,s,t),t)}function u(){var e=new DataView(new ArrayBuffer(4)),t=m(),n=t&32768,i=t&31744,a=t&1023;if(i===31744)i=261120;else if(i!==0)i+=114688;else if(a!==0)return a*r;return e.setUint32(0,n<<16|i<<13|a<<13),e.getFloat32(0)}function d(){return c(o.getFloat32(s),4)}function f(){return c(o.getFloat64(s),8)}function p(){return c(o.getUint8(s),1)}function m(){return c(o.getUint16(s),2)}function h(){return c(o.getUint32(s),4)}function g(){return h()*i+h()}function _(){return o.getUint8(s)===255&&(s+=1,!0)}function v(e){if(e<24)return e;if(e===24)return p();if(e===25)return m();if(e===26)return h();if(e===27)return g();if(e===31)return-1;throw`Invalid length encoding`}function y(e){var t=p();if(t===255)return-1;var n=v(t&31);if(n<0||t>>5!==e)throw`Invalid indefinite length element`;return n}function b(e,t){for(var n=0;n<t;++n){var r=p();r&128&&(r<224?(r=(r&31)<<6|p()&63,--t):r<240?(r=(r&15)<<12|(p()&63)<<6|p()&63,t-=2):(r=(r&15)<<18|(p()&63)<<12|(p()&63)<<6|p()&63,t-=3)),r<65536?e.push(r):(r-=65536,e.push(55296|r>>10),e.push(56320|r&1023))}}function x(){var e=p(),r=e>>5,i=e&31,o,s;if(r===7)switch(i){case 25:return u();case 26:return d();case 27:return f()}if(s=v(i),s<0&&(r<2||6<r))throw`Invalid length`;switch(r){case 0:return s;case 1:return-1-s;case 2:if(s<0){for(var c=[],m=0;(s=y(r))>=0;)m+=s,c.push(l(s));var h=new Uint8Array(m),g=0;for(o=0;o<c.length;++o)h.set(c[o],g),g+=c[o].length;return h}return l(s);case 3:var S=[];if(s<0)for(;(s=y(r))>=0;)b(S,s);else b(S,s);return String.fromCharCode.apply(null,S);case 4:var C;if(s<0)for(C=[];!_();)C.push(x());else for(C=Array(s),o=0;o<s;++o)C[o]=x();return C;case 5:var w={};for(o=0;o<s||s<0&&!_();++o){var T=x();w[T]=x()}return w;case 6:return t(x(),s);case 7:switch(s){case 20:return!1;case 21:return!0;case 22:return null;case 23:return n;default:return a(s)}}}var S=x();if(s!==e.byteLength)throw`Remaining bytes`;return S}var c={encode:o,decode:s};typeof define==`function`&&define.amd?define(`cbor/cbor`,c):t!==void 0&&t.exports?t.exports=c:e.CBOR||=c})(e)})),Oe=i((()=>{
2
+ import{a as e,i as t,n,r,t as i}from"./rolldown-runtime-B0Z9INg1.mjs";import{n as a,r as o,t as s}from"./dist-C970_f6m.mjs";import{defineCommand as c,renderUsage as l,runMain as u}from"citty";import*as d from"valibot";import{ECDH as f,createECDH as p,createHash as m,createPrivateKey as h,randomBytes as g,sign as _}from"node:crypto";import{execFile as v,spawn as y}from"node:child_process";import{accessSync as b,chmodSync as x,constants as S,existsSync as C,mkdirSync as w,readFileSync as T,realpathSync as E,renameSync as D,rmSync as O,statSync as k,writeFileSync as A}from"node:fs";import{homedir as ee}from"node:os";import{dirname as j,isAbsolute as M,join as te,resolve as ne}from"node:path";import{createServer as re}from"node:http";import{constants as N,isUtf8 as ie}from"node:buffer";import ae from"semver";var P=`@catena/cli`,oe=`0.12.0`;function se(e){return e instanceof Error?e.message:String(e)}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function le(e){if(!ce(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var F=class{container;constructor(e){this.container=e}};function ue(e,t){let n=Object.getOwnPropertyDescriptor(e,t);return n!==void 0&&n.enumerable===!0&&`value`in n}function de(e){if(Object.getOwnPropertySymbols(e).length>0)return null;let t=Object.getOwnPropertyNames(e);for(let n of t)if(!ue(e,n))return null;return t}function fe(e){if(Object.getPrototypeOf(e)!==Array.prototype||Object.getOwnPropertySymbols(e).length>0)return!1;let t=Object.getOwnPropertyNames(e);if(t.length!==e.length+1)return!1;for(let n=0;n<e.length;n++)if(t[n]!==String(n)||!ue(e,t[n]))return!1;return!0}function pe(e){let t=new Set,n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(e instanceof F){t.delete(e.container),n.add(e.container);continue}if(e===null||typeof e==`string`||typeof e==`boolean`)continue;if(typeof e==`number`){if(!Number.isFinite(e))return!1;continue}if(Array.isArray(e)){if(t.has(e))return!1;if(n.has(e))continue;if(!fe(e))return!1;t.add(e),r.push(new F(e));for(let t of e)r.push(t);continue}if(!le(e)||Object.hasOwn(e,`__proto__`)||t.has(e))return!1;if(n.has(e))continue;let i=de(e);if(i===null)return!1;t.add(e),r.push(new F(e));for(let t of i)r.push(e[t])}return!0}function me(e){return t=>{try{return e(t)}catch{return!1}}}d.custom(me(pe),`Expected a JSON value`),d.custom(me(e=>le(e)&&pe(e)),`Expected a JSON object`),d.custom(me(e=>Array.isArray(e)&&pe(e)),`Expected a JSON array`);function I(e){return ge(L(e))}function he(e,t){let n=e.padStart(Math.ceil(e.length/2)*2,`0`);return I(a(n,t).reduce((e,t)=>e+String.fromCharCode(t),``))}function ge(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function L(e){if(arguments.length===0)throw TypeError(`1 argument required, but only 0 present.`);let t;for(e=`${e}`,t=0;t<e.length;t++)if(e.charCodeAt(t)>255)throw Error(`InvalidCharacterError: found code point greater than 255:${e.charCodeAt(t)} at position ${t}`);let n=``;for(t=0;t<e.length;t+=3){let r=[void 0,void 0,void 0,void 0];r[0]=e.charCodeAt(t)>>2,r[1]=(e.charCodeAt(t)&3)<<4,e.length>t+1&&(r[1]|=e.charCodeAt(t+1)>>4,r[2]=(e.charCodeAt(t+1)&15)<<2),e.length>t+2&&(r[2]|=e.charCodeAt(t+2)>>6,r[3]=e.charCodeAt(t+2)&63);for(let e=0;e<r.length;e++)r[e]===void 0?n+=`=`:n+=_e(r[e])}return n}function _e(e){if(e>=0&&e<64)return`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`[e]}var R=[`u8`,`u16`,`u32`,`u64`,`u128`,`i8`,`i16`,`i32`,`i64`,`i128`,`f32`,`f64`],ve=function(){function e(){this.offset=0,this.buffer_size=256,this.buffer=new ArrayBuffer(this.buffer_size),this.view=new DataView(this.buffer)}return e.prototype.resize_if_necessary=function(e){if(this.buffer_size-this.offset<e){this.buffer_size=Math.max(this.buffer_size*2,this.buffer_size+e);var t=new ArrayBuffer(this.buffer_size);new Uint8Array(t).set(new Uint8Array(this.buffer)),this.buffer=t,this.view=new DataView(t)}},e.prototype.get_used_buffer=function(){return new Uint8Array(this.buffer).slice(0,this.offset)},e.prototype.store_value=function(e,t){var n=t.substring(1),r=parseInt(n)/8;this.resize_if_necessary(r);var i=t[0]===`f`?`setFloat${n}`:t[0]===`i`?`setInt${n}`:`setUint${n}`;this.view[i](this.offset,e,!0),this.offset+=r},e.prototype.store_bytes=function(e){this.resize_if_necessary(e.length),new Uint8Array(this.buffer).set(new Uint8Array(e),this.offset),this.offset+=e.length},e}(),ye=function(){function e(e){this.offset=0,this.buffer_size=e.length,this.buffer=new ArrayBuffer(e.length),new Uint8Array(this.buffer).set(e),this.view=new DataView(this.buffer)}return e.prototype.assert_enough_buffer=function(e){if(this.offset+e>this.buffer.byteLength)throw Error(`Error in schema, the buffer is smaller than expected`)},e.prototype.consume_value=function(e){var t=e.substring(1),n=parseInt(t)/8;this.assert_enough_buffer(n);var r=e[0]===`f`?`getFloat${t}`:e[0]===`i`?`getInt${t}`:`getUint${t}`,i=this.view[r](this.offset,!0);return this.offset+=n,i},e.prototype.consume_bytes=function(e){this.assert_enough_buffer(e);var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t},e}(),be=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};return function(t,n){if(typeof n!=`function`&&n!==null)throw TypeError(`Class extends value `+String(n)+` is not a constructor or null`);e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();function xe(e){return Array.isArray(e)||!!e&&typeof e==`object`&&`length`in e&&typeof e.length==`number`&&(e.length===0||e.length>0&&e.length-1 in e)}function Se(e,t,n){if(typeof e!==t)throw Error(`Expected ${t} not ${typeof e}(${e}) at ${n.join(`.`)}`)}function z(e,t){var n=[`number`,`string`,`bigint`,`boolean`].includes(typeof e),r=typeof e==`object`&&!!e&&`toString`in e;if(!n&&!r)throw Error(`Expected bigint, number, boolean or string not ${typeof e}(${e}) at ${t.join(`.`)}`)}function Ce(e,t,n){if(e!==t)throw Error(`Array length ${e} does not match schema length ${t} at ${n.join(`.`)}`)}function we(e,t){if(typeof e!=`object`||!e)throw Error(`Expected object not ${typeof e}(${e}) at ${t.join(`.`)}`)}R.concat([`bool`,`string`]),function(e){be(t,e);function t(t,n){var r=`Invalid schema: ${JSON.stringify(t)} expected ${n}`;return e.call(this,r)||this}return t}(Error),function(){function e(e){this.encoded=new ve,this.fieldPath=[`value`],this.checkTypes=e}return e.prototype.encode=function(e,t){return this.encode_value(e,t),this.encoded.get_used_buffer()},e.prototype.encode_value=function(e,t){if(typeof t==`string`){if(R.includes(t))return this.encode_integer(e,t);if(t===`string`)return this.encode_string(e);if(t===`bool`)return this.encode_boolean(e)}if(typeof t==`object`){if(`option`in t)return this.encode_option(e,t);if(`enum`in t)return this.encode_enum(e,t);if(`array`in t)return this.encode_array(e,t);if(`set`in t)return this.encode_set(e,t);if(`map`in t)return this.encode_map(e,t);if(`struct`in t)return this.encode_struct(e,t)}},e.prototype.encode_integer=function(e,t){var n=parseInt(t.substring(1));n<=32||t==`f64`?(this.checkTypes&&Se(e,`number`,this.fieldPath),this.encoded.store_value(e,t)):(this.checkTypes&&z(e,this.fieldPath),this.encode_bigint(BigInt(e),n))},e.prototype.encode_bigint=function(e,t){for(var n=t/8,r=new Uint8Array(n),i=0;i<n;i++)r[i]=Number(e&BigInt(255)),e>>=BigInt(8);this.encoded.store_bytes(new Uint8Array(r))},e.prototype.encode_string=function(e){this.checkTypes&&Se(e,`string`,this.fieldPath);for(var t=e,n=[],r=0;r<t.length;r++){var i=t.charCodeAt(r);i<128?n.push(i):i<2048?n.push(192|i>>6,128|i&63):i<55296||i>=57344?n.push(224|i>>12,128|i>>6&63,128|i&63):(r++,i=65536+((i&1023)<<10|t.charCodeAt(r)&1023),n.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|i&63))}this.encoded.store_value(n.length,`u32`),this.encoded.store_bytes(new Uint8Array(n))},e.prototype.encode_boolean=function(e){this.checkTypes&&Se(e,`boolean`,this.fieldPath),this.encoded.store_value(+!!e,`u8`)},e.prototype.encode_option=function(e,t){e==null?this.encoded.store_value(0,`u8`):(this.encoded.store_value(1,`u8`),this.encode_value(e,t.option))},e.prototype.encode_enum=function(e,t){this.checkTypes&&we(e,this.fieldPath);for(var n=Object.keys(e)[0],r=0;r<t.enum.length;r++){var i=t.enum[r];if(n===Object.keys(i.struct)[0])return this.encoded.store_value(r,`u8`),this.encode_struct(e,i)}throw Error(`Enum key (${n}) not found in enum schema: ${JSON.stringify(t)} at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_array=function(e,t){if(xe(e))return this.encode_arraylike(e,t);if(e instanceof ArrayBuffer)return this.encode_buffer(e,t);throw Error(`Expected Array-like not ${typeof e}(${e}) at ${this.fieldPath.join(`.`)}`)},e.prototype.encode_arraylike=function(e,t){t.array.len?Ce(e.length,t.array.len,this.fieldPath):this.encoded.store_value(e.length,`u32`);for(var n=0;n<e.length;n++)this.encode_value(e[n],t.array.type)},e.prototype.encode_buffer=function(e,t){t.array.len?Ce(e.byteLength,t.array.len,this.fieldPath):this.encoded.store_value(e.byteLength,`u32`),this.encoded.store_bytes(new Uint8Array(e))},e.prototype.encode_set=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Set?Array.from(e.values()):Object.values(e);this.encoded.store_value(n.length,`u32`);for(var r=0,i=n;r<i.length;r++){var a=i[r];this.encode_value(a,t.set)}},e.prototype.encode_map=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);var n=e instanceof Map,r=n?Array.from(e.keys()):Object.keys(e);this.encoded.store_value(r.length,`u32`);for(var i=0,a=r;i<a.length;i++){var o=a[i];this.encode_value(o,t.map.key),this.encode_value(n?e.get(o):e[o],t.map.value)}},e.prototype.encode_struct=function(e,t){this.checkTypes&&Se(e,`object`,this.fieldPath);for(var n=0,r=Object.keys(t.struct);n<r.length;n++){var i=r[n];this.fieldPath.push(i),this.encode_value(e[i],t.struct[i]),this.fieldPath.pop()}},e}(),function(){function e(e){this.buffer=new ye(e)}return e.prototype.decode=function(e){return this.decode_value(e)},e.prototype.decode_value=function(e){if(typeof e==`string`){if(R.includes(e))return this.decode_integer(e);if(e===`string`)return this.decode_string();if(e===`bool`)return this.decode_boolean()}if(typeof e==`object`){if(`option`in e)return this.decode_option(e);if(`enum`in e)return this.decode_enum(e);if(`array`in e)return this.decode_array(e);if(`set`in e)return this.decode_set(e);if(`map`in e)return this.decode_map(e);if(`struct`in e)return this.decode_struct(e)}throw Error(`Unsupported type: ${e}`)},e.prototype.decode_integer=function(e){var t=parseInt(e.substring(1));return t<=32||e==`f64`?this.buffer.consume_value(e):this.decode_bigint(t,e.startsWith(`i`))},e.prototype.decode_bigint=function(e,t){t===void 0&&(t=!1);var n=e/8,r=new Uint8Array(this.buffer.consume_bytes(n)),i=r.reduceRight(function(e,t){return e+t.toString(16).padStart(2,`0`)},``);return t&&r[n-1]?BigInt.asIntN(e,BigInt(`0x${i}`)):BigInt(`0x${i}`)},e.prototype.decode_string=function(){for(var e=this.decode_integer(`u32`),t=new Uint8Array(this.buffer.consume_bytes(e)),n=[],r=0;r<e;++r){var i=t[r];if(i<128)n.push(i);else if(i<224)n.push((i&31)<<6|t[++r]&63);else if(i<240)n.push((i&15)<<12|(t[++r]&63)<<6|t[++r]&63);else{var a=(i&7)<<18|(t[++r]&63)<<12|(t[++r]&63)<<6|t[++r]&63;n.push(a)}}return String.fromCodePoint.apply(String,n)},e.prototype.decode_boolean=function(){return this.buffer.consume_value(`u8`)>0},e.prototype.decode_option=function(e){var t=this.buffer.consume_value(`u8`);if(t===1)return this.decode_value(e.option);if(t!==0)throw Error(`Invalid option ${t}`);return null},e.prototype.decode_enum=function(e){var t,n=this.buffer.consume_value(`u8`);if(n>e.enum.length)throw Error(`Enum option ${n} is not available`);var r=e.enum[n].struct,i=Object.keys(r)[0];return t={},t[i]=this.decode_value(r[i]),t},e.prototype.decode_array=function(e){for(var t=[],n=e.array.len?e.array.len:this.decode_integer(`u32`),r=0;r<n;++r)t.push(this.decode_value(e.array.type));return t},e.prototype.decode_set=function(e){for(var t=this.decode_integer(`u32`),n=new Set,r=0;r<t;++r)n.add(this.decode_value(e.set));return n},e.prototype.decode_map=function(e){for(var t=this.decode_integer(`u32`),n=new Map,r=0;r<t;++r){var i=this.decode_value(e.map.key),a=this.decode_value(e.map.value);n.set(i,a)}return n},e.prototype.decode_struct=function(e){var t={};for(var n in e.struct)t[n]=this.decode_value(e.struct[n]);return t},e}(),new Uint8Array([75,69,77,0,16]),new Uint8Array([72,80,75,69,0,16,0,1,0,2]),new Uint8Array([72,80,75,69,45,118,49]),new Uint8Array([115,101,99,114,101,116]),new Uint8Array([101,97,101,95,112,114,107]),new Uint8Array([115,104,97,114,101,100,95,115,101,99,114,101,116]),new Uint8Array([0,32,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,107,101,121,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([0,12,72,80,75,69,45,118,49,72,80,75,69,0,16,0,1,0,2,98,97,115,101,95,110,111,110,99,101,0,143,195,174,184,50,73,10,75,90,179,228,32,35,40,125,178,154,31,75,199,194,34,192,223,34,135,39,183,10,64,33,18,47,63,4,233,32,108,209,36,19,80,53,41,180,122,198,166,48,185,46,196,207,125,35,69,8,208,175,151,113,201,158,80]),new Uint8Array([113,111,115,95,101,110,99,114,121,112,116,105,111,110,95,104,109,97,99,95,109,101,115,115,97,103,101]);const Te=e=>{let t=a(e);if(t.length<2)throw Error(`failed to convert DER-encoded signature: insufficient length`);if(t[0]!==48)throw Error(`failed to convert DER-encoded signature: invalid format (missing SEQUENCE tag)`);let n=1,r=t[n];if(r<=127){if(t.length<2+r)throw Error(`failed to convert DER-encoded signature: inconsistent message length header`);n+=1}else throw Error(`failed to convert DER-encoded signature: unexpectedly large or invalid signature length`);if(t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for r`);n++;let i=t[n];if(i>33)throw Error(`failed to convert DER-encoded signature: unexpected length for r`);n++;let o=t.slice(n,n+i);if(n+=i,t[n]!==2)throw Error(`failed to convert DER-encoded signature: invalid tag for s`);n++;let c=t[n];if(c>33)throw Error(`failed to convert DER-encoded signature: unexpected length for s`);n++;let l=t.slice(n,n+c),u=s(o,32),d=s(l,32);return new Uint8Array([...u,...d])};var Ee;(function(e){e.NOTARIZER=`notarizer`,e.SIGNER=`signer`,e.EVM_PARSER=`evm-parser`,e.TLS_FETCHER=`tls-fetcher`,e.UMP=`ump`})(Ee||={});var De=i(((e,t)=>{(function(e,n){var r=2**-24,i=2**32,a=2**53;function o(e){var t=new ArrayBuffer(256),r=new DataView(t),o,s=0;function c(e){for(var n=t.byteLength,i=s+e;n<i;)n*=2;if(n!==t.byteLength){var a=r;t=new ArrayBuffer(n),r=new DataView(t);for(var c=s+3>>2,l=0;l<c;++l)r.setUint32(l*4,a.getUint32(l*4))}return o=e,r}function l(){s+=o}function u(e){l(c(8).setFloat64(s,e))}function d(e){l(c(1).setUint8(s,e))}function f(e){for(var t=c(e.length),n=0;n<e.length;++n)t.setUint8(s+n,e[n]);l()}function p(e){l(c(2).setUint16(s,e))}function m(e){l(c(4).setUint32(s,e))}function h(e){var t=e%i,n=(e-t)/i,r=c(8);r.setUint32(s,n),r.setUint32(s+4,t),l()}function g(e,t){t<24?d(e<<5|t):t<256?(d(e<<5|24),d(t)):t<65536?(d(e<<5|25),p(t)):t<4294967296?(d(e<<5|26),m(t)):(d(e<<5|27),h(t))}function _(e){var t;if(e===!1)return d(244);if(e===!0)return d(245);if(e===null)return d(246);if(e===n)return d(247);switch(typeof e){case`number`:if(Math.floor(e)===e){if(0<=e&&e<=a)return g(0,e);if(-a<=e&&e<0)return g(1,-(e+1))}return d(251),u(e);case`string`:var r=[];for(t=0;t<e.length;++t){var i=e.charCodeAt(t);i<128?r.push(i):i<2048?(r.push(192|i>>6),r.push(128|i&63)):i<55296?(r.push(224|i>>12),r.push(128|i>>6&63),r.push(128|i&63)):(i=(i&1023)<<10,i|=e.charCodeAt(++t)&1023,i+=65536,r.push(240|i>>18),r.push(128|i>>12&63),r.push(128|i>>6&63),r.push(128|i&63))}return g(3,r.length),f(r);default:var o;if(Array.isArray(e))for(o=e.length,g(4,o),t=0;t<o;++t)_(e[t]);else if(e instanceof Uint8Array)g(2,e.length),f(e);else{var s=Object.keys(e);for(o=s.length,g(5,o),t=0;t<o;++t){var c=s[t];_(c),_(e[c])}}}}if(_(e),`slice`in t)return t.slice(0,s);for(var v=new ArrayBuffer(s),y=new DataView(v),b=0;b<s;++b)y.setUint8(b,r.getUint8(b));return v}function s(e,t,a){var o=new DataView(e),s=0;typeof t!=`function`&&(t=function(e){return e}),typeof a!=`function`&&(a=function(){return n});function c(e,t){return s+=t,e}function l(t){return c(new Uint8Array(e,s,t),t)}function u(){var e=new DataView(new ArrayBuffer(4)),t=m(),n=t&32768,i=t&31744,a=t&1023;if(i===31744)i=261120;else if(i!==0)i+=114688;else if(a!==0)return a*r;return e.setUint32(0,n<<16|i<<13|a<<13),e.getFloat32(0)}function d(){return c(o.getFloat32(s),4)}function f(){return c(o.getFloat64(s),8)}function p(){return c(o.getUint8(s),1)}function m(){return c(o.getUint16(s),2)}function h(){return c(o.getUint32(s),4)}function g(){return h()*i+h()}function _(){return o.getUint8(s)===255&&(s+=1,!0)}function v(e){if(e<24)return e;if(e===24)return p();if(e===25)return m();if(e===26)return h();if(e===27)return g();if(e===31)return-1;throw`Invalid length encoding`}function y(e){var t=p();if(t===255)return-1;var n=v(t&31);if(n<0||t>>5!==e)throw`Invalid indefinite length element`;return n}function b(e,t){for(var n=0;n<t;++n){var r=p();r&128&&(r<224?(r=(r&31)<<6|p()&63,--t):r<240?(r=(r&15)<<12|(p()&63)<<6|p()&63,t-=2):(r=(r&15)<<18|(p()&63)<<12|(p()&63)<<6|p()&63,t-=3)),r<65536?e.push(r):(r-=65536,e.push(55296|r>>10),e.push(56320|r&1023))}}function x(){var e=p(),r=e>>5,i=e&31,o,s;if(r===7)switch(i){case 25:return u();case 26:return d();case 27:return f()}if(s=v(i),s<0&&(r<2||6<r))throw`Invalid length`;switch(r){case 0:return s;case 1:return-1-s;case 2:if(s<0){for(var c=[],m=0;(s=y(r))>=0;)m+=s,c.push(l(s));var h=new Uint8Array(m),g=0;for(o=0;o<c.length;++o)h.set(c[o],g),g+=c[o].length;return h}return l(s);case 3:var S=[];if(s<0)for(;(s=y(r))>=0;)b(S,s);else b(S,s);return String.fromCharCode.apply(null,S);case 4:var C;if(s<0)for(C=[];!_();)C.push(x());else for(C=Array(s),o=0;o<s;++o)C[o]=x();return C;case 5:var w={};for(o=0;o<s||s<0&&!_();++o){var T=x();w[T]=x()}return w;case 6:return t(x(),s);case 7:switch(s){case 20:return!1;case 21:return!0;case 22:return null;case 23:return n;default:return a(s)}}}var S=x();if(s!==e.byteLength)throw`Remaining bytes`;return S}var c={encode:o,decode:s};typeof define==`function`&&define.amd?define(`cbor/cbor`,c):t!==void 0&&t.exports?t.exports=c:e.CBOR||=c})(e)})),Oe=i((()=>{
3
3
  /*! *****************************************************************************
4
4
  Copyright (C) Microsoft. All rights reserved.
5
5
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -14,7 +14,7 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
14
14
  See the Apache Version 2.0 License for specific language governing permissions
15
15
  and limitations under the License.
16
16
  ***************************************************************************** */
17
- var e;(function(e){(function(t){var n=typeof globalThis==`object`?globalThis:typeof global==`object`?global:typeof self==`object`?self:typeof this==`object`?this:s(),r=i(e);n.Reflect!==void 0&&(r=i(n.Reflect,r)),t(r,n),n.Reflect===void 0&&(n.Reflect=e);function i(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:!0,writable:!0,value:r}),t&&t(n,r)}}function a(){try{return Function(`return this;`)()}catch{}}function o(){try{return(0,eval)(`(function() { return this; })()`)}catch{}}function s(){return a()||o()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol==`function`,i=r&&Symbol.toPrimitive!==void 0?Symbol.toPrimitive:`@@toPrimitive`,a=r&&Symbol.iterator!==void 0?Symbol.iterator:`@@iterator`,o=typeof Object.create==`function`,s={__proto__:[]}instanceof Array,c=!o&&!s,l={create:o?function(){return Te(Object.create(null))}:s?function(){return Te({__proto__:null})}:function(){return Te({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d=typeof Map==`function`&&typeof Map.prototype.entries==`function`?Map:z(),f=typeof Set==`function`&&typeof Set.prototype.entries==`function`?Set:Ce(),p=typeof WeakMap==`function`?WeakMap:we(),m=r?Symbol.for(`@reflect-metadata:registry`):void 0,h=be(),g=xe(h);function _(e,t,n,r){if(N(n)){if(!de(e)||!pe(t))throw TypeError();return D(e,t)}if(!de(e)||!P(t)||!P(r)&&!N(r)&&!ie(r))throw TypeError();return ie(r)&&(r=void 0),n=ue(n),O(e,t,n,r)}e(`decorate`,_);function v(e,t){function n(n,r){if(!P(n)||!N(r)&&!me(r))throw TypeError();M(e,t,n,r)}return n}e(`metadata`,v);function y(e,t,n,r){if(!P(n))throw TypeError();return N(r)||(r=ue(r)),M(e,t,n,r)}e(`defineMetadata`,y);function b(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=ue(n)),k(e,t,n)}e(`hasMetadata`,b);function x(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=ue(n)),A(e,t,n)}e(`hasOwnMetadata`,x);function S(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=ue(n)),ee(e,t,n)}e(`getMetadata`,S);function C(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=ue(n)),j(e,t,n)}e(`getOwnMetadata`,C);function w(e,t){if(!P(e))throw TypeError();return N(t)||(t=ue(t)),te(e,t)}e(`getMetadataKeys`,w);function T(e,t){if(!P(e))throw TypeError();return N(t)||(t=ue(t)),ne(e,t)}e(`getOwnMetadataKeys`,T);function E(e,t,n){if(!P(t)||(N(n)||(n=ue(n)),!P(t)))throw TypeError();N(n)||(n=ue(n));var r=R(t,n,!1);return!N(r)&&r.OrdinaryDeleteMetadata(e,t,n)}e(`deleteMetadata`,E);function D(e,t){for(var n=e.length-1;n>=0;--n){var r=e[n],i=r(t);if(!N(i)&&!ie(i)){if(!pe(i))throw TypeError();t=i}}return t}function O(e,t,n,r){for(var i=e.length-1;i>=0;--i){var a=e[i],o=a(t,n,r);if(!N(o)&&!ie(o)){if(!P(o))throw TypeError();r=o}}return r}function k(e,t,n){if(A(e,t,n))return!0;var r=L(t);return!ie(r)&&k(e,r,n)}function A(e,t,n){var r=R(t,n,!1);return!N(r)&&ce(r.OrdinaryHasOwnMetadata(e,t,n))}function ee(e,t,n){if(A(e,t,n))return j(e,t,n);var r=L(t);if(!ie(r))return ee(e,r,n)}function j(e,t,n){var r=R(t,n,!1);if(!N(r))return r.OrdinaryGetOwnMetadata(e,t,n)}function M(e,t,n,r){R(n,r,!0).OrdinaryDefineOwnMetadata(e,t,n,r)}function te(e,t){var n=ne(e,t),r=L(e);if(r===null)return n;var i=te(r,t);if(i.length<=0)return n;if(n.length<=0)return i;for(var a=new f,o=[],s=0,c=n;s<c.length;s++){var l=c[s],u=a.has(l);u||(a.add(l),o.push(l))}for(var d=0,p=i;d<p.length;d++){var l=p[d],u=a.has(l);u||(a.add(l),o.push(l))}return o}function ne(e,t){var n=R(e,t,!1);return n?n.OrdinaryOwnMetadataKeys(e,t):[]}function re(e){if(e===null)return 1;switch(typeof e){case`undefined`:return 0;case`boolean`:return 2;case`string`:return 3;case`symbol`:return 4;case`number`:return 5;case`object`:return e===null?1:6;default:return 6}}function N(e){return e===void 0}function ie(e){return e===null}function ae(e){return typeof e==`symbol`}function P(e){return typeof e==`object`?e!==null:typeof e==`function`}function oe(e,t){switch(re(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var n=t===3?`string`:t===5?`number`:`default`,r=F(e,i);if(r!==void 0){var a=r.call(e,n);if(P(a))throw TypeError();return a}return se(e,n==="default"?`number`:n)}function se(e,t){if(t===`string`){var n=e.toString;if(fe(n)){var r=n.call(e);if(!P(r))return r}var i=e.valueOf;if(fe(i)){var r=i.call(e);if(!P(r))return r}}else{var i=e.valueOf;if(fe(i)){var r=i.call(e);if(!P(r))return r}var a=e.toString;if(fe(a)){var r=a.call(e);if(!P(r))return r}}throw TypeError()}function ce(e){return!!e}function le(e){return``+e}function ue(e){var t=oe(e,3);return ae(t)?t:le(t)}function de(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)===`[object Array]`}function fe(e){return typeof e==`function`}function pe(e){return typeof e==`function`}function me(e){switch(re(e)){case 3:return!0;case 4:return!0;default:return!1}}function he(e,t){return e===t||e!==e&&t!==t}function F(e,t){var n=e[t];if(n!=null){if(!fe(n))throw TypeError();return n}}function ge(e){var t=F(e,a);if(!fe(t))throw TypeError();var n=t.call(e);if(!P(n))throw TypeError();return n}function _e(e){return e.value}function I(e){var t=e.next();return!t.done&&t}function ve(e){var t=e.return;t&&t.call(e)}function L(e){var t=Object.getPrototypeOf(e);if(typeof e!=`function`||e===u||t!==u)return t;var n=e.prototype,r=n&&Object.getPrototypeOf(n);if(r==null||r===Object.prototype)return t;var i=r.constructor;return typeof i!=`function`||i===e?t:i}function ye(){var e;!N(m)&&t.Reflect!==void 0&&!(m in t.Reflect)&&typeof t.Reflect.defineMetadata==`function`&&(e=Se(t.Reflect));var n,r,i,a=new p,o={registerProvider:s,getProvider:l,setProvider:h};return o;function s(t){if(!Object.isExtensible(o))throw Error(`Cannot add provider to a frozen registry.`);switch(!0){case e===t:break;case N(n):n=t;break;case n===t:break;case N(r):r=t;break;case r===t:break;default:i===void 0&&(i=new f),i.add(t)}}function c(t,a){if(!N(n)){if(n.isProviderFor(t,a))return n;if(!N(r)){if(r.isProviderFor(t,a))return n;if(!N(i))for(var o=ge(i);;){var s=I(o);if(!s)return;var c=_e(s);if(c.isProviderFor(t,a))return ve(o),c}}}if(!N(e)&&e.isProviderFor(t,a))return e}function l(e,t){var n=a.get(e),r;return N(n)||(r=n.get(t)),N(r)?(r=c(e,t),N(r)||(N(n)&&(n=new d,a.set(e,n)),n.set(t,r)),r):r}function u(e){if(N(e))throw TypeError();return n===e||r===e||!N(i)&&i.has(e)}function h(e,t,n){if(!u(n))throw Error(`Metadata provider not registered.`);var r=l(e,t);if(r!==n){if(!N(r))return!1;var i=a.get(e);N(i)&&(i=new d,a.set(e,i)),i.set(t,n)}return!0}}function be(){var e;return!N(m)&&P(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[m]),N(e)&&(e=ye()),!N(m)&&P(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function xe(e){var t=new p,n={isProviderFor:function(e,n){var r=t.get(e);return!N(r)&&r.has(n)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:a,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:c};return h.registerProvider(n),n;function r(r,i,a){var o=t.get(r),s=!1;if(N(o)){if(!a)return;o=new d,t.set(r,o),s=!0}var c=o.get(i);if(N(c)){if(!a)return;if(c=new d,o.set(i,c),!e.setProvider(r,i,n))throw o.delete(i),s&&t.delete(r),Error(`Wrong provider for target.`)}return c}function i(e,t,n){var i=r(t,n,!1);return!N(i)&&ce(i.has(e))}function a(e,t,n){var i=r(t,n,!1);if(!N(i))return i.get(e)}function o(e,t,n,i){r(n,i,!0).set(e,t)}function s(e,t){var n=[],i=r(e,t,!1);if(N(i))return n;for(var a=ge(i.keys()),o=0;;){var s=I(a);if(!s)return n.length=o,n;var c=_e(s);try{n[o]=c}catch(e){try{ve(a)}finally{throw e}}o++}}function c(e,n,i){var a=r(n,i,!1);if(N(a)||!a.delete(e))return!1;if(a.size===0){var o=t.get(n);N(o)||(o.delete(i),o.size===0&&t.delete(o))}return!0}}function Se(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,i=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new p;return{isProviderFor:function(e,t){var n=o.get(e);return!N(n)&&n.has(t)?!0:i(e,t).length?(N(n)&&(n=new f,o.set(e,n)),n.add(t),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:a}}function R(e,t,n){var r=h.getProvider(e,t);if(!N(r))return r;if(n){if(h.setProvider(e,t,g))return g;throw Error(`Illegal state.`)}}function z(){var e={},t=[],n=function(){function e(e,t,n){this._index=0,this._keys=e,this._values=t,this._selector=n}return e.prototype[`@@iterator`]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:n,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var n=this._find(e,!0);return this._values[n]=t,this},t.prototype.delete=function(t){var n=this._find(t,!1);if(n>=0){for(var r=this._keys.length,i=n+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,he(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new n(this._keys,this._values,r)},t.prototype.values=function(){return new n(this._keys,this._values,i)},t.prototype.entries=function(){return new n(this._keys,this._values,o)},t.prototype[`@@iterator`]=function(){return this.entries()},t.prototype[a]=function(){return this.entries()},t.prototype._find=function(e,t){if(!he(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(he(this._keys[n],e)){this._cacheIndex=n;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function r(e,t){return e}function i(e,t){return t}function o(e,t){return[e,t]}}function Ce(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype[`@@iterator`]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}()}function we(){var e=l.create(),t=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=i(e,!1);return t!==void 0&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return t===void 0?void 0:l.get(t,this._key)},e.prototype.set=function(e,t){var n=i(e,!0);return n[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return t!==void 0&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var t;do t=`@@WeakMap@@`+s();while(l.has(e,t));return e[t]=!0,t}function i(e,r){if(!n.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function a(e,t){for(var n=0;n<t;++n)e[n]=Math.random()*255|0;return e}function o(e){if(typeof Uint8Array==`function`){var t=new Uint8Array(e);return typeof crypto<`u`?crypto.getRandomValues(t):typeof msCrypto<`u`?msCrypto.getRandomValues(t):a(t,e),t}return a(Array(e),e)}function s(){var e=o(16);e[6]=e[6]&79|64,e[8]=e[8]&191|128;for(var t=``,n=0;n<16;++n){var r=e[n];(n===4||n===6||n===8)&&(t+=`-`),r<16&&(t+=`0`),t+=r.toString(16).toLowerCase()}return t}}function Te(e){return e.__=void 0,delete e.__,e}})})(e||={})})),B=r({__addDisposableResource:()=>Ze,__assign:()=>tt,__asyncDelegator:()=>We,__asyncGenerator:()=>Ue,__asyncValues:()=>Ge,__await:()=>He,__awaiter:()=>Le,__classPrivateFieldGet:()=>G,__classPrivateFieldIn:()=>Xe,__classPrivateFieldSet:()=>Ye,__createBinding:()=>nt,__decorate:()=>Ae,__disposeResources:()=>Qe,__esDecorate:()=>Me,__exportStar:()=>ze,__extends:()=>ke,__generator:()=>Re,__importDefault:()=>Je,__importStar:()=>qe,__makeTemplateObject:()=>Ke,__metadata:()=>Ie,__param:()=>je,__propKey:()=>Pe,__read:()=>Be,__rest:()=>V,__rewriteRelativeImportExtension:()=>$e,__runInitializers:()=>Ne,__setFunctionName:()=>Fe,__spread:()=>U,__spreadArray:()=>Ve,__spreadArrays:()=>W,__values:()=>H,default:()=>ot});function ke(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);et(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function V(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Ae(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function je(e,t){return function(n,r){t(n,r,e)}}function Me(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function Ne(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function Pe(e){return typeof e==`symbol`?e:`${e}`}function Fe(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function Ie(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function Le(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Re(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function ze(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&nt(t,e,n)}function H(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Be(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function U(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Be(arguments[t]));return e}function W(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function Ve(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function He(e){return this instanceof He?(this.v=e,this):new He(e)}function Ue(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof He?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function We(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:He(e[r](t)),done:!1}:i?i(t):t}:i}}function Ge(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof H==`function`?H(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Ke(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function qe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=it(e),r=0;r<n.length;r++)n[r]!=="default"&&nt(t,e,n[r]);return rt(t,e),t}function Je(e){return e&&e.__esModule?e:{default:e}}function G(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Ye(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Xe(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function Ze(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Qe(e){function t(t){e.error=e.hasError?new at(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function $e(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var et,tt,nt,rt,it,at,ot,K=n((()=>{et=function(e,t){return et=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},et(e,t)},tt=function(){return tt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},tt.apply(this,arguments)},nt=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),rt=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},it=function(e){return it=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},it(e)},at=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},ot={__extends:ke,__assign:tt,__rest:V,__decorate:Ae,__param:je,__esDecorate:Me,__runInitializers:Ne,__propKey:Pe,__setFunctionName:Fe,__metadata:Ie,__awaiter:Le,__generator:Re,__createBinding:nt,__exportStar:ze,__values:H,__read:Be,__spread:U,__spreadArrays:W,__spreadArray:Ve,__await:He,__asyncGenerator:Ue,__asyncDelegator:We,__asyncValues:Ge,__makeTemplateObject:Ke,__importStar:qe,__importDefault:Je,__classPrivateFieldGet:G,__classPrivateFieldSet:Ye,__classPrivateFieldIn:Xe,__addDisposableResource:Ze,__disposeResources:Qe,__rewriteRelativeImportExtension:$e}})),st=i((e=>{
17
+ var e;(function(e){(function(t){var n=typeof globalThis==`object`?globalThis:typeof global==`object`?global:typeof self==`object`?self:typeof this==`object`?this:s(),r=i(e);n.Reflect!==void 0&&(r=i(n.Reflect,r)),t(r,n),n.Reflect===void 0&&(n.Reflect=e);function i(e,t){return function(n,r){Object.defineProperty(e,n,{configurable:!0,writable:!0,value:r}),t&&t(n,r)}}function a(){try{return Function(`return this;`)()}catch{}}function o(){try{return(0,eval)(`(function() { return this; })()`)}catch{}}function s(){return a()||o()}})(function(e,t){var n=Object.prototype.hasOwnProperty,r=typeof Symbol==`function`,i=r&&Symbol.toPrimitive!==void 0?Symbol.toPrimitive:`@@toPrimitive`,a=r&&Symbol.iterator!==void 0?Symbol.iterator:`@@iterator`,o=typeof Object.create==`function`,s={__proto__:[]}instanceof Array,c=!o&&!s,l={create:o?function(){return Te(Object.create(null))}:s?function(){return Te({__proto__:null})}:function(){return Te({})},has:c?function(e,t){return n.call(e,t)}:function(e,t){return t in e},get:c?function(e,t){return n.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d=typeof Map==`function`&&typeof Map.prototype.entries==`function`?Map:z(),f=typeof Set==`function`&&typeof Set.prototype.entries==`function`?Set:Ce(),p=typeof WeakMap==`function`?WeakMap:we(),m=r?Symbol.for(`@reflect-metadata:registry`):void 0,h=ye(),g=be(h);function _(e,t,n,r){if(N(n)){if(!ue(e)||!fe(t))throw TypeError();return D(e,t)}if(!ue(e)||!P(t)||!P(r)&&!N(r)&&!ie(r))throw TypeError();return ie(r)&&(r=void 0),n=F(n),O(e,t,n,r)}e(`decorate`,_);function v(e,t){function n(n,r){if(!P(n)||!N(r)&&!pe(r))throw TypeError();M(e,t,n,r)}return n}e(`metadata`,v);function y(e,t,n,r){if(!P(n))throw TypeError();return N(r)||(r=F(r)),M(e,t,n,r)}e(`defineMetadata`,y);function b(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=F(n)),k(e,t,n)}e(`hasMetadata`,b);function x(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=F(n)),A(e,t,n)}e(`hasOwnMetadata`,x);function S(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=F(n)),ee(e,t,n)}e(`getMetadata`,S);function C(e,t,n){if(!P(t))throw TypeError();return N(n)||(n=F(n)),j(e,t,n)}e(`getOwnMetadata`,C);function w(e,t){if(!P(e))throw TypeError();return N(t)||(t=F(t)),te(e,t)}e(`getMetadataKeys`,w);function T(e,t){if(!P(e))throw TypeError();return N(t)||(t=F(t)),ne(e,t)}e(`getOwnMetadataKeys`,T);function E(e,t,n){if(!P(t)||(N(n)||(n=F(n)),!P(t)))throw TypeError();N(n)||(n=F(n));var r=Se(t,n,!1);return!N(r)&&r.OrdinaryDeleteMetadata(e,t,n)}e(`deleteMetadata`,E);function D(e,t){for(var n=e.length-1;n>=0;--n){var r=e[n],i=r(t);if(!N(i)&&!ie(i)){if(!fe(i))throw TypeError();t=i}}return t}function O(e,t,n,r){for(var i=e.length-1;i>=0;--i){var a=e[i],o=a(t,n,r);if(!N(o)&&!ie(o)){if(!P(o))throw TypeError();r=o}}return r}function k(e,t,n){if(A(e,t,n))return!0;var r=R(t);return!ie(r)&&k(e,r,n)}function A(e,t,n){var r=Se(t,n,!1);return!N(r)&&ce(r.OrdinaryHasOwnMetadata(e,t,n))}function ee(e,t,n){if(A(e,t,n))return j(e,t,n);var r=R(t);if(!ie(r))return ee(e,r,n)}function j(e,t,n){var r=Se(t,n,!1);if(!N(r))return r.OrdinaryGetOwnMetadata(e,t,n)}function M(e,t,n,r){Se(n,r,!0).OrdinaryDefineOwnMetadata(e,t,n,r)}function te(e,t){var n=ne(e,t),r=R(e);if(r===null)return n;var i=te(r,t);if(i.length<=0)return n;if(n.length<=0)return i;for(var a=new f,o=[],s=0,c=n;s<c.length;s++){var l=c[s],u=a.has(l);u||(a.add(l),o.push(l))}for(var d=0,p=i;d<p.length;d++){var l=p[d],u=a.has(l);u||(a.add(l),o.push(l))}return o}function ne(e,t){var n=Se(e,t,!1);return n?n.OrdinaryOwnMetadataKeys(e,t):[]}function re(e){if(e===null)return 1;switch(typeof e){case`undefined`:return 0;case`boolean`:return 2;case`string`:return 3;case`symbol`:return 4;case`number`:return 5;case`object`:return e===null?1:6;default:return 6}}function N(e){return e===void 0}function ie(e){return e===null}function ae(e){return typeof e==`symbol`}function P(e){return typeof e==`object`?e!==null:typeof e==`function`}function oe(e,t){switch(re(e)){case 0:return e;case 1:return e;case 2:return e;case 3:return e;case 4:return e;case 5:return e}var n=t===3?`string`:t===5?`number`:`default`,r=I(e,i);if(r!==void 0){var a=r.call(e,n);if(P(a))throw TypeError();return a}return se(e,n==="default"?`number`:n)}function se(e,t){if(t===`string`){var n=e.toString;if(de(n)){var r=n.call(e);if(!P(r))return r}var i=e.valueOf;if(de(i)){var r=i.call(e);if(!P(r))return r}}else{var i=e.valueOf;if(de(i)){var r=i.call(e);if(!P(r))return r}var a=e.toString;if(de(a)){var r=a.call(e);if(!P(r))return r}}throw TypeError()}function ce(e){return!!e}function le(e){return``+e}function F(e){var t=oe(e,3);return ae(t)?t:le(t)}function ue(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:Object.prototype.toString.call(e)===`[object Array]`}function de(e){return typeof e==`function`}function fe(e){return typeof e==`function`}function pe(e){switch(re(e)){case 3:return!0;case 4:return!0;default:return!1}}function me(e,t){return e===t||e!==e&&t!==t}function I(e,t){var n=e[t];if(n!=null){if(!de(n))throw TypeError();return n}}function he(e){var t=I(e,a);if(!de(t))throw TypeError();var n=t.call(e);if(!P(n))throw TypeError();return n}function ge(e){return e.value}function L(e){var t=e.next();return!t.done&&t}function _e(e){var t=e.return;t&&t.call(e)}function R(e){var t=Object.getPrototypeOf(e);if(typeof e!=`function`||e===u||t!==u)return t;var n=e.prototype,r=n&&Object.getPrototypeOf(n);if(r==null||r===Object.prototype)return t;var i=r.constructor;return typeof i!=`function`||i===e?t:i}function ve(){var e;!N(m)&&t.Reflect!==void 0&&!(m in t.Reflect)&&typeof t.Reflect.defineMetadata==`function`&&(e=xe(t.Reflect));var n,r,i,a=new p,o={registerProvider:s,getProvider:l,setProvider:h};return o;function s(t){if(!Object.isExtensible(o))throw Error(`Cannot add provider to a frozen registry.`);switch(!0){case e===t:break;case N(n):n=t;break;case n===t:break;case N(r):r=t;break;case r===t:break;default:i===void 0&&(i=new f),i.add(t)}}function c(t,a){if(!N(n)){if(n.isProviderFor(t,a))return n;if(!N(r)){if(r.isProviderFor(t,a))return n;if(!N(i))for(var o=he(i);;){var s=L(o);if(!s)return;var c=ge(s);if(c.isProviderFor(t,a))return _e(o),c}}}if(!N(e)&&e.isProviderFor(t,a))return e}function l(e,t){var n=a.get(e),r;return N(n)||(r=n.get(t)),N(r)?(r=c(e,t),N(r)||(N(n)&&(n=new d,a.set(e,n)),n.set(t,r)),r):r}function u(e){if(N(e))throw TypeError();return n===e||r===e||!N(i)&&i.has(e)}function h(e,t,n){if(!u(n))throw Error(`Metadata provider not registered.`);var r=l(e,t);if(r!==n){if(!N(r))return!1;var i=a.get(e);N(i)&&(i=new d,a.set(e,i)),i.set(t,n)}return!0}}function ye(){var e;return!N(m)&&P(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[m]),N(e)&&(e=ve()),!N(m)&&P(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,m,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function be(e){var t=new p,n={isProviderFor:function(e,n){var r=t.get(e);return!N(r)&&r.has(n)},OrdinaryDefineOwnMetadata:o,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:a,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:c};return h.registerProvider(n),n;function r(r,i,a){var o=t.get(r),s=!1;if(N(o)){if(!a)return;o=new d,t.set(r,o),s=!0}var c=o.get(i);if(N(c)){if(!a)return;if(c=new d,o.set(i,c),!e.setProvider(r,i,n))throw o.delete(i),s&&t.delete(r),Error(`Wrong provider for target.`)}return c}function i(e,t,n){var i=r(t,n,!1);return!N(i)&&ce(i.has(e))}function a(e,t,n){var i=r(t,n,!1);if(!N(i))return i.get(e)}function o(e,t,n,i){r(n,i,!0).set(e,t)}function s(e,t){var n=[],i=r(e,t,!1);if(N(i))return n;for(var a=he(i.keys()),o=0;;){var s=L(a);if(!s)return n.length=o,n;var c=ge(s);try{n[o]=c}catch(e){try{_e(a)}finally{throw e}}o++}}function c(e,n,i){var a=r(n,i,!1);if(N(a)||!a.delete(e))return!1;if(a.size===0){var o=t.get(n);N(o)||(o.delete(i),o.size===0&&t.delete(o))}return!0}}function xe(e){var t=e.defineMetadata,n=e.hasOwnMetadata,r=e.getOwnMetadata,i=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new p;return{isProviderFor:function(e,t){var n=o.get(e);return!N(n)&&n.has(t)?!0:i(e,t).length?(N(n)&&(n=new f,o.set(e,n)),n.add(t),!0):!1},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:n,OrdinaryGetOwnMetadata:r,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:a}}function Se(e,t,n){var r=h.getProvider(e,t);if(!N(r))return r;if(n){if(h.setProvider(e,t,g))return g;throw Error(`Illegal state.`)}}function z(){var e={},t=[],n=function(){function e(e,t,n){this._index=0,this._keys=e,this._values=t,this._selector=n}return e.prototype[`@@iterator`]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var n=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:n,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}();return function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var n=this._find(e,!0);return this._values[n]=t,this},t.prototype.delete=function(t){var n=this._find(t,!1);if(n>=0){for(var r=this._keys.length,i=n+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,me(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new n(this._keys,this._values,r)},t.prototype.values=function(){return new n(this._keys,this._values,i)},t.prototype.entries=function(){return new n(this._keys,this._values,o)},t.prototype[`@@iterator`]=function(){return this.entries()},t.prototype[a]=function(){return this.entries()},t.prototype._find=function(e,t){if(!me(this._cacheKey,e)){this._cacheIndex=-1;for(var n=0;n<this._keys.length;n++)if(me(this._keys[n],e)){this._cacheIndex=n;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();function r(e,t){return e}function i(e,t){return t}function o(e,t){return[e,t]}}function Ce(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype[`@@iterator`]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}()}function we(){var e=l.create(),t=r();return function(){function e(){this._key=r()}return e.prototype.has=function(e){var t=i(e,!1);return t!==void 0&&l.has(t,this._key)},e.prototype.get=function(e){var t=i(e,!1);return t===void 0?void 0:l.get(t,this._key)},e.prototype.set=function(e,t){var n=i(e,!0);return n[this._key]=t,this},e.prototype.delete=function(e){var t=i(e,!1);return t!==void 0&&delete t[this._key]},e.prototype.clear=function(){this._key=r()},e}();function r(){var t;do t=`@@WeakMap@@`+s();while(l.has(e,t));return e[t]=!0,t}function i(e,r){if(!n.call(e,t)){if(!r)return;Object.defineProperty(e,t,{value:l.create()})}return e[t]}function a(e,t){for(var n=0;n<t;++n)e[n]=Math.random()*255|0;return e}function o(e){if(typeof Uint8Array==`function`){var t=new Uint8Array(e);return typeof crypto<`u`?crypto.getRandomValues(t):typeof msCrypto<`u`?msCrypto.getRandomValues(t):a(t,e),t}return a(Array(e),e)}function s(){var e=o(16);e[6]=e[6]&79|64,e[8]=e[8]&191|128;for(var t=``,n=0;n<16;++n){var r=e[n];(n===4||n===6||n===8)&&(t+=`-`),r<16&&(t+=`0`),t+=r.toString(16).toLowerCase()}return t}}function Te(e){return e.__=void 0,delete e.__,e}})})(e||={})})),B=r({__addDisposableResource:()=>Ze,__assign:()=>tt,__asyncDelegator:()=>We,__asyncGenerator:()=>Ue,__asyncValues:()=>Ge,__await:()=>He,__awaiter:()=>Le,__classPrivateFieldGet:()=>G,__classPrivateFieldIn:()=>Xe,__classPrivateFieldSet:()=>Ye,__createBinding:()=>nt,__decorate:()=>Ae,__disposeResources:()=>Qe,__esDecorate:()=>Me,__exportStar:()=>ze,__extends:()=>ke,__generator:()=>Re,__importDefault:()=>Je,__importStar:()=>qe,__makeTemplateObject:()=>Ke,__metadata:()=>Ie,__param:()=>je,__propKey:()=>Pe,__read:()=>Be,__rest:()=>V,__rewriteRelativeImportExtension:()=>$e,__runInitializers:()=>Ne,__setFunctionName:()=>Fe,__spread:()=>U,__spreadArray:()=>Ve,__spreadArrays:()=>W,__values:()=>H,default:()=>ot});function ke(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);et(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function V(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Ae(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function je(e,t){return function(n,r){t(n,r,e)}}function Me(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function Ne(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function Pe(e){return typeof e==`symbol`?e:`${e}`}function Fe(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function Ie(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function Le(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Re(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function ze(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&nt(t,e,n)}function H(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Be(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function U(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Be(arguments[t]));return e}function W(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function Ve(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function He(e){return this instanceof He?(this.v=e,this):new He(e)}function Ue(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof He?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function We(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:He(e[r](t)),done:!1}:i?i(t):t}:i}}function Ge(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof H==`function`?H(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Ke(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function qe(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=it(e),r=0;r<n.length;r++)n[r]!=="default"&&nt(t,e,n[r]);return rt(t,e),t}function Je(e){return e&&e.__esModule?e:{default:e}}function G(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Ye(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Xe(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function Ze(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Qe(e){function t(t){e.error=e.hasError?new at(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function $e(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var et,tt,nt,rt,it,at,ot,K=n((()=>{et=function(e,t){return et=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},et(e,t)},tt=function(){return tt=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},tt.apply(this,arguments)},nt=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),rt=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},it=function(e){return it=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},it(e)},at=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},ot={__extends:ke,__assign:tt,__rest:V,__decorate:Ae,__param:je,__esDecorate:Me,__runInitializers:Ne,__propKey:Pe,__setFunctionName:Fe,__metadata:Ie,__awaiter:Le,__generator:Re,__createBinding:nt,__exportStar:ze,__values:H,__read:Be,__spread:U,__spreadArrays:W,__spreadArray:Ve,__await:He,__asyncGenerator:Ue,__asyncDelegator:We,__asyncValues:Ge,__makeTemplateObject:Ke,__importStar:qe,__importDefault:Je,__classPrivateFieldGet:G,__classPrivateFieldSet:Ye,__classPrivateFieldIn:Xe,__addDisposableResource:Ze,__disposeResources:Qe,__rewriteRelativeImportExtension:$e}})),st=i((e=>{
18
18
  /*!
19
19
  * MIT License
20
20
  *
@@ -80,7 +80,7 @@ Object.defineProperty(e,"__esModule",{value:!0});function t(e){return new Date(e
80
80
  var t=st(),n=ct();function r(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var i=r(t),a=r(n);function o(){if(typeof BigInt>`u`)throw Error(`BigInt is not defined. Your environment doesn't implement BigInt.`)}function s(e){let t=0,n=0;for(let n=0;n<e.length;n++){let r=e[n];t+=r.byteLength}let r=new Uint8Array(t);for(let t=0;t<e.length;t++){let i=e[t];r.set(new Uint8Array(i),n),n+=i.byteLength}return r.buffer}function c(e,t,n,r){return t instanceof Uint8Array?t.byteLength?n<0?(e.error=`Wrong parameter: inputOffset less than zero`,!1):r<0?(e.error=`Wrong parameter: inputLength less than zero`,!1):t.byteLength-n-r<0?(e.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,!1):!0:(e.error=`Wrong parameter: inputBuffer has zero length`,!1):(e.error=`Wrong parameter: inputBuffer must be 'Uint8Array'`,!1)}var l=class{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return s(this.items)}};let u=[new Uint8Array([1])],d=`0123456789`,f=`name`,p=`valueHexView`,m=new ArrayBuffer(0),h=new Uint8Array,g=`EndOfContent`,_=`OCTET STRING`,v=`BIT STRING`;function y(e){var t=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){super(...e);let t=e[0]||{};this.isHexOnly=t.isHexOnly??!1,this.valueHexView=t.valueHex?i.BufferSourceConverter.toUint8Array(t.valueHex):h}fromBER(e,t,n,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!c(this,i,t,n))return-1;let a=t+n;return this.valueHexView=i.subarray(t,a),this.valueHexView.length?(this.blockLength=n,a):(this.warnings.push(`Zero buffer length`),t)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error=`Flag 'isHexOnly' is not set, abort`,m)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:i.Convert.ToHex(this.valueHexView)}}};return t.NAME=`hexBlock`,t}var b=class{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:t=``,warnings:n=[],valueBeforeDecode:r=h}={}){this.blockLength=e,this.error=t,this.warnings=n,this.valueBeforeDecodeView=i.BufferSourceConverter.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:i.Convert.ToHex(this.valueBeforeDecodeView)}}};b.NAME=`baseBlock`;var x=class extends b{fromBER(e,t,n,r){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}toBER(e,t){throw TypeError(`User need to make a specific function in a class which extends 'ValueBlock'`)}};x.NAME=`valueBlock`;var S=class extends y(b){constructor({idBlock:e={}}={}){super(),e?(this.isHexOnly=e.isHexOnly??!1,this.valueHexView=e.valueHex?i.BufferSourceConverter.toUint8Array(e.valueHex):h,this.tagClass=e.tagClass??-1,this.tagNumber=e.tagNumber??-1,this.isConstructed=e.isConstructed??!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error=`Unknown tag class`,m}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){let n=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,t|=e,n[0]=t}return n.buffer}if(!this.isHexOnly){let n=a.utilToBase(this.tagNumber,7),r=new Uint8Array(n),i=n.byteLength,o=new Uint8Array(i+1);if(o[0]=t|31,!e){for(let e=0;e<i-1;e++)o[e+1]=r[e]|128;o[i]=r[i-1]}return o.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=t|31,!e){let e=this.valueHexView;for(let t=0;t<e.length-1;t++)n[t+1]=e[t]|128;n[this.valueHexView.byteLength]=e[e.length-1]}return n.buffer}fromBER(e,t,n){let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);if(o.length===0)return this.error=`Zero buffer length`,-1;switch(o[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error=`Unknown tag class`,-1}this.isConstructed=(o[0]&32)==32,this.isHexOnly=!1;let s=o[0]&31;if(s!==31)this.tagNumber=s,this.blockLength=1;else{let e=0;for(;;){let t=e+1;if(t>=o.length)return this.error=`End of input reached before message was fully decoded`,-1;if(e++,!(o[t]&128))break}this.blockLength=e+1;let t=this.valueHexView=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=o[n+1]&127;this.blockLength<=9?this.tagNumber=a.utilFromBase(t,7):(this.isHexOnly=!0,this.warnings.push(`Tag too long, represented as hex-coded`))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error=`Constructed encoding used for primitive type`,-1}return t+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};S.NAME=`identificationBlock`;var C=class extends b{constructor({lenBlock:e={}}={}){super(),this.isIndefiniteForm=e.isIndefiniteForm??!1,this.longFormUsed=e.longFormUsed??!1,this.length=e.length??0}fromBER(e,t,n){let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);if(o.length===0)return this.error=`Zero buffer length`,-1;if(o[0]===255)return this.error=`Length block 0xFF is reserved by standard`,-1;if(this.isIndefiniteForm=o[0]===128,this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(o[0]&128),this.longFormUsed===!1)return this.length=o[0],this.blockLength=1,t+this.blockLength;let s=o[0]&127;if(s>8)return this.error=`Too big integer`,-1;if(s+1>o.length)return this.error=`End of input reached before message was fully decoded`,-1;let l=t+1,u=r.subarray(l,l+s);return u[s-1]===0&&this.warnings.push(`Needlessly long encoded length`),this.length=a.utilFromBase(u,8),this.longFormUsed&&this.length<=127&&this.warnings.push(`Unnecessary usage of long length form`),this.blockLength=s+1,t+this.blockLength}toBER(e=!1){let t,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=128),t;if(this.longFormUsed){let r=a.utilToBase(this.length,8);if(r.byteLength>127)return this.error=`Too big length`,m;if(t=new ArrayBuffer(r.byteLength+1),e)return t;let i=new Uint8Array(r);n=new Uint8Array(t),n[0]=r.byteLength|128;for(let e=0;e<r.byteLength;e++)n[e+1]=i[e];return t}return t=new ArrayBuffer(1),e===!1&&(n=new Uint8Array(t),n[0]=this.length),t}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};C.NAME=`lengthBlock`;let w={};var T=class extends b{constructor({name:e=``,optional:t=!1,primitiveSchema:n,...r}={},i){super(r),this.name=e,this.optional=t,n&&(this.primitiveSchema=n),this.idBlock=new S(r),this.lenBlock=new C(r),this.valueBlock=i?new i(r):new x(r)}fromBER(e,t,n,r){let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}toBER(e,t){let n=t||new l;t||E(this);let r=this.idBlock.toBER(e);if(n.write(r),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,n),n.write(new ArrayBuffer(2));else{let t=this.valueBlock.toBER(e);this.lenBlock.length=t.byteLength;let r=this.lenBlock.toBER(e);n.write(r),n.write(t)}return t?m:n.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e=`ascii`){return e===`ascii`?this.onAsciiEncoding():i.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${i.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(e){if(this===e)return!0;if(!(e instanceof this.constructor))return!1;let t=this.toBER(),n=e.toBER();return a.isEqualBuffer(t,n)}};T.NAME=`BaseBlock`;function E(e){if(e instanceof w.Constructed)for(let t of e.valueBlock.value)E(t)&&(e.lenBlock.isIndefiniteForm=!0);return!!e.lenBlock?.isIndefiniteForm}var D=class extends T{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e=``,...t}={},n){super(t,n),e&&this.fromString(e)}fromBER(e,t,n){let r=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return r===-1?(this.error=this.valueBlock.error,r):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),r)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};D.NAME=`BaseStringBlock`;var O=class extends y(x){constructor({isHexOnly:e=!0,...t}={}){super(t),this.isHexOnly=e}};O.NAME=`PrimitiveValueBlock`;var k,A=class extends T{constructor(e={}){super(e,O),this.idBlock.isConstructed=!1}};k=A,w.Primitive=k,A.NAME=`PRIMITIVE`;let ee=1e4,j=16777216;function M(e={}){return{depth:0,maxDepth:e.maxDepth??100,nodesCount:0,maxNodes:e.maxNodes??ee,maxContentLength:e.maxContentLength??j}}function te(e){let t=new T({},x);return t.error=e,{offset:-1,result:t}}function ne(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return`Maximum ASN.1 node count exceeded`}function re(e,t){if(e>t.maxContentLength)return`Maximum ASN.1 content length exceeded`}function N(e,t,n,r){let i=r.depth+1;if(i>r.maxDepth)return te(`Maximum ASN.1 nesting depth exceeded`);r.depth=i;try{return ae(e,t,n,r)}finally{--r.depth}}function ie(e,t){if(e instanceof t)return e;let n=new t;return n.idBlock=e.idBlock,n.lenBlock=e.lenBlock,n.warnings=e.warnings,n.valueBeforeDecodeView=e.valueBeforeDecodeView,n}function ae(e,t=0,n=e.length,r=M()){let i=t,a=new T({},x),o=new b;if(!c(o,e,t,n))return a.error=o.error,{offset:-1,result:a};if(!e.subarray(t,t+n).length)return a.error=`Zero buffer length`,{offset:-1,result:a};let s=ne(r);if(s)return a.error=s,{offset:-1,result:a};let l=a.idBlock.fromBER(e,t,n);if(a.idBlock.warnings.length&&a.warnings.concat(a.idBlock.warnings),l===-1)return a.error=a.idBlock.error,{offset:-1,result:a};if(t=l,n-=a.idBlock.blockLength,l=a.lenBlock.fromBER(e,t,n),a.lenBlock.warnings.length&&a.warnings.concat(a.lenBlock.warnings),l===-1)return a.error=a.lenBlock.error,{offset:-1,result:a};t=l,n-=a.lenBlock.blockLength;let u=a.lenBlock.isIndefiniteForm?n:a.lenBlock.length,d=re(u,r);if(d)return a.error=d,{offset:-1,result:a};if(!a.idBlock.isConstructed&&a.lenBlock.isIndefiniteForm)return a.error=`Indefinite length form used for primitive encoding form`,{offset:-1,result:a};let f=T;switch(a.idBlock.tagClass){case 1:if(a.idBlock.tagNumber>=37&&a.idBlock.isHexOnly===!1)return a.error=`UNIVERSAL 37 and upper tags are reserved by ASN.1 standard`,{offset:-1,result:a};switch(a.idBlock.tagNumber){case 0:if(a.idBlock.isConstructed&&a.lenBlock.length>0)return a.error=`Type [UNIVERSAL 0] is reserved`,{offset:-1,result:a};f=w.EndOfContent;break;case 1:f=w.Boolean;break;case 2:f=w.Integer;break;case 3:f=w.BitString;break;case 4:f=w.OctetString;break;case 5:f=w.Null;break;case 6:f=w.ObjectIdentifier;break;case 10:f=w.Enumerated;break;case 12:f=w.Utf8String;break;case 13:f=w.RelativeObjectIdentifier;break;case 14:f=w.TIME;break;case 15:return a.error=`[UNIVERSAL 15] is reserved by ASN.1 standard`,{offset:-1,result:a};case 16:f=w.Sequence;break;case 17:f=w.Set;break;case 18:f=w.NumericString;break;case 19:f=w.PrintableString;break;case 20:f=w.TeletexString;break;case 21:f=w.VideotexString;break;case 22:f=w.IA5String;break;case 23:f=w.UTCTime;break;case 24:f=w.GeneralizedTime;break;case 25:f=w.GraphicString;break;case 26:f=w.VisibleString;break;case 27:f=w.GeneralString;break;case 28:f=w.UniversalString;break;case 29:f=w.CharacterString;break;case 30:f=w.BmpString;break;case 31:f=w.DATE;break;case 32:f=w.TimeOfDay;break;case 33:f=w.DateTime;break;case 34:f=w.Duration;break;default:{let e=a.idBlock.isConstructed?new w.Constructed:new w.Primitive;e.idBlock=a.idBlock,e.lenBlock=a.lenBlock,e.warnings=a.warnings,a=e}}break;default:f=a.idBlock.isConstructed?w.Constructed:w.Primitive}return a=ie(a,f),l=a.fromBER(e,t,u,r),a.valueBeforeDecodeView=e.subarray(i,i+a.blockLength),{offset:l,result:a}}function P(e,t={}){if(!e.byteLength){let e=new T({},x);return e.error=`Input buffer has zero length`,{offset:-1,result:e}}return ae(i.BufferSourceConverter.toUint8Array(e).slice(),0,e.byteLength,M(t))}function oe(e,t){return e?1:t}var se=class extends x{constructor({value:e=[],isIndefiniteForm:t=!1,...n}={}){super(n),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,n,r){let a=i.BufferSourceConverter.toUint8Array(e),o=r??M();if(!c(this,a,t,n))return-1;if(this.valueBeforeDecodeView=a.subarray(t,t+n),this.valueBeforeDecodeView.length===0)return this.warnings.push(`Zero buffer length`),t;let s=t;for(;oe(this.isIndefiniteForm,n)>0;){let e=N(a,s,n,o);if(e.offset===-1)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,n-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===g)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===g?this.value.pop():this.warnings.push(`No EndOfContent block encoded`)),s}toBER(e,t){let n=t||new l;for(let t=0;t<this.value.length;t++)this.value[t].toBER(e,n);return t?m:n.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let t of this.value)e.value.push(t.toJSON());return e}};se.NAME=`ConstructedValueBlock`;var ce,le=class extends T{constructor(e={}){super(e,se),this.idBlock.isConstructed=!0}fromBER(e,t,n,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length,r);return i===-1?(this.error=this.valueBlock.error,i):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),i)}onAsciiEncoding(){let e=[];for(let t of this.valueBlock.value)e.push(t.toString(`ascii`).split(`
81
81
  `).map(e=>` ${e}`).join(`
82
82
  `));let t=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join(`
83
- `)}`:`${t} :`}};ce=le,w.Constructed=ce,le.NAME=`CONSTRUCTED`;var ue=class extends x{fromBER(e,t,n){return t}toBER(e){return m}};ue.override=`EndOfContentValueBlock`;var de,fe=class extends T{constructor(e={}){super(e,ue),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};de=fe,w.EndOfContent=de,fe.NAME=g;var pe,me=class extends T{constructor(e={}){super(e,x),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push(`Non-zero length of value block for Null type`),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let e=new Uint8Array(n);e[0]=5,e[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};pe=me,w.Null=pe,me.NAME=`NULL`;var he=class extends y(x){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),this.valueHexView=t.valueHex?i.BufferSourceConverter.toUint8Array(t.valueHex):new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let r=i.BufferSourceConverter.toUint8Array(e);return c(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push(`Boolean value encoded in more then 1 octet`),this.isHexOnly=!0,a.utilDecodeTC.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};he.NAME=`BooleanValueBlock`;var F,ge=class extends T{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,he),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};F=ge,w.Boolean=F,ge.NAME=`BOOLEAN`;var _e=class extends y(se){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=se.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===g){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==_)return this.error=`OCTET STRING may consists of OCTET STRINGs only`,-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,n),this.blockLength=n;return i}toBER(e,t){return this.isConstructed?se.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};_e.NAME=`OctetStringValueBlock`;var I,ve=class extends T{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},_e),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let e=r??M(),t=N(i,0,i.byteLength,e);t.offset!==-1&&t.offset===n&&(this.valueBlock.value=[t.result])}}catch{}}return super.fromBER(e,t,n,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?le.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${i.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof I&&e.push(t.valueBlock.valueHexView);return i.BufferSourceConverter.concat(e)}};I=ve,w.OctetString=I,ve.NAME=_;var L=class extends y(se){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,r){if(!n)return t;let a=-1;if(this.isConstructed){if(a=se.prototype.fromBER.call(this,e,t,n,r),a===-1)return a;for(let e of this.value){let t=e.constructor.NAME;if(t===g){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==v)return this.error=`BIT STRING may consists of BIT STRINGs only`,-1;let n=e.valueBlock;if(this.unusedBits>0&&n.unusedBits>0)return this.error=`Using of "unused bits" inside constructive BIT STRING allowed for least one only`,-1;this.unusedBits=n.unusedBits}return a}let o=i.BufferSourceConverter.toUint8Array(e);if(!c(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error=`Unused bits for BitString must be in range 0-7`,-1;if(!this.unusedBits){let e=s.subarray(1);try{if(e.byteLength){let t=r??M(),i=N(e,0,e.byteLength,t);i.offset!==-1&&i.offset===n-1&&(this.value=[i.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return se.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let e=new Uint8Array(1);return e[0]=0,e.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};L.NAME=`BitStringValueBlock`;var ye,be=class extends T{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},L),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return le.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let n of t)e.push(n.toString(2).padStart(8,`0`));let n=e.join(``);return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ye=be,w.BitString=ye,be.NAME=v;var xe;function Se(e,t){let n=new Uint8Array([0]),r=new Uint8Array(e),i=new Uint8Array(t),o=r.slice(0),s=o.length-1,c=i.slice(0),l=c.length-1,u=0,d=l<s?s:l,f=0;for(let e=d;e>=0;e--,f++){switch(!0){case f<c.length:u=o[s-f]+c[l-f]+n[0];break;default:u=o[s-f]+n[0]}switch(n[0]=u/10,!0){case f>=o.length:o=a.utilConcatView(new Uint8Array([u%10]),o);break;default:o[s-f]=u%10}}return n[0]>0&&(o=a.utilConcatView(n,o)),o}function R(e){if(e>=u.length)for(let t=u.length;t<=e;t++){let e=new Uint8Array([0]),n=u[t-1].slice(0);for(let t=n.length-1;t>=0;t--){let r=new Uint8Array([(n[t]<<1)+e[0]]);e[0]=r[0]/10,n[t]=r[0]%10}e[0]>0&&(n=a.utilConcatView(e,n)),u.push(n)}return u[e]}function z(e,t){let n=0,r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l,u=0;for(let e=c;e>=0;e--,u++)switch(l=a[o-u]-s[c-u]-n,!0){case l<0:n=1,a[o-u]=l+10;break;default:n=0,a[o-u]=l}if(n>0)for(let e=o-c+1;e>=0;e--,u++)if(l=a[o-u]-n,l<0)n=1,a[o-u]=l+10;else{n=0,a[o-u]=l;break}return a.slice()}var Ce=class extends y(x){setValueHex(){this.valueHexView.length>=4?(this.warnings.push(`Too big Integer for decoding, hex only`),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=a.utilDecodeTC.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(a.utilEncodeTC(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case!!(t[0]&128):{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case t[0]===0&&!(t[1]&128):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a=``,o=!1;for(let o=i.byteLength-1;o>=0;o--){r=i[o];for(let i=0;i<8;i++){if((r&1)==1)switch(n){case e:t=z(R(n),t),a=`-`;break;default:t=Se(t,R(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=d.charAt(t[e]));return o===!1&&(a+=d.charAt(0)),a}};xe=Ce,Ce.NAME=`IntegerValueBlock`,Object.defineProperty(xe.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var we,Te=class extends T{constructor(e={}){super(e,Ce),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return o(),BigInt(this.valueBlock.toString())}static fromBigInt(e){o();let t=BigInt(e),n=new l,r=t.toString(16).replace(/^-/,``),a=new Uint8Array(i.Convert.FromHex(r));if(t<0){let e=new Uint8Array(a.length+(a[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${i.Convert.ToHex(e)}`)+t,o=i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(r.toString(16)));o[0]|=128,n.write(o)}else a[0]&128&&n.write(new Uint8Array([0])),n.write(a);return new we({valueHex:n.final()})}convertToDER(){let e=new we({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new we({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};we=Te,w.Integer=we,Te.NAME=`INTEGER`;var Ee,De=class extends Te{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Ee=De,w.Enumerated=Ee,De.NAME=`ENUMERATED`;var Oe=class extends y(x){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=o[e]&127,this.blockLength++,o[e]&128);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,o[this.blockLength-1]&128?(this.error=`End of input reached before message was fully decoded`,-1):(this.valueHexView[0]===0&&this.warnings.push(`Needlessly long format of SID encoding`),this.blockLength<=8?this.valueDec=a.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){o();let t=BigInt(e).toString(2);for(;t.length%7;)t=`0`+t;let n=new Uint8Array(t.length/7);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*7,e*7+7),2)+(e+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=a.utilToBase(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,m;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n}toString(){let e=``;if(this.isHexOnly)e=i.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e=`0.`:this.valueDec<=79?(e=`1.`,t-=40):(e=`2.`,t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Oe.NAME=`sidBlock`;var B=class extends x{constructor({value:e=``,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Oe;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.value.length===0&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,m;t.push(r)}return s(t)}fromString(e){this.value=[];let t=0,n=0,r=``,i=!1;do if(n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1,i){let e=this.value[0],t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:this.value=[];return}let n=parseInt(r,10);if(isNaN(n))return;e.valueDec=n+t,i=!1}else{let e=new Oe;if(r>2**53-1)o(),e.valueBigInt=BigInt(r);else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(n!==-1)}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};B.NAME=`ObjectIdentifierValueBlock`;var ke,V=class extends T{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,B),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};ke=V,w.ObjectIdentifier=ke,V.NAME=`OBJECT IDENTIFIER`;var Ae=class extends y(b){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=o[e]&127,this.blockLength++,o[e]&128);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,o[this.blockLength-1]&128?(this.error=`End of input reached before message was fully decoded`,-1):(this.valueHexView[0]===0&&this.warnings.push(`Needlessly long format of SID encoding`),this.blockLength<=8?this.valueDec=a.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=a.utilToBase(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,m;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n.buffer}toString(){let e=``;return e=this.isHexOnly?i.Convert.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ae.NAME=`relativeSidBlock`;var je=class extends x{constructor({value:e=``,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Ae;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e,t){let n=[];for(let t=0;t<this.value.length;t++){let r=this.value[t].toBER(e);if(r.byteLength===0)return this.error=this.value[t].error,m;n.push(r)}return s(n)}fromString(e){this.value=[];let t=0,n=0,r=``;do{n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1;let i=new Ae;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};je.NAME=`RelativeObjectIdentifierValueBlock`;var Me,Ne=class extends T{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,je),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Me=Ne,w.RelativeObjectIdentifier=Me,Ne.NAME=`RelativeObjectIdentifier`;var Pe,Fe=class extends le{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Pe=Fe,w.Sequence=Pe,Fe.NAME=`SEQUENCE`;var Ie,Le=class extends le{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Ie=Le,w.Set=Ie,Le.NAME=`SET`;var Re=class extends y(x){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=``}toJSON(){return{...super.toJSON(),value:this.value}}};Re.NAME=`StringValueBlock`;var ze=class extends Re{};ze.NAME=`SimpleStringValueBlock`;var H=class extends D{constructor({...e}={}){super(e,ze)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,i.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e}};H.NAME=`SIMPLE STRING`;var Be=class extends H{fromBuffer(e){this.valueBlock.valueHexView=i.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=i.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=i.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(i.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Be.NAME=`Utf8StringValueBlock`;var U,W=class extends Be{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};U=W,w.Utf8String=U,W.NAME=`UTF8String`;var Ve=class extends H{fromBuffer(e){this.valueBlock.value=i.Convert.ToUtf16String(e),this.valueBlock.valueHexView=i.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(i.Convert.FromUtf16String(e))}};Ve.NAME=`BmpStringValueBlock`;var He,Ue=class extends Ve{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};He=Ue,w.BmpString=He,Ue.NAME=`BMPString`;var We=class extends H{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let e=0;e<n.length;e+=4)n[e]=n[e+3],n[e+1]=n[e+2],n[e+2]=0,n[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let t=a.utilToBase(e.charCodeAt(r),8),i=new Uint8Array(t);if(i.length>4)continue;let o=4-i.length;for(let e=i.length-1;e>=0;e--)n[r*4+e+o]=i[e]}this.valueBlock.value=e}};We.NAME=`UniversalStringValueBlock`;var Ge,Ke=class extends We{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Ge=Ke,w.UniversalString=Ge,Ke.NAME=`UniversalString`;var qe,Je=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};qe=Je,w.NumericString=qe,Je.NAME=`NumericString`;var G,Ye=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};G=Ye,w.PrintableString=G,Ye.NAME=`PrintableString`;var Xe,Ze=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Xe=Ze,w.TeletexString=Xe,Ze.NAME=`TeletexString`;var Qe,$e=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Qe=$e,w.VideotexString=Qe,$e.NAME=`VideotexString`;var et,tt=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};et=tt,w.IA5String=et,tt.NAME=`IA5String`;var nt,rt=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};nt=rt,w.GraphicString=nt,rt.NAME=`GraphicString`;var it,at=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};it=at,w.VisibleString=it,at.NAME=`VisibleString`;var ot,K=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ot=K,w.GeneralString=ot,K.NAME=`GeneralString`;var lt,ut=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};lt=ut,w.CharacterString=lt,ut.NAME=`CharacterString`;var dt,ft=class extends at{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,i.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(t===null){this.error=`Wrong input string for conversion`;return}let n=parseInt(t[1],10);this.year=n>=50?1900+n:2e3+n,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e=`iso`){if(e===`iso`){let e=Array(7);return e[0]=a.padNumber(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=a.padNumber(this.month,2),e[2]=a.padNumber(this.day,2),e[3]=a.padNumber(this.hour,2),e[4]=a.padNumber(this.minute,2),e[5]=a.padNumber(this.second,2),e[6]=`Z`,e.join(``)}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};dt=ft,w.UTCTime=dt,ft.NAME=`UTCTime`;var pt,mt=class extends ft{constructor(e={}){super(e),this.millisecond??=0,this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n=``,r=``,i=0,a,o=0,s=0;if(e[e.length-1]===`Z`)n=e.substring(0,e.length-1),t=!0;else{let t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw Error(`Wrong input string for conversion`);n=e}if(t){if(n.indexOf(`+`)!==-1||n.indexOf(`-`)!==-1)throw Error(`Wrong input string for conversion`)}else{let e=1,t=n.indexOf(`+`),r=``;if(t===-1&&(t=n.indexOf(`-`),e=-1),t!==-1){if(r=n.substring(t+1),n=n.substring(0,t),r.length!==2&&r.length!==4)throw Error(`Wrong input string for conversion`);let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);if(o=e*i,r.length===4){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);s=e*i}}}let c=n.indexOf(`.`);if(c===-1&&(c=n.indexOf(`,`)),c!==-1){let e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw Error(`Wrong input string for conversion`);i=e.valueOf(),r=n.substring(0,c)}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/gi,c!==-1)throw Error(`Wrong input string for conversion`);break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw Error(`Wrong input string for conversion`)}let l=a.exec(r);if(l===null)throw Error(`Wrong input string for conversion`);for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+s;break;case 6:this.second=parseInt(l[e],10);break;default:throw Error(`Wrong input string for conversion`)}if(t===!1){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e=`iso`){if(e===`iso`){let e=[];return e.push(a.padNumber(this.year,4)),e.push(a.padNumber(this.month,2)),e.push(a.padNumber(this.day,2)),e.push(a.padNumber(this.hour,2)),e.push(a.padNumber(this.minute,2)),e.push(a.padNumber(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(a.padNumber(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};pt=mt,w.GeneralizedTime=pt,mt.NAME=`GeneralizedTime`;var ht,gt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};ht=gt,w.DATE=ht,gt.NAME=`DATE`;var _t,vt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};_t=vt,w.TimeOfDay=_t,vt.NAME=`TimeOfDay`;var yt,bt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};yt=bt,w.DateTime=yt,bt.NAME=`DateTime`;var xt,St=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};xt=St,w.Duration=xt,St.NAME=`Duration`;var Ct,wt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ct=wt,w.TIME=Ct,wt.NAME=`TIME`;var Tt=class{constructor({name:e=``,optional:t=!1}={}){this.name=e,this.optional=t}},Et=class extends Tt{constructor({value:e=[],...t}={}){super(t),this.value=e}},Dt=class extends Tt{constructor({value:e=new Tt,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Ot=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=i.BufferSourceConverter.toUint8Array(e)}constructor({data:e=h}={}){this.dataView=i.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,n){let r=t+n;return this.dataView=i.BufferSourceConverter.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function kt(e,t,n){if(n instanceof Et){for(let r of n.value)if(kt(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(f)&&(e.name=n.name),e}}if(n instanceof Tt)return n.hasOwnProperty(f)&&(e[n.name]=t),{verified:!0,result:e};if(!(e instanceof Object))return{verified:!1,result:{error:`Wrong root object`}};if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 data`}};if(!(n instanceof Object)||!(`idBlock`in n)||!(`fromBER`in n.idBlock)||!(`toBER`in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:`Error encoding idBlock for ASN.1 schema`}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:`Error decoding idBlock for ASN.1 schema`}};if(n.idBlock.hasOwnProperty(`tagClass`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(`tagNumber`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(`isConstructed`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(`isHexOnly`in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(n.idBlock.isHexOnly){if(!(p in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.valueHexView,i=t.idBlock.valueHexView;if(r.length!==i.length)return{verified:!1,result:e};for(let t=0;t<r.length;t++)if(r[t]!==i[1])return{verified:!1,result:e}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(e[n.name]=t)),n instanceof w.Constructed){let r=0,i={verified:!1,result:{error:`Unknown error`}},a=n.valueBlock.value.length;if(a>0&&n.valueBlock.value[0]instanceof Dt&&(a=t.valueBlock.value.length),a===0)return{verified:!0,result:e};if(t.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let t=!0;for(let e=0;e<n.valueBlock.value.length;e++)t&&=n.valueBlock.value[e].optional||!1;return t?{verified:!0,result:e}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),e.error=`Inconsistent object length`,{verified:!1,result:e})}for(let o=0;o<a;o++)if(o-r>=t.valueBlock.value.length){if(n.valueBlock.value[o].optional===!1){let t={verified:!1,result:e};return e.error=`Inconsistent length between ASN.1 data and schema`,n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof Dt){if(i=kt(e,t.valueBlock.value[o],n.valueBlock.value[0].value),i.verified===!1){if(n.valueBlock.value[0].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),i}if(f in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=`local`in n.valueBlock.value[0]&&n.valueBlock.value[0].local?t:e,r[n.valueBlock.value[0].name]===void 0&&(r[n.valueBlock.value[0].name]=[]),r[n.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=kt(e,t.valueBlock.value[o-r],n.valueBlock.value[o]),i.verified===!1){if(n.valueBlock.value[o].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),i}if(i.verified===!1){let t={verified:!1,result:e};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&p in t.valueBlock){let r=ae(t.valueBlock.valueHexView);if(r.offset===-1){let t={verified:!1,result:r.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}return kt(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function q(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=ae(i.BufferSourceConverter.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:kt(n.result,n.result,t)}e.Any=Tt,e.BaseBlock=T,e.BaseStringBlock=D,e.BitString=be,e.BmpString=Ue,e.Boolean=ge,e.CharacterString=ut,e.Choice=Et,e.Constructed=le,e.DATE=gt,e.DEFAULT_MAX_CONTENT_LENGTH=j,e.DEFAULT_MAX_DEPTH=100,e.DEFAULT_MAX_NODES=ee,e.DateTime=bt,e.Duration=St,e.EndOfContent=fe,e.Enumerated=De,e.GeneralString=K,e.GeneralizedTime=mt,e.GraphicString=rt,e.HexBlock=y,e.IA5String=tt,e.Integer=Te,e.Null=me,e.NumericString=Je,e.ObjectIdentifier=V,e.OctetString=ve,e.Primitive=A,e.PrintableString=Ye,e.RawData=Ot,e.RelativeObjectIdentifier=Ne,e.Repeated=Dt,e.Sequence=Fe,e.Set=Le,e.TIME=wt,e.TeletexString=Ze,e.TimeOfDay=vt,e.UTCTime=ft,e.UniversalString=Ke,e.Utf8String=W,e.ValueBlock=x,e.VideotexString=$e,e.ViewWriter=l,e.VisibleString=at,e.compareSchema=kt,e.fromBER=P,e.verifySchema=q})),ut=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isArrayBuffer=o,e.isSharedArrayBuffer=s,e.isArrayBufferLike=c,e.isArrayBufferView=l,e.isBufferSource=u,e.assertBufferSource=d,e.toUint8Array=f,e.toUint8ArrayCopy=p,e.toArrayBuffer=m,e.toArrayBufferLike=h,e.toView=g,e.toViewCopy=_;function t(e){return Object.prototype.toString.call(e)}function n(e){return e===DataView||e.prototype instanceof DataView}function r(e){return n(e)?1:e.BYTES_PER_ELEMENT??1}function i(e){if(ArrayBuffer.isView(e))return!0;if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.byteOffset==`number`&&typeof t.byteLength==`number`&&c(t.buffer)}function a(e){let t=f(e),n=new Uint8Array(t.byteLength);return n.set(t),n}function o(e){return t(e)===`[object ArrayBuffer]`}function s(e){return typeof SharedArrayBuffer<`u`&&t(e)===`[object SharedArrayBuffer]`}function c(e){return o(e)||s(e)}function l(e){return i(e)}function u(e){return c(e)||l(e)}function d(e){if(!u(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function f(e){return d(e),c(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function p(e){return a(e)}function m(e){if(d(e),o(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(f(e)),t}function h(e){return d(e),c(e)?e:e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:a(e).buffer}function g(e,t){if(d(e),ArrayBuffer.isView(e)&&e.constructor===t)return e;let i=f(e),a=r(t);if(i.byteOffset%a!==0||i.byteLength%a!==0)throw RangeError(`Cannot create ${t.name} over unaligned byte range`);return n(t)?new t(i.buffer,i.byteOffset,i.byteLength):new t(i.buffer,i.byteOffset,i.byteLength/a)}function _(e,t){return g(p(e),t)}})),dt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.concatToUint8Array=n,e.concat=r;let t=ut();function n(e){let n=[],r=0;for(let i of e){let e=(0,t.toUint8Array)(i);n.push(e),r+=e.byteLength}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return i}function r(e,r,...i){let a,o;typeof r==`function`?(a=Array.from(e),o=r):(0,t.isBufferSource)(e)?a=[e,r,...i].filter(t.isBufferSource):(a=Array.from(e),r&&a.push(r),a.push(...i));let s=n(a);return o?(0,t.toView)(s,o):s.buffer}})),ft=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.equal=n;let t=ut();function n(e,n,r={}){let i=(0,t.toUint8Array)(e),a=(0,t.toUint8Array)(n);if(!r.constantTime&&i.byteLength!==a.byteLength)return!1;let o=Math.max(i.byteLength,a.byteLength),s=i.byteLength^a.byteLength;for(let e=0;e<o;e++)s|=(i[e]??0)^(a[e]??0);return s===0}})),pt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.indexOf=u,e.lastIndexOf=d,e.includes=f,e.startsWith=p,e.endsWith=m,e.slice=h,e.tail=g,e.copy=_,e.compare=v;let t=ut();function n(e,t,n){let r=Number.isFinite(e)?Math.trunc(e):t;return r<=0?0:r>=n?n:r}function r(e,t){let r=n(t?.start,0,e),i=n(t?.end,e,e);return i>=r?[r,i]:[r,r]}function i(e,t){let r=n(t?.start,e,e),i=n(t?.end,0,e);return r>=i?[i,r]:[r,r]}function a(e,t,n){let r=Number.isFinite(e)?Math.trunc(e):t;return r<0?Math.max(n+r,0):r>n?n:r}function o(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function s(e){return new TextEncoder().encode(e)}function c(e,n){return typeof e==`string`?n?.encoding===`utf8`?s(e):o(e):(0,t.toUint8Array)(e)}function l(e,t,n){for(let r=0;r<t.byteLength;r++)if(e[n+r]!==t[r])return!1;return!0}function u(e,n,i){let a=(0,t.toUint8Array)(e),o=c(n,i),[s,u]=r(a.byteLength,i);if(o.byteLength===0)return s;let d=u-o.byteLength;if(d<s)return-1;for(let e=s;e<=d;e++)if(l(a,o,e))return e;return-1}function d(e,n,r){let a=(0,t.toUint8Array)(e),o=c(n,r),[s,u]=i(a.byteLength,r);if(o.byteLength===0)return u;let d=u-o.byteLength;if(d<s)return-1;for(let e=d;e>=s;e--)if(l(a,o,e))return e;return-1}function f(e,t,n){return u(e,t,n)!==-1}function p(e,n,r){let i=(0,t.toUint8Array)(e),a=c(n,r);return a.byteLength>i.byteLength?!1:l(i,a,0)}function m(e,n,r){let i=(0,t.toUint8Array)(e),a=c(n,r);return a.byteLength>i.byteLength?!1:l(i,a,i.byteLength-a.byteLength)}function h(e,n,r){let i=(0,t.toUint8Array)(e),o=a(n,0,i.byteLength),s=a(r,i.byteLength,i.byteLength);return s<=o?i.subarray(o,o):i.subarray(o,s)}function g(e,n){let r=(0,t.toUint8Array)(e),i=Number.isFinite(n)?Math.max(0,Math.trunc(n)):0;return i>=r.byteLength?r:r.subarray(r.byteLength-i)}function _(e){return(0,t.toUint8ArrayCopy)(e)}function v(e,n){let r=(0,t.toUint8Array)(e),i=(0,t.toUint8Array)(n),a=Math.min(r.byteLength,i.byteLength);for(let e=0;e<a;e++){if(r[e]<i[e])return-1;if(r[e]>i[e])return 1}return r.byteLength<i.byteLength?-1:+(r.byteLength>i.byteLength)}})),mt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.tail=e.startsWith=e.slice=e.lastIndexOf=e.indexOf=e.includes=e.endsWith=e.copy=e.compare=e.equal=e.concatToUint8Array=e.concat=e.toViewCopy=e.toView=e.toUint8ArrayCopy=e.toUint8Array=e.toArrayBufferLike=e.toArrayBuffer=e.isSharedArrayBuffer=e.isBufferSource=e.isArrayBufferView=e.isArrayBufferLike=e.isArrayBuffer=e.assertBufferSource=void 0;var t=ut();Object.defineProperty(e,"assertBufferSource",{enumerable:!0,get:function(){return t.assertBufferSource}}),Object.defineProperty(e,"isArrayBuffer",{enumerable:!0,get:function(){return t.isArrayBuffer}}),Object.defineProperty(e,"isArrayBufferLike",{enumerable:!0,get:function(){return t.isArrayBufferLike}}),Object.defineProperty(e,"isArrayBufferView",{enumerable:!0,get:function(){return t.isArrayBufferView}}),Object.defineProperty(e,"isBufferSource",{enumerable:!0,get:function(){return t.isBufferSource}}),Object.defineProperty(e,"isSharedArrayBuffer",{enumerable:!0,get:function(){return t.isSharedArrayBuffer}}),Object.defineProperty(e,"toArrayBuffer",{enumerable:!0,get:function(){return t.toArrayBuffer}}),Object.defineProperty(e,"toArrayBufferLike",{enumerable:!0,get:function(){return t.toArrayBufferLike}}),Object.defineProperty(e,"toUint8Array",{enumerable:!0,get:function(){return t.toUint8Array}}),Object.defineProperty(e,"toUint8ArrayCopy",{enumerable:!0,get:function(){return t.toUint8ArrayCopy}}),Object.defineProperty(e,"toView",{enumerable:!0,get:function(){return t.toView}}),Object.defineProperty(e,"toViewCopy",{enumerable:!0,get:function(){return t.toViewCopy}});var n=dt();Object.defineProperty(e,"concat",{enumerable:!0,get:function(){return n.concat}}),Object.defineProperty(e,"concatToUint8Array",{enumerable:!0,get:function(){return n.concatToUint8Array}});var r=ft();Object.defineProperty(e,"equal",{enumerable:!0,get:function(){return r.equal}});var i=pt();Object.defineProperty(e,"compare",{enumerable:!0,get:function(){return i.compare}}),Object.defineProperty(e,"copy",{enumerable:!0,get:function(){return i.copy}}),Object.defineProperty(e,"endsWith",{enumerable:!0,get:function(){return i.endsWith}}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return i.includes}}),Object.defineProperty(e,"indexOf",{enumerable:!0,get:function(){return i.indexOf}}),Object.defineProperty(e,"lastIndexOf",{enumerable:!0,get:function(){return i.lastIndexOf}}),Object.defineProperty(e,"slice",{enumerable:!0,get:function(){return i.slice}}),Object.defineProperty(e,"startsWith",{enumerable:!0,get:function(){return i.startsWith}}),Object.defineProperty(e,"tail",{enumerable:!0,get:function(){return i.tail}})})),ht=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnPropTypes=e.AsnTypeTypes=void 0;var t;(function(e){e[e.Sequence=0]=`Sequence`,e[e.Set=1]=`Set`,e[e.Choice=2]=`Choice`})(t||(e.AsnTypeTypes=t={}));var n;(function(e){e[e.Any=1]=`Any`,e[e.Boolean=2]=`Boolean`,e[e.OctetString=3]=`OctetString`,e[e.BitString=4]=`BitString`,e[e.Integer=5]=`Integer`,e[e.Enumerated=6]=`Enumerated`,e[e.ObjectIdentifier=7]=`ObjectIdentifier`,e[e.Utf8String=8]=`Utf8String`,e[e.BmpString=9]=`BmpString`,e[e.UniversalString=10]=`UniversalString`,e[e.NumericString=11]=`NumericString`,e[e.PrintableString=12]=`PrintableString`,e[e.TeletexString=13]=`TeletexString`,e[e.VideotexString=14]=`VideotexString`,e[e.IA5String=15]=`IA5String`,e[e.GraphicString=16]=`GraphicString`,e[e.VisibleString=17]=`VisibleString`,e[e.GeneralString=18]=`GeneralString`,e[e.CharacterString=19]=`CharacterString`,e[e.UTCTime=20]=`UTCTime`,e[e.GeneralizedTime=21]=`GeneralizedTime`,e[e.DATE=22]=`DATE`,e[e.TimeOfDay=23]=`TimeOfDay`,e[e.DateTime=24]=`DateTime`,e[e.Duration=25]=`Duration`,e[e.TIME=26]=`TIME`,e[e.Null=27]=`Null`})(n||(e.AsnPropTypes=n={}))})),gt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BitString=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt();e.BitString=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if((0,r.isBufferSource)(e))this.unusedBits=t,this.value=(0,r.toArrayBuffer)(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof n.BitString))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=(0,r.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new n.BitString({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new n.BitString({name:e})}toNumber(){let e=``,t=new Uint8Array(this.value);for(let n of t)e+=n.toString(2).padStart(8,`0`);return e=e.split(``).reverse().join(``),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,`0`)),parseInt(e,2)}fromNumber(e){let t=e.toString(2),n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;let r=new Uint8Array(n);t=t.padStart(n<<3,`0`).split(``).reverse().join(``);let i=0;for(;i<n;)r[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=r.buffer}}})),_t=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OctetString=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt();e.OctetString=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):(0,r.isBufferSource)(e)?(0,r.toArrayBuffer)(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof n.OctetString))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=(0,r.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new n.OctetString({valueHex:this.buffer})}toSchema(e){return new n.OctetString({name:e})}}})),vt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0});let n=(K(),t(B));n.__exportStar(gt(),e),n.__exportStar(_t(),e)})),yt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnNullConverter=e.AsnGeneralizedTimeConverter=e.AsnUTCTimeConverter=e.AsnCharacterStringConverter=e.AsnGeneralStringConverter=e.AsnVisibleStringConverter=e.AsnGraphicStringConverter=e.AsnIA5StringConverter=e.AsnVideotexStringConverter=e.AsnTeletexStringConverter=e.AsnPrintableStringConverter=e.AsnNumericStringConverter=e.AsnUniversalStringConverter=e.AsnBmpStringConverter=e.AsnUtf8StringConverter=e.AsnConstructedOctetStringConverter=e.AsnOctetStringConverter=e.AsnBooleanConverter=e.AsnObjectIdentifierConverter=e.AsnBitStringConverter=e.AsnIntegerBigIntConverter=e.AsnIntegerArrayBufferConverter=e.AsnEnumeratedConverter=e.AsnIntegerConverter=e.AsnAnyConverter=void 0,e.defaultConverter=s;let n=(K(),t(B)).__importStar(lt()),r=mt(),i=ht(),a=vt();e.AsnAnyConverter={fromASN:e=>e instanceof n.Null?null:(0,r.toArrayBuffer)(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new n.Null;let t=n.fromBER(e);if(t.result.error)throw Error(t.result.error);return t.result}},e.AsnIntegerConverter={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new n.Integer({value:+e})},e.AsnEnumeratedConverter={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new n.Enumerated({value:e})},e.AsnIntegerArrayBufferConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.Integer({valueHex:e})},e.AsnIntegerBigIntConverter={fromASN:e=>e.toBigInt(),toASN:e=>n.Integer.fromBigInt(e)},e.AsnBitStringConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.BitString({valueHex:e})},e.AsnObjectIdentifierConverter={fromASN:e=>e.valueBlock.toString(),toASN:e=>new n.ObjectIdentifier({value:e})},e.AsnBooleanConverter={fromASN:e=>e.valueBlock.value,toASN:e=>new n.Boolean({value:e})},e.AsnOctetStringConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.OctetString({valueHex:e})},e.AsnConstructedOctetStringConverter={fromASN:e=>new a.OctetString(e.getValue()),toASN:e=>e.toASN()};function o(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}e.AsnUtf8StringConverter=o(n.Utf8String),e.AsnBmpStringConverter=o(n.BmpString),e.AsnUniversalStringConverter=o(n.UniversalString),e.AsnNumericStringConverter=o(n.NumericString),e.AsnPrintableStringConverter=o(n.PrintableString),e.AsnTeletexStringConverter=o(n.TeletexString),e.AsnVideotexStringConverter=o(n.VideotexString),e.AsnIA5StringConverter=o(n.IA5String),e.AsnGraphicStringConverter=o(n.GraphicString),e.AsnVisibleStringConverter=o(n.VisibleString),e.AsnGeneralStringConverter=o(n.GeneralString),e.AsnCharacterStringConverter=o(n.CharacterString),e.AsnUTCTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new n.UTCTime({valueDate:e})},e.AsnGeneralizedTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new n.GeneralizedTime({valueDate:e})},e.AsnNullConverter={fromASN:()=>null,toASN:()=>new n.Null};function s(t){switch(t){case i.AsnPropTypes.Any:return e.AsnAnyConverter;case i.AsnPropTypes.BitString:return e.AsnBitStringConverter;case i.AsnPropTypes.BmpString:return e.AsnBmpStringConverter;case i.AsnPropTypes.Boolean:return e.AsnBooleanConverter;case i.AsnPropTypes.CharacterString:return e.AsnCharacterStringConverter;case i.AsnPropTypes.Enumerated:return e.AsnEnumeratedConverter;case i.AsnPropTypes.GeneralString:return e.AsnGeneralStringConverter;case i.AsnPropTypes.GeneralizedTime:return e.AsnGeneralizedTimeConverter;case i.AsnPropTypes.GraphicString:return e.AsnGraphicStringConverter;case i.AsnPropTypes.IA5String:return e.AsnIA5StringConverter;case i.AsnPropTypes.Integer:return e.AsnIntegerConverter;case i.AsnPropTypes.Null:return e.AsnNullConverter;case i.AsnPropTypes.NumericString:return e.AsnNumericStringConverter;case i.AsnPropTypes.ObjectIdentifier:return e.AsnObjectIdentifierConverter;case i.AsnPropTypes.OctetString:return e.AsnOctetStringConverter;case i.AsnPropTypes.PrintableString:return e.AsnPrintableStringConverter;case i.AsnPropTypes.TeletexString:return e.AsnTeletexStringConverter;case i.AsnPropTypes.UTCTime:return e.AsnUTCTimeConverter;case i.AsnPropTypes.UniversalString:return e.AsnUniversalStringConverter;case i.AsnPropTypes.Utf8String:return e.AsnUtf8StringConverter;case i.AsnPropTypes.VideotexString:return e.AsnVideotexStringConverter;case i.AsnPropTypes.VisibleString:return e.AsnVisibleStringConverter;default:return null}}})),bt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isConvertible=t,e.isTypeOfArray=n,e.isArrayEqual=r;function t(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:t(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function n(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||n(t)}return!1}function r(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}})),xt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSchemaStorage=void 0;let n=(K(),t(B)).__importStar(lt()),r=ht(),i=bt();e.AsnSchemaStorage=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let n=this.items.get(e);if(!n)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let t=this.get(e);t.schema||=this.create(e,!0)}createDefault(e){let t={type:r.AsnTypeTypes.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(t,n),t.items=Object.assign({},t.items,n.items)),t}create(e,t){let a=this.items.get(e)||this.createDefault(e),o=[];for(let e in a.items){let s=a.items[e],c=t?e:``,l;if(typeof s.type==`number`){let e=r.AsnPropTypes[s.type],t=n[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);l=new t({name:c})}else(0,i.isConvertible)(s.type)?l=new s.type().toSchema(c):s.optional?this.get(s.type).type===r.AsnTypeTypes.Choice?l=new n.Any({name:c}):(l=this.create(s.type,!1),l.name=c):l=new n.Any({name:c});let u=!!s.optional||s.defaultValue!==void 0;if(s.repeated&&(l.name=``,l=new(s.repeated===`set`?n.Set:n.Sequence)({name:``,value:[new n.Repeated({name:c,value:l})]})),s.context!==null&&s.context!==void 0){if(s.implicit){if(typeof s.type==`number`||(0,i.isConvertible)(s.type)){let e=s.repeated?n.Constructed:n.Primitive;o.push(new e({name:c,optional:u,idBlock:{tagClass:3,tagNumber:s.context}}))}else{this.cache(s.type);let e=!!s.repeated,t=e?l:this.get(s.type,!0).schema;t=`valueBlock`in t?t.valueBlock.value:t.value,o.push(new n.Constructed({name:e?``:c,optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:t}))}}else o.push(new n.Constructed({optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:[l]}))}else l.optional=u,o.push(l)}switch(a.type){case r.AsnTypeTypes.Sequence:return new n.Sequence({value:o,name:``});case r.AsnTypeTypes.Set:return new n.Set({value:o,name:``});case r.AsnTypeTypes.Choice:return new n.Choice({value:o,name:``});default:throw Error(`Unsupported ASN1 type in use`)}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}}})),St=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.schemaStorage=void 0,e.schemaStorage=new(xt()).AsnSchemaStorage})),Ct=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnProp=e.AsnSequenceType=e.AsnSetType=e.AsnChoiceType=e.AsnType=void 0;let n=(K(),t(B)).__importStar(yt()),r=ht(),i=St();e.AsnType=e=>t=>{let n;i.schemaStorage.has(t)?n=i.schemaStorage.get(t):(n=i.schemaStorage.createDefault(t),i.schemaStorage.set(t,n)),Object.assign(n,e)},e.AsnChoiceType=()=>(0,e.AsnType)({type:r.AsnTypeTypes.Choice}),e.AsnSetType=t=>(0,e.AsnType)({type:r.AsnTypeTypes.Set,...t}),e.AsnSequenceType=t=>(0,e.AsnType)({type:r.AsnTypeTypes.Sequence,...t}),e.AsnProp=e=>(t,r)=>{let a;i.schemaStorage.has(t.constructor)?a=i.schemaStorage.get(t.constructor):(a=i.schemaStorage.createDefault(t.constructor),i.schemaStorage.set(t.constructor,a));let o=Object.assign({},e);if(typeof o.type==`number`&&!o.converter){let i=n.defaultConverter(e.type);if(!i)throw Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);o.converter=i}o.raw=e.raw,a.items[r]=o}})),wt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSchemaValidationError=void 0,e.AsnSchemaValidationError=class extends Error{schemas=[]}})),Tt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),(K(),t(B)).__exportStar(wt(),e)})),Et=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnParser=void 0;let n=(K(),t(B)),r=n.__importStar(lt()),i=mt(),a=ht(),o=n.__importStar(yt()),s=Tt(),c=bt(),l=St();e.AsnParser=class{static parse(e,t,n){let a=r.fromBER((0,i.toArrayBuffer)(e),n?.berOptions);if(a.result.error)throw Error(a.result.error);return this.fromASN(a.result,t,n)}static fromASN(e,t,n){try{if((0,c.isConvertible)(t))return new t().fromASN(e);let r=l.schemaStorage.get(t);l.schemaStorage.cache(t);let i=r.schema,a=this.handleChoiceTypes(e,r,t,i,n);if(a?.result)return a.result;a?.targetSchema&&(i=a.targetSchema);let o=this.handleSequenceTypes(e,r,t,i),s=new t;return(0,c.isTypeOfArray)(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof s.AsnSchemaValidationError&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,i,o){if(e.constructor===r.Constructed&&t.type===a.AsnTypeTypes.Choice&&e.idBlock.tagClass===3)for(let i in t.items){let s=t.items[i];if(s.context===e.idBlock.tagNumber&&s.implicit&&typeof s.type==`function`&&l.schemaStorage.has(s.type)){let t=l.schemaStorage.get(s.type);if(t&&t.type===a.AsnTypeTypes.Sequence){let t=new r.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;let r=this.fromASN(t,s.type,o),a=new n;return a[i]=r,{result:a}}}}}else if(e.constructor===r.Constructed&&t.type!==a.AsnTypeTypes.Choice){let n=new r.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let n in t.items)delete e[n];return{targetSchema:n}}return null}static handleSequenceTypes(e,t,n,i){if(t.type===a.AsnTypeTypes.Sequence){let t=r.compareSchema({},e,i);if(!t.verified)throw new s.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=r.compareSchema({},e,i);if(!t.verified)throw new s.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}}static processRepeatedField(e,t,n){let r=e.slice(t);if(r.length===1&&r[0].constructor.name===`Sequence`){let e=r[0];e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value)&&(r=e.valueBlock.value)}if(typeof n.type==`number`){let e=o.defaultConverter(n.type);if(!e)throw Error(`No converter for ASN.1 type ${n.type}`);return r.filter(e=>e&&e.valueBlock).map(t=>{try{return e.fromASN(t)}catch{return}}).filter(e=>e!==void 0)}return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,n.type)}catch{return}}).filter(e=>e!==void 0)}static processPrimitiveField(e,t){let n=o.defaultConverter(t.type);if(!n)throw Error(`No converter for ASN.1 type ${t.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type==`function`&&l.schemaStorage.has(e.type)&&l.schemaStorage.get(e.type).type===a.AsnTypeTypes.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(e){if(e instanceof s.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return{processed:!1};throw e}}static handleArrayTypes(e,t,n,r){if(!(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let i=t.itemType;if(typeof i==`number`){let t=o.defaultConverter(i);if(!t)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,e=>t.fromASN(e))}return n.from(e.valueBlock.value,e=>this.fromASN(e,i,r))}static processSchemaItems(e,t,n,r){for(let i in e.items){let a=t.result[i];if(!a)continue;let o=e.items[i],s=o.type,l;l=typeof s==`number`||(0,c.isConvertible)(s)?this.processPrimitiveSchemaItem(a,o,s,r):this.processComplexSchemaItem(a,o,s,r),l&&typeof l==`object`&&`value`in l&&`raw`in l?(n[i]=l.value,n[`${i}Raw`]=l.raw):n[i]=l}}static processPrimitiveSchemaItem(e,t,n,r){let i=t.converter??((0,c.isConvertible)(n)?new n:null);if(!i)throw Error(`Converter is empty`);return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,r):this.processSinglePrimitiveItem(e,t,n,i,r)}static processRepeatedPrimitiveItem(e,t,n,i){if(t.implicit){let a=new(t.repeated===`sequence`?r.Sequence:r.Set);a.valueBlock=e.valueBlock;let o=r.fromBER(a.toBER(!1),i?.berOptions);if(o.offset===-1)throw Error(`Cannot parse the child item. ${o.result.error}`);if(!(`value`in o.result.valueBlock&&Array.isArray(o.result.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let s=o.result.valueBlock.value;return Array.from(s,e=>n.fromASN(e))}return Array.from(e,e=>n.fromASN(e))}static processSinglePrimitiveItem(e,t,n,i,o){let s=e;if(t.implicit){let e;if((0,c.isConvertible)(n))e=new n().toSchema(``);else{let t=a.AsnPropTypes[n],i=r[t];if(!i)throw Error(`Cannot get '${t}' class from asn1js module`);e=new i}e.valueBlock=s.valueBlock,s=r.fromBER(e.toBER(!1),o?.berOptions).result}return i.fromASN(s)}static processComplexSchemaItem(e,t,n,r){if(t.repeated){if(!Array.isArray(e))throw Error(`Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.`);return Array.from(e,e=>this.fromASN(e,n,r))}{let i=this.handleImplicitTagging(e,t,n);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,n,r)}catch(e){if(e instanceof s.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return;throw e}{let a=this.fromASN(i,n,r);return t.raw?{value:a,raw:e.valueBeforeDecodeView}:a}}}static handleImplicitTagging(e,t,n){if(t.implicit&&typeof t.context==`number`){let t=l.schemaStorage.get(n);if(t.type===a.AsnTypeTypes.Sequence){let t=new r.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}else if(t.type===a.AsnTypeTypes.Set){let t=new r.Set;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}}})),Dt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSerializer=void 0;let n=(K(),t(B)),r=n.__importStar(lt()),i=mt(),a=n.__importStar(yt()),o=ht(),s=bt(),c=St();e.AsnSerializer=class e{static serialize(e){return e instanceof r.BaseBlock?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&(0,s.isConvertible)(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,l=c.schemaStorage.get(n);c.schemaStorage.cache(n);let u=[];if(l.itemType){if(!Array.isArray(t))throw TypeError(`Parameter 1 should be type of Array.`);if(typeof l.itemType==`number`){let e=a.defaultConverter(l.itemType);if(!e)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);u=t.map(t=>e.toASN(t))}else u=t.map(e=>this.toAsnItem({type:l.itemType},`[]`,n,e))}else for(let a in l.items){let o=l.items[a],c=t[a];if(c===void 0||o.defaultValue===c||typeof o.defaultValue==`object`&&typeof c==`object`&&(0,s.isArrayEqual)(this.serialize(o.defaultValue),this.serialize(c)))continue;let d=e.toAsnItem(o,a,n,c);if(typeof o.context==`number`){if(o.implicit){if(!o.repeated&&(typeof o.type==`number`||(0,s.isConvertible)(o.type))){let e={};e.valueHex=d instanceof r.Null?(0,i.toArrayBuffer)(d.valueBeforeDecodeView):d.valueBlock.toBER(),u.push(new r.Primitive({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else u.push(new r.Constructed({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:d.valueBlock.value}))}else u.push(new r.Constructed({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:[d]}))}else o.repeated?u=u.concat(d):u.push(d)}let d;switch(l.type){case o.AsnTypeTypes.Sequence:d=new r.Sequence({value:u});break;case o.AsnTypeTypes.Set:d=new r.Set({value:u});break;case o.AsnTypeTypes.Choice:if(!u[0])throw Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);d=u[0]}return d}static toAsnItem(e,t,n,i){let a;if(typeof e.type==`number`){let s=e.converter;if(!s)throw Error(`Property '${t}' doesn't have converter for type ${o.AsnPropTypes[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(i))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(i,e=>s.toASN(e));a=new(e.repeated===`sequence`?r.Sequence:r.Set)({value:t})}else a=s.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(i,e=>this.toASN(e));a=new(e.repeated===`sequence`?r.Sequence:r.Set)({value:t})}else a=this.toASN(i);return a}}})),Ot=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnArray=void 0,e.AsnArray=class extends Array{constructor(e=[]){if(typeof e==`number`)super(e);else{super();for(let t of e)this.push(t)}}}})),kt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnConvert=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt(),i=Et(),a=Dt();e.AsnConvert=class e{static serialize(e){return a.AsnSerializer.serialize(e)}static parse(e,t,n){return i.AsnParser.parse(e,t,n)}static toString(t,i){let a=(0,r.isBufferSource)(t)?(0,r.toArrayBuffer)(t):e.serialize(t),o=n.fromBER(a,i?.berOptions);if(o.offset===-1)throw Error(`Cannot decode ASN.1 data. ${o.result.error}`);return o.result.toString()}}})),q=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSerializer=e.AsnParser=e.AsnPropTypes=e.AsnTypeTypes=e.AsnSetType=e.AsnSequenceType=e.AsnChoiceType=e.AsnType=e.AsnProp=void 0;let n=(K(),t(B));n.__exportStar(yt(),e),n.__exportStar(vt(),e);var r=Ct();Object.defineProperty(e,"AsnProp",{enumerable:!0,get:function(){return r.AsnProp}}),Object.defineProperty(e,"AsnType",{enumerable:!0,get:function(){return r.AsnType}}),Object.defineProperty(e,"AsnChoiceType",{enumerable:!0,get:function(){return r.AsnChoiceType}}),Object.defineProperty(e,"AsnSequenceType",{enumerable:!0,get:function(){return r.AsnSequenceType}}),Object.defineProperty(e,"AsnSetType",{enumerable:!0,get:function(){return r.AsnSetType}});var i=ht();Object.defineProperty(e,"AsnTypeTypes",{enumerable:!0,get:function(){return i.AsnTypeTypes}}),Object.defineProperty(e,"AsnPropTypes",{enumerable:!0,get:function(){return i.AsnPropTypes}});var a=Et();Object.defineProperty(e,"AsnParser",{enumerable:!0,get:function(){return a.AsnParser}});var o=Dt();Object.defineProperty(e,"AsnSerializer",{enumerable:!0,get:function(){return o.AsnSerializer}}),n.__exportStar(Tt(),e),n.__exportStar(Ot(),e),n.__exportStar(kt(),e)})),At=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.binary=void 0,e.encode=n,e.decode=r,e.is=i;let t=mt();function n(e){let n=(0,t.toUint8Array)(e),r=``;for(let e of n)r+=String.fromCharCode(e);return r}function r(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function i(e){return typeof e==`string`}e.binary={encode:n,decode:r,is:i}})),jt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.hex=e.formats=void 0,e.normalize=m,e.is=h,e.encode=g,e.decode=_,e.parse=v,e.format=y;let t=mt(),n=/^[0-9a-f]$/i,r=[` `,` `,`
83
+ `)}`:`${t} :`}};ce=le,w.Constructed=ce,le.NAME=`CONSTRUCTED`;var F=class extends x{fromBER(e,t,n){return t}toBER(e){return m}};F.override=`EndOfContentValueBlock`;var ue,de=class extends T{constructor(e={}){super(e,F),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};ue=de,w.EndOfContent=ue,de.NAME=g;var fe,pe=class extends T{constructor(e={}){super(e,x),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,n){return this.lenBlock.length>0&&this.warnings.push(`Non-zero length of value block for Null type`),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,t+n>e.byteLength?(this.error=`End of input reached before message was fully decoded (inconsistent offset and length values)`,-1):t+n}toBER(e,t){let n=new ArrayBuffer(2);if(!e){let e=new Uint8Array(n);e[0]=5,e[1]=0}return t&&t.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};fe=pe,w.Null=fe,pe.NAME=`NULL`;var me=class extends y(x){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor({value:e,...t}={}){super(t),this.valueHexView=t.valueHex?i.BufferSourceConverter.toUint8Array(t.valueHex):new Uint8Array(1),e&&(this.value=e)}fromBER(e,t,n){let r=i.BufferSourceConverter.toUint8Array(e);return c(this,r,t,n)?(this.valueHexView=r.subarray(t,t+n),n>1&&this.warnings.push(`Boolean value encoded in more then 1 octet`),this.isHexOnly=!0,a.utilDecodeTC.call(this),this.blockLength=n,t+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};me.NAME=`BooleanValueBlock`;var I,he=class extends T{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,me),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};I=he,w.Boolean=I,he.NAME=`BOOLEAN`;var ge=class extends y(se){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,n,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,i=se.prototype.fromBER.call(this,e,t,n,r),i===-1)return i;for(let e=0;e<this.value.length;e++){let t=this.value[e].constructor.NAME;if(t===g){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only`,-1}if(t!==_)return this.error=`OCTET STRING may consists of OCTET STRINGs only`,-1}}else this.isHexOnly=!0,i=super.fromBER(e,t,n),this.blockLength=n;return i}toBER(e,t){return this.isConstructed?se.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};ge.NAME=`OctetStringValueBlock`;var L,_e=class extends T{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},ge),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,n,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+n);try{if(i.byteLength){let e=r??M(),t=N(i,0,i.byteLength,e);t.offset!==-1&&t.offset===n&&(this.valueBlock.value=[t.result])}}catch{}}return super.fromBER(e,t,n,r)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?le.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${i.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let t of this.valueBlock.value)t instanceof L&&e.push(t.valueBlock.valueHexView);return i.BufferSourceConverter.concat(e)}};L=_e,w.OctetString=L,_e.NAME=_;var R=class extends y(se){constructor({unusedBits:e=0,isConstructed:t=!1,...n}={}){super(n),this.unusedBits=e,this.isConstructed=t,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,n,r){if(!n)return t;let a=-1;if(this.isConstructed){if(a=se.prototype.fromBER.call(this,e,t,n,r),a===-1)return a;for(let e of this.value){let t=e.constructor.NAME;if(t===g){if(this.isIndefiniteForm)break;return this.error=`EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only`,-1}if(t!==v)return this.error=`BIT STRING may consists of BIT STRINGs only`,-1;let n=e.valueBlock;if(this.unusedBits>0&&n.unusedBits>0)return this.error=`Using of "unused bits" inside constructive BIT STRING allowed for least one only`,-1;this.unusedBits=n.unusedBits}return a}let o=i.BufferSourceConverter.toUint8Array(e);if(!c(this,o,t,n))return-1;let s=o.subarray(t,t+n);if(this.unusedBits=s[0],this.unusedBits>7)return this.error=`Unused bits for BitString must be in range 0-7`,-1;if(!this.unusedBits){let e=s.subarray(1);try{if(e.byteLength){let t=r??M(),i=N(e,0,e.byteLength,t);i.offset!==-1&&i.offset===n-1&&(this.value=[i.result])}}catch{}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+n}toBER(e,t){if(this.isConstructed)return se.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let e=new Uint8Array(1);return e[0]=0,e.buffer}let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};R.NAME=`BitStringValueBlock`;var ve,ye=class extends T{constructor({idBlock:e={},lenBlock:t={},...n}={}){n.isConstructed??=!!n.value?.length,super({idBlock:{isConstructed:n.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!n.isIndefiniteForm},...n},R),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,n,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,n,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return le.prototype.onAsciiEncoding.call(this);{let e=[],t=this.valueBlock.valueHexView;for(let n of t)e.push(n.toString(2).padStart(8,`0`));let n=e.join(``);return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ve=ye,w.BitString=ve,ye.NAME=v;var be;function xe(e,t){let n=new Uint8Array([0]),r=new Uint8Array(e),i=new Uint8Array(t),o=r.slice(0),s=o.length-1,c=i.slice(0),l=c.length-1,u=0,d=l<s?s:l,f=0;for(let e=d;e>=0;e--,f++){switch(!0){case f<c.length:u=o[s-f]+c[l-f]+n[0];break;default:u=o[s-f]+n[0]}switch(n[0]=u/10,!0){case f>=o.length:o=a.utilConcatView(new Uint8Array([u%10]),o);break;default:o[s-f]=u%10}}return n[0]>0&&(o=a.utilConcatView(n,o)),o}function Se(e){if(e>=u.length)for(let t=u.length;t<=e;t++){let e=new Uint8Array([0]),n=u[t-1].slice(0);for(let t=n.length-1;t>=0;t--){let r=new Uint8Array([(n[t]<<1)+e[0]]);e[0]=r[0]/10,n[t]=r[0]%10}e[0]>0&&(n=a.utilConcatView(e,n)),u.push(n)}return u[e]}function z(e,t){let n=0,r=new Uint8Array(e),i=new Uint8Array(t),a=r.slice(0),o=a.length-1,s=i.slice(0),c=s.length-1,l,u=0;for(let e=c;e>=0;e--,u++)switch(l=a[o-u]-s[c-u]-n,!0){case l<0:n=1,a[o-u]=l+10;break;default:n=0,a[o-u]=l}if(n>0)for(let e=o-c+1;e>=0;e--,u++)if(l=a[o-u]-n,l<0)n=1,a[o-u]=l+10;else{n=0,a[o-u]=l;break}return a.slice()}var Ce=class extends y(x){setValueHex(){this.valueHexView.length>=4?(this.warnings.push(`Too big Integer for decoding, hex only`),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=a.utilDecodeTC.call(this)))}constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),e!==void 0&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(a.utilEncodeTC(e))}get valueDec(){return this._valueDec}fromDER(e,t,n,r=0){let i=this.fromBER(e,t,n);if(i===-1)return i;let a=this.valueHexView;return a[0]===0&&a[1]&128?this.valueHexView=a.subarray(1):r!==0&&a.length<r&&(r-a.length>1&&(r=a.length+1),this.valueHexView=a.subarray(r-a.length)),i}toDER(e=!1){let t=this.valueHexView;switch(!0){case!!(t[0]&128):{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case t[0]===0&&!(t[1]&128):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,n){let r=super.fromBER(e,t,n);return r===-1||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e=this.valueHexView.length*8-1,t=new Uint8Array(this.valueHexView.length*8/3),n=0,r,i=this.valueHexView,a=``,o=!1;for(let o=i.byteLength-1;o>=0;o--){r=i[o];for(let i=0;i<8;i++){if((r&1)==1)switch(n){case e:t=z(Se(n),t),a=`-`;break;default:t=xe(t,Se(n))}n++,r>>=1}}for(let e=0;e<t.length;e++)t[e]&&(o=!0),o&&(a+=d.charAt(t[e]));return o===!1&&(a+=d.charAt(0)),a}};be=Ce,Ce.NAME=`IntegerValueBlock`,Object.defineProperty(be.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var we,Te=class extends T{constructor(e={}){super(e,Ce),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return o(),BigInt(this.valueBlock.toString())}static fromBigInt(e){o();let t=BigInt(e),n=new l,r=t.toString(16).replace(/^-/,``),a=new Uint8Array(i.Convert.FromHex(r));if(t<0){let e=new Uint8Array(a.length+(a[0]&128?1:0));e[0]|=128;let r=BigInt(`0x${i.Convert.ToHex(e)}`)+t,o=i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(r.toString(16)));o[0]|=128,n.write(o)}else a[0]&128&&n.write(new Uint8Array([0])),n.write(a);return new we({valueHex:n.final()})}convertToDER(){let e=new we({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new we({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};we=Te,w.Integer=we,Te.NAME=`INTEGER`;var Ee,De=class extends Te{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Ee=De,w.Enumerated=Ee,De.NAME=`ENUMERATED`;var Oe=class extends y(x){constructor({valueDec:e=-1,isFirstSid:t=!1,...n}={}){super(n),this.valueDec=e,this.isFirstSid=t}fromBER(e,t,n){if(!n)return t;let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=o[e]&127,this.blockLength++,o[e]&128);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,o[this.blockLength-1]&128?(this.error=`End of input reached before message was fully decoded`,-1):(this.valueHexView[0]===0&&this.warnings.push(`Needlessly long format of SID encoding`),this.blockLength<=8?this.valueDec=a.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}set valueBigInt(e){o();let t=BigInt(e).toString(2);for(;t.length%7;)t=`0`+t;let n=new Uint8Array(t.length/7);for(let e=0;e<n.length;e++)n[e]=parseInt(t.slice(e*7,e*7+7),2)+(e+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=a.utilToBase(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,m;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n}toString(){let e=``;if(this.isHexOnly)e=i.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let t=this.valueDec;this.valueDec<=39?e=`0.`:this.valueDec<=79?(e=`1.`,t-=40):(e=`2.`,t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Oe.NAME=`sidBlock`;var B=class extends x{constructor({value:e=``,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Oe;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.value.length===0&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e){let t=[];for(let n=0;n<this.value.length;n++){let r=this.value[n].toBER(e);if(r.byteLength===0)return this.error=this.value[n].error,m;t.push(r)}return s(t)}fromString(e){this.value=[];let t=0,n=0,r=``,i=!1;do if(n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1,i){let e=this.value[0],t=0;switch(e.valueDec){case 0:break;case 1:t=40;break;case 2:t=80;break;default:this.value=[];return}let n=parseInt(r,10);if(isNaN(n))return;e.valueDec=n+t,i=!1}else{let e=new Oe;if(r>2**53-1)o(),e.valueBigInt=BigInt(r);else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(n!==-1)}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t?(r=`{${r}}`,this.value[n].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};B.NAME=`ObjectIdentifierValueBlock`;var ke,V=class extends T{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,B),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};ke=V,w.ObjectIdentifier=ke,V.NAME=`OBJECT IDENTIFIER`;var Ae=class extends y(b){constructor({valueDec:e=0,...t}={}){super(t),this.valueDec=e}fromBER(e,t,n){if(n===0)return t;let r=i.BufferSourceConverter.toUint8Array(e);if(!c(this,r,t,n))return-1;let o=r.subarray(t,t+n);this.valueHexView=new Uint8Array(n);for(let e=0;e<n&&(this.valueHexView[e]=o[e]&127,this.blockLength++,o[e]&128);e++);let s=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)s[e]=this.valueHexView[e];return this.valueHexView=s,o[this.blockLength-1]&128?(this.error=`End of input reached before message was fully decoded`,-1):(this.valueHexView[0]===0&&this.warnings.push(`Needlessly long format of SID encoding`),this.blockLength<=8?this.valueDec=a.utilFromBase(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push(`Too big SID for decoding, hex only`)),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let t=this.valueHexView,n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)n[e]=t[e]|128;return n[this.blockLength-1]=t[this.blockLength-1],n.buffer}let t=a.utilToBase(this.valueDec,7);if(t.byteLength===0)return this.error=`Error during encoding SID value`,m;let n=new Uint8Array(t.byteLength);if(!e){let e=new Uint8Array(t),r=t.byteLength-1;for(let t=0;t<r;t++)n[t]=e[t]|128;n[r]=e[r]}return n.buffer}toString(){let e=``;return e=this.isHexOnly?i.Convert.ToHex(this.valueHexView):this.valueDec.toString(),e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Ae.NAME=`relativeSidBlock`;var je=class extends x{constructor({value:e=``,...t}={}){super(t),this.value=[],e&&this.fromString(e)}fromBER(e,t,n){let r=t;for(;n>0;){let t=new Ae;if(r=t.fromBER(e,r,n),r===-1)return this.blockLength=0,this.error=t.error,r;this.blockLength+=t.blockLength,n-=t.blockLength,this.value.push(t)}return r}toBER(e,t){let n=[];for(let t=0;t<this.value.length;t++){let r=this.value[t].toBER(e);if(r.byteLength===0)return this.error=this.value[t].error,m;n.push(r)}return s(n)}fromString(e){this.value=[];let t=0,n=0,r=``;do{n=e.indexOf(`.`,t),r=n===-1?e.substring(t):e.substring(t,n),t=n+1;let i=new Ae;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(n!==-1);return!0}toString(){let e=``,t=!1;for(let n=0;n<this.value.length;n++){t=this.value[n].isHexOnly;let r=this.value[n].toString();n!==0&&(e=`${e}.`),t&&(r=`{${r}}`),e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let t=0;t<this.value.length;t++)e.sidArray.push(this.value[t].toJSON());return e}};je.NAME=`RelativeObjectIdentifierValueBlock`;var Me,Ne=class extends T{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,je),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||`empty`}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Me=Ne,w.RelativeObjectIdentifier=Me,Ne.NAME=`RelativeObjectIdentifier`;var Pe,Fe=class extends le{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Pe=Fe,w.Sequence=Pe,Fe.NAME=`SEQUENCE`;var Ie,Le=class extends le{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Ie=Le,w.Set=Ie,Le.NAME=`SET`;var Re=class extends y(x){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=``}toJSON(){return{...super.toJSON(),value:this.value}}};Re.NAME=`StringValueBlock`;var ze=class extends Re{};ze.NAME=`SimpleStringValueBlock`;var H=class extends D{constructor({...e}={}){super(e,ze)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,i.BufferSourceConverter.toUint8Array(e))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);this.valueBlock.value=e}};H.NAME=`SIMPLE STRING`;var Be=class extends H{fromBuffer(e){this.valueBlock.valueHexView=i.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=i.Convert.ToUtf8String(e)}catch(t){this.warnings.push(`Error during "decodeURIComponent": ${t}, using raw string`),this.valueBlock.value=i.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(i.Convert.FromUtf8String(e)),this.valueBlock.value=e}};Be.NAME=`Utf8StringValueBlock`;var U,W=class extends Be{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};U=W,w.Utf8String=U,W.NAME=`UTF8String`;var Ve=class extends H{fromBuffer(e){this.valueBlock.value=i.Convert.ToUtf16String(e),this.valueBlock.valueHexView=i.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(i.Convert.FromUtf16String(e))}};Ve.NAME=`BmpStringValueBlock`;var He,Ue=class extends Ve{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};He=Ue,w.BmpString=He,Ue.NAME=`BMPString`;var We=class extends H{fromBuffer(e){let t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),n=new Uint8Array(t);for(let e=0;e<n.length;e+=4)n[e]=n[e+3],n[e+1]=n[e+2],n[e+2]=0,n[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){let t=e.length,n=this.valueBlock.valueHexView=new Uint8Array(t*4);for(let r=0;r<t;r++){let t=a.utilToBase(e.charCodeAt(r),8),i=new Uint8Array(t);if(i.length>4)continue;let o=4-i.length;for(let e=i.length-1;e>=0;e--)n[r*4+e+o]=i[e]}this.valueBlock.value=e}};We.NAME=`UniversalStringValueBlock`;var Ge,Ke=class extends We{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Ge=Ke,w.UniversalString=Ge,Ke.NAME=`UniversalString`;var qe,Je=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};qe=Je,w.NumericString=qe,Je.NAME=`NumericString`;var G,Ye=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};G=Ye,w.PrintableString=G,Ye.NAME=`PrintableString`;var Xe,Ze=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Xe=Ze,w.TeletexString=Xe,Ze.NAME=`TeletexString`;var Qe,$e=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Qe=$e,w.VideotexString=Qe,$e.NAME=`VideotexString`;var et,tt=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};et=tt,w.IA5String=et,tt.NAME=`IA5String`;var nt,rt=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};nt=rt,w.GraphicString=nt,rt.NAME=`GraphicString`;var it,at=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};it=at,w.VisibleString=it,at.NAME=`VisibleString`;var ot,K=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};ot=K,w.GeneralString=ot,K.NAME=`GeneralString`;var lt,ut=class extends H{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};lt=ut,w.CharacterString=lt,ut.NAME=`CharacterString`;var dt,ft=class extends at{constructor({value:e,valueDate:t,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t<e.length;t++)this.valueBlock.valueHexView[t]=e.charCodeAt(t)}t&&(this.fromDate(t),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,i.BufferSourceConverter.toUint8Array(e)))}toBuffer(){let e=this.toString(),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(t===null){this.error=`Wrong input string for conversion`;return}let n=parseInt(t[1],10);this.year=n>=50?1900+n:2e3+n,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e=`iso`){if(e===`iso`){let e=Array(7);return e[0]=a.padNumber(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=a.padNumber(this.month,2),e[2]=a.padNumber(this.day,2),e[3]=a.padNumber(this.hour,2),e[4]=a.padNumber(this.minute,2),e[5]=a.padNumber(this.second,2),e[6]=`Z`,e.join(``)}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};dt=ft,w.UTCTime=dt,ft.NAME=`UTCTime`;var pt,mt=class extends ft{constructor(e={}){super(e),this.millisecond??=0,this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){let e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){let t=!1,n=``,r=``,i=0,a,o=0,s=0;if(e[e.length-1]===`Z`)n=e.substring(0,e.length-1),t=!0;else{let t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw Error(`Wrong input string for conversion`);n=e}if(t){if(n.indexOf(`+`)!==-1||n.indexOf(`-`)!==-1)throw Error(`Wrong input string for conversion`)}else{let e=1,t=n.indexOf(`+`),r=``;if(t===-1&&(t=n.indexOf(`-`),e=-1),t!==-1){if(r=n.substring(t+1),n=n.substring(0,t),r.length!==2&&r.length!==4)throw Error(`Wrong input string for conversion`);let i=parseInt(r.substring(0,2),10);if(isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);if(o=e*i,r.length===4){if(i=parseInt(r.substring(2,4),10),isNaN(i.valueOf()))throw Error(`Wrong input string for conversion`);s=e*i}}}let c=n.indexOf(`.`);if(c===-1&&(c=n.indexOf(`,`)),c!==-1){let e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw Error(`Wrong input string for conversion`);i=e.valueOf(),r=n.substring(0,c)}else r=n;switch(!0){case r.length===8:if(a=/(\d{4})(\d{2})(\d{2})/gi,c!==-1)throw Error(`Wrong input string for conversion`);break;case r.length===10:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===12:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=60*i;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case r.length===14:if(a=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,c!==-1){let e=1e3*i;this.millisecond=Math.floor(e)}break;default:throw Error(`Wrong input string for conversion`)}let l=a.exec(r);if(l===null)throw Error(`Wrong input string for conversion`);for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+o;break;case 5:this.minute=parseInt(l[e],10)+s;break;case 6:this.second=parseInt(l[e],10);break;default:throw Error(`Wrong input string for conversion`)}if(t===!1){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e=`iso`){if(e===`iso`){let e=[];return e.push(a.padNumber(this.year,4)),e.push(a.padNumber(this.month,2)),e.push(a.padNumber(this.day,2)),e.push(a.padNumber(this.hour,2)),e.push(a.padNumber(this.minute,2)),e.push(a.padNumber(this.second,2)),this.millisecond!==0&&(e.push(`.`),e.push(a.padNumber(this.millisecond,3))),e.push(`Z`),e.join(``)}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};pt=mt,w.GeneralizedTime=pt,mt.NAME=`GeneralizedTime`;var ht,gt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};ht=gt,w.DATE=ht,gt.NAME=`DATE`;var _t,vt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};_t=vt,w.TimeOfDay=_t,vt.NAME=`TimeOfDay`;var yt,bt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};yt=bt,w.DateTime=yt,bt.NAME=`DateTime`;var xt,St=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};xt=St,w.Duration=xt,St.NAME=`Duration`;var Ct,wt=class extends W{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Ct=wt,w.TIME=Ct,wt.NAME=`TIME`;var Tt=class{constructor({name:e=``,optional:t=!1}={}){this.name=e,this.optional=t}},Et=class extends Tt{constructor({value:e=[],...t}={}){super(t),this.value=e}},Dt=class extends Tt{constructor({value:e=new Tt,local:t=!1,...n}={}){super(n),this.value=e,this.local=t}},Ot=class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=i.BufferSourceConverter.toUint8Array(e)}constructor({data:e=h}={}){this.dataView=i.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,n){let r=t+n;return this.dataView=i.BufferSourceConverter.toUint8Array(e).subarray(t,r),r}toBER(e){return this.dataView.slice().buffer}};function kt(e,t,n){if(n instanceof Et){for(let r of n.value)if(kt(e,t,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:`Wrong values for Choice type`}};return n.hasOwnProperty(f)&&(e.name=n.name),e}}if(n instanceof Tt)return n.hasOwnProperty(f)&&(e[n.name]=t),{verified:!0,result:e};if(!(e instanceof Object))return{verified:!1,result:{error:`Wrong root object`}};if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 data`}};if(!(n instanceof Object)||!(`idBlock`in n)||!(`fromBER`in n.idBlock)||!(`toBER`in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.toBER(!1);if(r.byteLength===0)return{verified:!1,result:{error:`Error encoding idBlock for ASN.1 schema`}};if(n.idBlock.fromBER(r,0,r.byteLength)===-1)return{verified:!1,result:{error:`Error decoding idBlock for ASN.1 schema`}};if(n.idBlock.hasOwnProperty(`tagClass`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(`tagNumber`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(n.idBlock.hasOwnProperty(`isConstructed`)===!1)return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!(`isHexOnly`in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};if(n.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(n.idBlock.isHexOnly){if(!(p in n.idBlock))return{verified:!1,result:{error:`Wrong ASN.1 schema`}};let r=n.idBlock.valueHexView,i=t.idBlock.valueHexView;if(r.length!==i.length)return{verified:!1,result:e};for(let t=0;t<r.length;t++)if(r[t]!==i[1])return{verified:!1,result:e}}if(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(e[n.name]=t)),n instanceof w.Constructed){let r=0,i={verified:!1,result:{error:`Unknown error`}},a=n.valueBlock.value.length;if(a>0&&n.valueBlock.value[0]instanceof Dt&&(a=t.valueBlock.value.length),a===0)return{verified:!0,result:e};if(t.valueBlock.value.length===0&&n.valueBlock.value.length!==0){let t=!0;for(let e=0;e<n.valueBlock.value.length;e++)t&&=n.valueBlock.value[e].optional||!1;return t?{verified:!0,result:e}:(n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),e.error=`Inconsistent object length`,{verified:!1,result:e})}for(let o=0;o<a;o++)if(o-r>=t.valueBlock.value.length){if(n.valueBlock.value[o].optional===!1){let t={verified:!1,result:e};return e.error=`Inconsistent length between ASN.1 data and schema`,n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}}else if(n.valueBlock.value[0]instanceof Dt){if(i=kt(e,t.valueBlock.value[o],n.valueBlock.value[0].value),i.verified===!1){if(n.valueBlock.value[0].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),i}if(f in n.valueBlock.value[0]&&n.valueBlock.value[0].name.length>0){let r={};r=`local`in n.valueBlock.value[0]&&n.valueBlock.value[0].local?t:e,r[n.valueBlock.value[0].name]===void 0&&(r[n.valueBlock.value[0].name]=[]),r[n.valueBlock.value[0].name].push(t.valueBlock.value[o])}}else if(i=kt(e,t.valueBlock.value[o-r],n.valueBlock.value[o]),i.verified===!1){if(n.valueBlock.value[o].optional)r++;else return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&delete e[n.name]),i}if(i.verified===!1){let t={verified:!1,result:e};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}return{verified:!0,result:e}}if(n.primitiveSchema&&p in t.valueBlock){let r=ae(t.valueBlock.valueHexView);if(r.offset===-1){let t={verified:!1,result:r.result};return n.name&&(n.name=n.name.replace(/^\s+|\s+$/g,``),n.name&&(delete e[n.name],t.name=n.name)),t}return kt(e,r.result,n.primitiveSchema)}return{verified:!0,result:e}}function q(e,t){if(!(t instanceof Object))return{verified:!1,result:{error:`Wrong ASN.1 schema type`}};let n=ae(i.BufferSourceConverter.toUint8Array(e));return n.offset===-1?{verified:!1,result:n.result}:kt(n.result,n.result,t)}e.Any=Tt,e.BaseBlock=T,e.BaseStringBlock=D,e.BitString=ye,e.BmpString=Ue,e.Boolean=he,e.CharacterString=ut,e.Choice=Et,e.Constructed=le,e.DATE=gt,e.DEFAULT_MAX_CONTENT_LENGTH=j,e.DEFAULT_MAX_DEPTH=100,e.DEFAULT_MAX_NODES=ee,e.DateTime=bt,e.Duration=St,e.EndOfContent=de,e.Enumerated=De,e.GeneralString=K,e.GeneralizedTime=mt,e.GraphicString=rt,e.HexBlock=y,e.IA5String=tt,e.Integer=Te,e.Null=pe,e.NumericString=Je,e.ObjectIdentifier=V,e.OctetString=_e,e.Primitive=A,e.PrintableString=Ye,e.RawData=Ot,e.RelativeObjectIdentifier=Ne,e.Repeated=Dt,e.Sequence=Fe,e.Set=Le,e.TIME=wt,e.TeletexString=Ze,e.TimeOfDay=vt,e.UTCTime=ft,e.UniversalString=Ke,e.Utf8String=W,e.ValueBlock=x,e.VideotexString=$e,e.ViewWriter=l,e.VisibleString=at,e.compareSchema=kt,e.fromBER=P,e.verifySchema=q})),ut=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isArrayBuffer=o,e.isSharedArrayBuffer=s,e.isArrayBufferLike=c,e.isArrayBufferView=l,e.isBufferSource=u,e.assertBufferSource=d,e.toUint8Array=f,e.toUint8ArrayCopy=p,e.toArrayBuffer=m,e.toArrayBufferLike=h,e.toView=g,e.toViewCopy=_;function t(e){return Object.prototype.toString.call(e)}function n(e){return e===DataView||e.prototype instanceof DataView}function r(e){return n(e)?1:e.BYTES_PER_ELEMENT??1}function i(e){if(ArrayBuffer.isView(e))return!0;if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.byteOffset==`number`&&typeof t.byteLength==`number`&&c(t.buffer)}function a(e){let t=f(e),n=new Uint8Array(t.byteLength);return n.set(t),n}function o(e){return t(e)===`[object ArrayBuffer]`}function s(e){return typeof SharedArrayBuffer<`u`&&t(e)===`[object SharedArrayBuffer]`}function c(e){return o(e)||s(e)}function l(e){return i(e)}function u(e){return c(e)||l(e)}function d(e){if(!u(e))throw TypeError(`Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView`)}function f(e){return d(e),c(e)?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function p(e){return a(e)}function m(e){if(d(e),o(e))return e;let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(f(e)),t}function h(e){return d(e),c(e)?e:e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:a(e).buffer}function g(e,t){if(d(e),ArrayBuffer.isView(e)&&e.constructor===t)return e;let i=f(e),a=r(t);if(i.byteOffset%a!==0||i.byteLength%a!==0)throw RangeError(`Cannot create ${t.name} over unaligned byte range`);return n(t)?new t(i.buffer,i.byteOffset,i.byteLength):new t(i.buffer,i.byteOffset,i.byteLength/a)}function _(e,t){return g(p(e),t)}})),dt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.concatToUint8Array=n,e.concat=r;let t=ut();function n(e){let n=[],r=0;for(let i of e){let e=(0,t.toUint8Array)(i);n.push(e),r+=e.byteLength}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return i}function r(e,r,...i){let a,o;typeof r==`function`?(a=Array.from(e),o=r):(0,t.isBufferSource)(e)?a=[e,r,...i].filter(t.isBufferSource):(a=Array.from(e),r&&a.push(r),a.push(...i));let s=n(a);return o?(0,t.toView)(s,o):s.buffer}})),ft=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.equal=n;let t=ut();function n(e,n,r={}){let i=(0,t.toUint8Array)(e),a=(0,t.toUint8Array)(n);if(!r.constantTime&&i.byteLength!==a.byteLength)return!1;let o=Math.max(i.byteLength,a.byteLength),s=i.byteLength^a.byteLength;for(let e=0;e<o;e++)s|=(i[e]??0)^(a[e]??0);return s===0}})),pt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.indexOf=u,e.lastIndexOf=d,e.includes=f,e.startsWith=p,e.endsWith=m,e.slice=h,e.tail=g,e.copy=_,e.compare=v;let t=ut();function n(e,t,n){let r=Number.isFinite(e)?Math.trunc(e):t;return r<=0?0:r>=n?n:r}function r(e,t){let r=n(t?.start,0,e),i=n(t?.end,e,e);return i>=r?[r,i]:[r,r]}function i(e,t){let r=n(t?.start,e,e),i=n(t?.end,0,e);return r>=i?[i,r]:[r,r]}function a(e,t,n){let r=Number.isFinite(e)?Math.trunc(e):t;return r<0?Math.max(n+r,0):r>n?n:r}function o(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function s(e){return new TextEncoder().encode(e)}function c(e,n){return typeof e==`string`?n?.encoding===`utf8`?s(e):o(e):(0,t.toUint8Array)(e)}function l(e,t,n){for(let r=0;r<t.byteLength;r++)if(e[n+r]!==t[r])return!1;return!0}function u(e,n,i){let a=(0,t.toUint8Array)(e),o=c(n,i),[s,u]=r(a.byteLength,i);if(o.byteLength===0)return s;let d=u-o.byteLength;if(d<s)return-1;for(let e=s;e<=d;e++)if(l(a,o,e))return e;return-1}function d(e,n,r){let a=(0,t.toUint8Array)(e),o=c(n,r),[s,u]=i(a.byteLength,r);if(o.byteLength===0)return u;let d=u-o.byteLength;if(d<s)return-1;for(let e=d;e>=s;e--)if(l(a,o,e))return e;return-1}function f(e,t,n){return u(e,t,n)!==-1}function p(e,n,r){let i=(0,t.toUint8Array)(e),a=c(n,r);return a.byteLength>i.byteLength?!1:l(i,a,0)}function m(e,n,r){let i=(0,t.toUint8Array)(e),a=c(n,r);return a.byteLength>i.byteLength?!1:l(i,a,i.byteLength-a.byteLength)}function h(e,n,r){let i=(0,t.toUint8Array)(e),o=a(n,0,i.byteLength),s=a(r,i.byteLength,i.byteLength);return s<=o?i.subarray(o,o):i.subarray(o,s)}function g(e,n){let r=(0,t.toUint8Array)(e),i=Number.isFinite(n)?Math.max(0,Math.trunc(n)):0;return i>=r.byteLength?r:r.subarray(r.byteLength-i)}function _(e){return(0,t.toUint8ArrayCopy)(e)}function v(e,n){let r=(0,t.toUint8Array)(e),i=(0,t.toUint8Array)(n),a=Math.min(r.byteLength,i.byteLength);for(let e=0;e<a;e++){if(r[e]<i[e])return-1;if(r[e]>i[e])return 1}return r.byteLength<i.byteLength?-1:+(r.byteLength>i.byteLength)}})),mt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.tail=e.startsWith=e.slice=e.lastIndexOf=e.indexOf=e.includes=e.endsWith=e.copy=e.compare=e.equal=e.concatToUint8Array=e.concat=e.toViewCopy=e.toView=e.toUint8ArrayCopy=e.toUint8Array=e.toArrayBufferLike=e.toArrayBuffer=e.isSharedArrayBuffer=e.isBufferSource=e.isArrayBufferView=e.isArrayBufferLike=e.isArrayBuffer=e.assertBufferSource=void 0;var t=ut();Object.defineProperty(e,"assertBufferSource",{enumerable:!0,get:function(){return t.assertBufferSource}}),Object.defineProperty(e,"isArrayBuffer",{enumerable:!0,get:function(){return t.isArrayBuffer}}),Object.defineProperty(e,"isArrayBufferLike",{enumerable:!0,get:function(){return t.isArrayBufferLike}}),Object.defineProperty(e,"isArrayBufferView",{enumerable:!0,get:function(){return t.isArrayBufferView}}),Object.defineProperty(e,"isBufferSource",{enumerable:!0,get:function(){return t.isBufferSource}}),Object.defineProperty(e,"isSharedArrayBuffer",{enumerable:!0,get:function(){return t.isSharedArrayBuffer}}),Object.defineProperty(e,"toArrayBuffer",{enumerable:!0,get:function(){return t.toArrayBuffer}}),Object.defineProperty(e,"toArrayBufferLike",{enumerable:!0,get:function(){return t.toArrayBufferLike}}),Object.defineProperty(e,"toUint8Array",{enumerable:!0,get:function(){return t.toUint8Array}}),Object.defineProperty(e,"toUint8ArrayCopy",{enumerable:!0,get:function(){return t.toUint8ArrayCopy}}),Object.defineProperty(e,"toView",{enumerable:!0,get:function(){return t.toView}}),Object.defineProperty(e,"toViewCopy",{enumerable:!0,get:function(){return t.toViewCopy}});var n=dt();Object.defineProperty(e,"concat",{enumerable:!0,get:function(){return n.concat}}),Object.defineProperty(e,"concatToUint8Array",{enumerable:!0,get:function(){return n.concatToUint8Array}});var r=ft();Object.defineProperty(e,"equal",{enumerable:!0,get:function(){return r.equal}});var i=pt();Object.defineProperty(e,"compare",{enumerable:!0,get:function(){return i.compare}}),Object.defineProperty(e,"copy",{enumerable:!0,get:function(){return i.copy}}),Object.defineProperty(e,"endsWith",{enumerable:!0,get:function(){return i.endsWith}}),Object.defineProperty(e,"includes",{enumerable:!0,get:function(){return i.includes}}),Object.defineProperty(e,"indexOf",{enumerable:!0,get:function(){return i.indexOf}}),Object.defineProperty(e,"lastIndexOf",{enumerable:!0,get:function(){return i.lastIndexOf}}),Object.defineProperty(e,"slice",{enumerable:!0,get:function(){return i.slice}}),Object.defineProperty(e,"startsWith",{enumerable:!0,get:function(){return i.startsWith}}),Object.defineProperty(e,"tail",{enumerable:!0,get:function(){return i.tail}})})),ht=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnPropTypes=e.AsnTypeTypes=void 0;var t;(function(e){e[e.Sequence=0]=`Sequence`,e[e.Set=1]=`Set`,e[e.Choice=2]=`Choice`})(t||(e.AsnTypeTypes=t={}));var n;(function(e){e[e.Any=1]=`Any`,e[e.Boolean=2]=`Boolean`,e[e.OctetString=3]=`OctetString`,e[e.BitString=4]=`BitString`,e[e.Integer=5]=`Integer`,e[e.Enumerated=6]=`Enumerated`,e[e.ObjectIdentifier=7]=`ObjectIdentifier`,e[e.Utf8String=8]=`Utf8String`,e[e.BmpString=9]=`BmpString`,e[e.UniversalString=10]=`UniversalString`,e[e.NumericString=11]=`NumericString`,e[e.PrintableString=12]=`PrintableString`,e[e.TeletexString=13]=`TeletexString`,e[e.VideotexString=14]=`VideotexString`,e[e.IA5String=15]=`IA5String`,e[e.GraphicString=16]=`GraphicString`,e[e.VisibleString=17]=`VisibleString`,e[e.GeneralString=18]=`GeneralString`,e[e.CharacterString=19]=`CharacterString`,e[e.UTCTime=20]=`UTCTime`,e[e.GeneralizedTime=21]=`GeneralizedTime`,e[e.DATE=22]=`DATE`,e[e.TimeOfDay=23]=`TimeOfDay`,e[e.DateTime=24]=`DateTime`,e[e.Duration=25]=`Duration`,e[e.TIME=26]=`TIME`,e[e.Null=27]=`Null`})(n||(e.AsnPropTypes=n={}))})),gt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BitString=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt();e.BitString=class{unusedBits=0;value=new ArrayBuffer(0);constructor(e,t=0){if(e){if(typeof e==`number`)this.fromNumber(e);else if((0,r.isBufferSource)(e))this.unusedBits=t,this.value=(0,r.toArrayBuffer)(e);else throw TypeError(`Unsupported type of 'params' argument for BitString`)}}fromASN(e){if(!(e instanceof n.BitString))throw TypeError(`Argument 'asn' is not instance of ASN.1 BitString`);return this.unusedBits=e.valueBlock.unusedBits,this.value=(0,r.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new n.BitString({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new n.BitString({name:e})}toNumber(){let e=``,t=new Uint8Array(this.value);for(let n of t)e+=n.toString(2).padStart(8,`0`);return e=e.split(``).reverse().join(``),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,`0`)),parseInt(e,2)}fromNumber(e){let t=e.toString(2),n=t.length+7>>3;this.unusedBits=(n<<3)-t.length;let r=new Uint8Array(n);t=t.padStart(n<<3,`0`).split(``).reverse().join(``);let i=0;for(;i<n;)r[i]=parseInt(t.slice(i<<3,(i<<3)+8),2),i++;this.value=r.buffer}}})),_t=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OctetString=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt();e.OctetString=class{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){this.buffer=typeof e==`number`?new ArrayBuffer(e):(0,r.isBufferSource)(e)?(0,r.toArrayBuffer)(e):Array.isArray(e)?new Uint8Array(e).buffer:new ArrayBuffer(0)}fromASN(e){if(!(e instanceof n.OctetString))throw TypeError(`Argument 'asn' is not instance of ASN.1 OctetString`);return this.buffer=(0,r.toArrayBuffer)(e.valueBlock.valueHex),this}toASN(){return new n.OctetString({valueHex:this.buffer})}toSchema(e){return new n.OctetString({name:e})}}})),vt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0});let n=(K(),t(B));n.__exportStar(gt(),e),n.__exportStar(_t(),e)})),yt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnNullConverter=e.AsnGeneralizedTimeConverter=e.AsnUTCTimeConverter=e.AsnCharacterStringConverter=e.AsnGeneralStringConverter=e.AsnVisibleStringConverter=e.AsnGraphicStringConverter=e.AsnIA5StringConverter=e.AsnVideotexStringConverter=e.AsnTeletexStringConverter=e.AsnPrintableStringConverter=e.AsnNumericStringConverter=e.AsnUniversalStringConverter=e.AsnBmpStringConverter=e.AsnUtf8StringConverter=e.AsnConstructedOctetStringConverter=e.AsnOctetStringConverter=e.AsnBooleanConverter=e.AsnObjectIdentifierConverter=e.AsnBitStringConverter=e.AsnIntegerBigIntConverter=e.AsnIntegerArrayBufferConverter=e.AsnEnumeratedConverter=e.AsnIntegerConverter=e.AsnAnyConverter=void 0,e.defaultConverter=s;let n=(K(),t(B)).__importStar(lt()),r=mt(),i=ht(),a=vt();e.AsnAnyConverter={fromASN:e=>e instanceof n.Null?null:(0,r.toArrayBuffer)(e.valueBeforeDecodeView),toASN:e=>{if(e===null)return new n.Null;let t=n.fromBER(e);if(t.result.error)throw Error(t.result.error);return t.result}},e.AsnIntegerConverter={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new n.Integer({value:+e})},e.AsnEnumeratedConverter={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new n.Enumerated({value:e})},e.AsnIntegerArrayBufferConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.Integer({valueHex:e})},e.AsnIntegerBigIntConverter={fromASN:e=>e.toBigInt(),toASN:e=>n.Integer.fromBigInt(e)},e.AsnBitStringConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.BitString({valueHex:e})},e.AsnObjectIdentifierConverter={fromASN:e=>e.valueBlock.toString(),toASN:e=>new n.ObjectIdentifier({value:e})},e.AsnBooleanConverter={fromASN:e=>e.valueBlock.value,toASN:e=>new n.Boolean({value:e})},e.AsnOctetStringConverter={fromASN:e=>(0,r.toArrayBuffer)(e.valueBlock.valueHexView),toASN:e=>new n.OctetString({valueHex:e})},e.AsnConstructedOctetStringConverter={fromASN:e=>new a.OctetString(e.getValue()),toASN:e=>e.toASN()};function o(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}e.AsnUtf8StringConverter=o(n.Utf8String),e.AsnBmpStringConverter=o(n.BmpString),e.AsnUniversalStringConverter=o(n.UniversalString),e.AsnNumericStringConverter=o(n.NumericString),e.AsnPrintableStringConverter=o(n.PrintableString),e.AsnTeletexStringConverter=o(n.TeletexString),e.AsnVideotexStringConverter=o(n.VideotexString),e.AsnIA5StringConverter=o(n.IA5String),e.AsnGraphicStringConverter=o(n.GraphicString),e.AsnVisibleStringConverter=o(n.VisibleString),e.AsnGeneralStringConverter=o(n.GeneralString),e.AsnCharacterStringConverter=o(n.CharacterString),e.AsnUTCTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new n.UTCTime({valueDate:e})},e.AsnGeneralizedTimeConverter={fromASN:e=>e.toDate(),toASN:e=>new n.GeneralizedTime({valueDate:e})},e.AsnNullConverter={fromASN:()=>null,toASN:()=>new n.Null};function s(t){switch(t){case i.AsnPropTypes.Any:return e.AsnAnyConverter;case i.AsnPropTypes.BitString:return e.AsnBitStringConverter;case i.AsnPropTypes.BmpString:return e.AsnBmpStringConverter;case i.AsnPropTypes.Boolean:return e.AsnBooleanConverter;case i.AsnPropTypes.CharacterString:return e.AsnCharacterStringConverter;case i.AsnPropTypes.Enumerated:return e.AsnEnumeratedConverter;case i.AsnPropTypes.GeneralString:return e.AsnGeneralStringConverter;case i.AsnPropTypes.GeneralizedTime:return e.AsnGeneralizedTimeConverter;case i.AsnPropTypes.GraphicString:return e.AsnGraphicStringConverter;case i.AsnPropTypes.IA5String:return e.AsnIA5StringConverter;case i.AsnPropTypes.Integer:return e.AsnIntegerConverter;case i.AsnPropTypes.Null:return e.AsnNullConverter;case i.AsnPropTypes.NumericString:return e.AsnNumericStringConverter;case i.AsnPropTypes.ObjectIdentifier:return e.AsnObjectIdentifierConverter;case i.AsnPropTypes.OctetString:return e.AsnOctetStringConverter;case i.AsnPropTypes.PrintableString:return e.AsnPrintableStringConverter;case i.AsnPropTypes.TeletexString:return e.AsnTeletexStringConverter;case i.AsnPropTypes.UTCTime:return e.AsnUTCTimeConverter;case i.AsnPropTypes.UniversalString:return e.AsnUniversalStringConverter;case i.AsnPropTypes.Utf8String:return e.AsnUtf8StringConverter;case i.AsnPropTypes.VideotexString:return e.AsnVideotexStringConverter;case i.AsnPropTypes.VisibleString:return e.AsnVisibleStringConverter;default:return null}}})),bt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isConvertible=t,e.isTypeOfArray=n,e.isArrayEqual=r;function t(e){return typeof e==`function`&&e.prototype?e.prototype.toASN&&e.prototype.fromASN?!0:t(e.prototype):!!(e&&typeof e==`object`&&`toASN`in e&&`fromASN`in e)}function n(e){if(e){let t=Object.getPrototypeOf(e);return t?.prototype?.constructor===Array||n(t)}return!1}function r(e,t){if(!(e&&t)||e.byteLength!==t.byteLength)return!1;let n=new Uint8Array(e),r=new Uint8Array(t);for(let t=0;t<e.byteLength;t++)if(n[t]!==r[t])return!1;return!0}})),xt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSchemaStorage=void 0;let n=(K(),t(B)).__importStar(lt()),r=ht(),i=bt();e.AsnSchemaStorage=class{items=new WeakMap;has(e){return this.items.has(e)}get(e,t=!1){let n=this.items.get(e);if(!n)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(t&&!n.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return n}cache(e){let t=this.get(e);t.schema||=this.create(e,!0)}createDefault(e){let t={type:r.AsnTypeTypes.Sequence,items:{}},n=this.findParentSchema(e);return n&&(Object.assign(t,n),t.items=Object.assign({},t.items,n.items)),t}create(e,t){let a=this.items.get(e)||this.createDefault(e),o=[];for(let e in a.items){let s=a.items[e],c=t?e:``,l;if(typeof s.type==`number`){let e=r.AsnPropTypes[s.type],t=n[e];if(!t)throw Error(`Cannot get ASN1 class by name '${e}'`);l=new t({name:c})}else(0,i.isConvertible)(s.type)?l=new s.type().toSchema(c):s.optional?this.get(s.type).type===r.AsnTypeTypes.Choice?l=new n.Any({name:c}):(l=this.create(s.type,!1),l.name=c):l=new n.Any({name:c});let u=!!s.optional||s.defaultValue!==void 0;if(s.repeated&&(l.name=``,l=new(s.repeated===`set`?n.Set:n.Sequence)({name:``,value:[new n.Repeated({name:c,value:l})]})),s.context!==null&&s.context!==void 0){if(s.implicit){if(typeof s.type==`number`||(0,i.isConvertible)(s.type)){let e=s.repeated?n.Constructed:n.Primitive;o.push(new e({name:c,optional:u,idBlock:{tagClass:3,tagNumber:s.context}}))}else{this.cache(s.type);let e=!!s.repeated,t=e?l:this.get(s.type,!0).schema;t=`valueBlock`in t?t.valueBlock.value:t.value,o.push(new n.Constructed({name:e?``:c,optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:t}))}}else o.push(new n.Constructed({optional:u,idBlock:{tagClass:3,tagNumber:s.context},value:[l]}))}else l.optional=u,o.push(l)}switch(a.type){case r.AsnTypeTypes.Sequence:return new n.Sequence({value:o,name:``});case r.AsnTypeTypes.Set:return new n.Set({value:o,name:``});case r.AsnTypeTypes.Choice:return new n.Choice({value:o,name:``});default:throw Error(`Unsupported ASN1 type in use`)}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){let t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}}})),St=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.schemaStorage=void 0,e.schemaStorage=new(xt()).AsnSchemaStorage})),Ct=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnProp=e.AsnSequenceType=e.AsnSetType=e.AsnChoiceType=e.AsnType=void 0;let n=(K(),t(B)).__importStar(yt()),r=ht(),i=St();e.AsnType=e=>t=>{let n;i.schemaStorage.has(t)?n=i.schemaStorage.get(t):(n=i.schemaStorage.createDefault(t),i.schemaStorage.set(t,n)),Object.assign(n,e)},e.AsnChoiceType=()=>(0,e.AsnType)({type:r.AsnTypeTypes.Choice}),e.AsnSetType=t=>(0,e.AsnType)({type:r.AsnTypeTypes.Set,...t}),e.AsnSequenceType=t=>(0,e.AsnType)({type:r.AsnTypeTypes.Sequence,...t}),e.AsnProp=e=>(t,r)=>{let a;i.schemaStorage.has(t.constructor)?a=i.schemaStorage.get(t.constructor):(a=i.schemaStorage.createDefault(t.constructor),i.schemaStorage.set(t.constructor,a));let o=Object.assign({},e);if(typeof o.type==`number`&&!o.converter){let i=n.defaultConverter(e.type);if(!i)throw Error(`Cannot get default converter for property '${r}' of ${t.constructor.name}`);o.converter=i}o.raw=e.raw,a.items[r]=o}})),wt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSchemaValidationError=void 0,e.AsnSchemaValidationError=class extends Error{schemas=[]}})),Tt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),(K(),t(B)).__exportStar(wt(),e)})),Et=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnParser=void 0;let n=(K(),t(B)),r=n.__importStar(lt()),i=mt(),a=ht(),o=n.__importStar(yt()),s=Tt(),c=bt(),l=St();e.AsnParser=class{static parse(e,t,n){let a=r.fromBER((0,i.toArrayBuffer)(e),n?.berOptions);if(a.result.error)throw Error(a.result.error);return this.fromASN(a.result,t,n)}static fromASN(e,t,n){try{if((0,c.isConvertible)(t))return new t().fromASN(e);let r=l.schemaStorage.get(t);l.schemaStorage.cache(t);let i=r.schema,a=this.handleChoiceTypes(e,r,t,i,n);if(a?.result)return a.result;a?.targetSchema&&(i=a.targetSchema);let o=this.handleSequenceTypes(e,r,t,i),s=new t;return(0,c.isTypeOfArray)(t)?this.handleArrayTypes(e,r,t,n):(this.processSchemaItems(r,o,s,n),s)}catch(e){throw e instanceof s.AsnSchemaValidationError&&e.schemas.push(t.name),e}}static handleChoiceTypes(e,t,n,i,o){if(e.constructor===r.Constructed&&t.type===a.AsnTypeTypes.Choice&&e.idBlock.tagClass===3)for(let i in t.items){let s=t.items[i];if(s.context===e.idBlock.tagNumber&&s.implicit&&typeof s.type==`function`&&l.schemaStorage.has(s.type)){let t=l.schemaStorage.get(s.type);if(t&&t.type===a.AsnTypeTypes.Sequence){let t=new r.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock){t.valueBlock.value=e.valueBlock.value;let r=this.fromASN(t,s.type,o),a=new n;return a[i]=r,{result:a}}}}}else if(e.constructor===r.Constructed&&t.type!==a.AsnTypeTypes.Choice){let n=new r.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:t.schema.valueBlock.value});for(let n in t.items)delete e[n];return{targetSchema:n}}return null}static handleSequenceTypes(e,t,n,i){if(t.type===a.AsnTypeTypes.Sequence){let t=r.compareSchema({},e,i);if(!t.verified)throw new s.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}{let t=r.compareSchema({},e,i);if(!t.verified)throw new s.AsnSchemaValidationError(`Data does not match to ${n.name} ASN1 schema.${t.result.error?` ${t.result.error}`:``}`);return t}}static processRepeatedField(e,t,n){let r=e.slice(t);if(r.length===1&&r[0].constructor.name===`Sequence`){let e=r[0];e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value)&&(r=e.valueBlock.value)}if(typeof n.type==`number`){let e=o.defaultConverter(n.type);if(!e)throw Error(`No converter for ASN.1 type ${n.type}`);return r.filter(e=>e&&e.valueBlock).map(t=>{try{return e.fromASN(t)}catch{return}}).filter(e=>e!==void 0)}return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,n.type)}catch{return}}).filter(e=>e!==void 0)}static processPrimitiveField(e,t){let n=o.defaultConverter(t.type);if(!n)throw Error(`No converter for ASN.1 type ${t.type}`);return n.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&typeof e.type==`function`&&l.schemaStorage.has(e.type)&&l.schemaStorage.get(e.type).type===a.AsnTypeTypes.Choice}static processOptionalChoiceField(e,t){try{return{processed:!0,value:this.fromASN(e,t.type)}}catch(e){if(e instanceof s.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return{processed:!1};throw e}}static handleArrayTypes(e,t,n,r){if(!(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let i=t.itemType;if(typeof i==`number`){let t=o.defaultConverter(i);if(!t)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);return n.from(e.valueBlock.value,e=>t.fromASN(e))}return n.from(e.valueBlock.value,e=>this.fromASN(e,i,r))}static processSchemaItems(e,t,n,r){for(let i in e.items){let a=t.result[i];if(!a)continue;let o=e.items[i],s=o.type,l;l=typeof s==`number`||(0,c.isConvertible)(s)?this.processPrimitiveSchemaItem(a,o,s,r):this.processComplexSchemaItem(a,o,s,r),l&&typeof l==`object`&&`value`in l&&`raw`in l?(n[i]=l.value,n[`${i}Raw`]=l.raw):n[i]=l}}static processPrimitiveSchemaItem(e,t,n,r){let i=t.converter??((0,c.isConvertible)(n)?new n:null);if(!i)throw Error(`Converter is empty`);return t.repeated?this.processRepeatedPrimitiveItem(e,t,i,r):this.processSinglePrimitiveItem(e,t,n,i,r)}static processRepeatedPrimitiveItem(e,t,n,i){if(t.implicit){let a=new(t.repeated===`sequence`?r.Sequence:r.Set);a.valueBlock=e.valueBlock;let o=r.fromBER(a.toBER(!1),i?.berOptions);if(o.offset===-1)throw Error(`Cannot parse the child item. ${o.result.error}`);if(!(`value`in o.result.valueBlock&&Array.isArray(o.result.valueBlock.value)))throw Error(`Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.`);let s=o.result.valueBlock.value;return Array.from(s,e=>n.fromASN(e))}return Array.from(e,e=>n.fromASN(e))}static processSinglePrimitiveItem(e,t,n,i,o){let s=e;if(t.implicit){let e;if((0,c.isConvertible)(n))e=new n().toSchema(``);else{let t=a.AsnPropTypes[n],i=r[t];if(!i)throw Error(`Cannot get '${t}' class from asn1js module`);e=new i}e.valueBlock=s.valueBlock,s=r.fromBER(e.toBER(!1),o?.berOptions).result}return i.fromASN(s)}static processComplexSchemaItem(e,t,n,r){if(t.repeated){if(!Array.isArray(e))throw Error(`Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.`);return Array.from(e,e=>this.fromASN(e,n,r))}{let i=this.handleImplicitTagging(e,t,n);if(this.isOptionalChoiceField(t))try{return this.fromASN(i,n,r)}catch(e){if(e instanceof s.AsnSchemaValidationError&&/Wrong values for Choice type/.test(e.message))return;throw e}{let a=this.fromASN(i,n,r);return t.raw?{value:a,raw:e.valueBeforeDecodeView}:a}}}static handleImplicitTagging(e,t,n){if(t.implicit&&typeof t.context==`number`){let t=l.schemaStorage.get(n);if(t.type===a.AsnTypeTypes.Sequence){let t=new r.Sequence;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}else if(t.type===a.AsnTypeTypes.Set){let t=new r.Set;if(`value`in e.valueBlock&&Array.isArray(e.valueBlock.value)&&`value`in t.valueBlock)return t.valueBlock.value=e.valueBlock.value,t}}return e}}})),Dt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSerializer=void 0;let n=(K(),t(B)),r=n.__importStar(lt()),i=mt(),a=n.__importStar(yt()),o=ht(),s=bt(),c=St();e.AsnSerializer=class e{static serialize(e){return e instanceof r.BaseBlock?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&typeof t==`object`&&(0,s.isConvertible)(t))return t.toASN();if(!(t&&typeof t==`object`))throw TypeError(`Parameter 1 should be type of Object.`);let n=t.constructor,l=c.schemaStorage.get(n);c.schemaStorage.cache(n);let u=[];if(l.itemType){if(!Array.isArray(t))throw TypeError(`Parameter 1 should be type of Array.`);if(typeof l.itemType==`number`){let e=a.defaultConverter(l.itemType);if(!e)throw Error(`Cannot get default converter for array item of ${n.name} ASN1 schema`);u=t.map(t=>e.toASN(t))}else u=t.map(e=>this.toAsnItem({type:l.itemType},`[]`,n,e))}else for(let a in l.items){let o=l.items[a],c=t[a];if(c===void 0||o.defaultValue===c||typeof o.defaultValue==`object`&&typeof c==`object`&&(0,s.isArrayEqual)(this.serialize(o.defaultValue),this.serialize(c)))continue;let d=e.toAsnItem(o,a,n,c);if(typeof o.context==`number`){if(o.implicit){if(!o.repeated&&(typeof o.type==`number`||(0,s.isConvertible)(o.type))){let e={};e.valueHex=d instanceof r.Null?(0,i.toArrayBuffer)(d.valueBeforeDecodeView):d.valueBlock.toBER(),u.push(new r.Primitive({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},...e}))}else u.push(new r.Constructed({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:d.valueBlock.value}))}else u.push(new r.Constructed({optional:o.optional,idBlock:{tagClass:3,tagNumber:o.context},value:[d]}))}else o.repeated?u=u.concat(d):u.push(d)}let d;switch(l.type){case o.AsnTypeTypes.Sequence:d=new r.Sequence({value:u});break;case o.AsnTypeTypes.Set:d=new r.Set({value:u});break;case o.AsnTypeTypes.Choice:if(!u[0])throw Error(`Schema '${n.name}' has wrong data. Choice cannot be empty.`);d=u[0]}return d}static toAsnItem(e,t,n,i){let a;if(typeof e.type==`number`){let s=e.converter;if(!s)throw Error(`Property '${t}' doesn't have converter for type ${o.AsnPropTypes[e.type]} in schema '${n.name}'`);if(e.repeated){if(!Array.isArray(i))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(i,e=>s.toASN(e));a=new(e.repeated===`sequence`?r.Sequence:r.Set)({value:t})}else a=s.toASN(i)}else if(e.repeated){if(!Array.isArray(i))throw TypeError(`Parameter 'objProp' should be type of Array.`);let t=Array.from(i,e=>this.toASN(e));a=new(e.repeated===`sequence`?r.Sequence:r.Set)({value:t})}else a=this.toASN(i);return a}}})),Ot=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnArray=void 0,e.AsnArray=class extends Array{constructor(e=[]){if(typeof e==`number`)super(e);else{super();for(let t of e)this.push(t)}}}})),kt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnConvert=void 0;let n=(K(),t(B)).__importStar(lt()),r=mt(),i=Et(),a=Dt();e.AsnConvert=class e{static serialize(e){return a.AsnSerializer.serialize(e)}static parse(e,t,n){return i.AsnParser.parse(e,t,n)}static toString(t,i){let a=(0,r.isBufferSource)(t)?(0,r.toArrayBuffer)(t):e.serialize(t),o=n.fromBER(a,i?.berOptions);if(o.offset===-1)throw Error(`Cannot decode ASN.1 data. ${o.result.error}`);return o.result.toString()}}})),q=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AsnSerializer=e.AsnParser=e.AsnPropTypes=e.AsnTypeTypes=e.AsnSetType=e.AsnSequenceType=e.AsnChoiceType=e.AsnType=e.AsnProp=void 0;let n=(K(),t(B));n.__exportStar(yt(),e),n.__exportStar(vt(),e);var r=Ct();Object.defineProperty(e,"AsnProp",{enumerable:!0,get:function(){return r.AsnProp}}),Object.defineProperty(e,"AsnType",{enumerable:!0,get:function(){return r.AsnType}}),Object.defineProperty(e,"AsnChoiceType",{enumerable:!0,get:function(){return r.AsnChoiceType}}),Object.defineProperty(e,"AsnSequenceType",{enumerable:!0,get:function(){return r.AsnSequenceType}}),Object.defineProperty(e,"AsnSetType",{enumerable:!0,get:function(){return r.AsnSetType}});var i=ht();Object.defineProperty(e,"AsnTypeTypes",{enumerable:!0,get:function(){return i.AsnTypeTypes}}),Object.defineProperty(e,"AsnPropTypes",{enumerable:!0,get:function(){return i.AsnPropTypes}});var a=Et();Object.defineProperty(e,"AsnParser",{enumerable:!0,get:function(){return a.AsnParser}});var o=Dt();Object.defineProperty(e,"AsnSerializer",{enumerable:!0,get:function(){return o.AsnSerializer}}),n.__exportStar(Tt(),e),n.__exportStar(Ot(),e),n.__exportStar(kt(),e)})),At=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.binary=void 0,e.encode=n,e.decode=r,e.is=i;let t=mt();function n(e){let n=(0,t.toUint8Array)(e),r=``;for(let e of n)r+=String.fromCharCode(e);return r}function r(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function i(e){return typeof e==`string`}e.binary={encode:n,decode:r,is:i}})),jt=i((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.hex=e.formats=void 0,e.normalize=m,e.is=h,e.encode=g,e.decode=_,e.parse=v,e.format=y;let t=mt(),n=/^[0-9a-f]$/i,r=[` `,` `,`
84
84
  `,`\r`,`:`,`-`,`.`];function i(e){return e.separators===`none`?[]:!e.separators||e.separators===`common`?r:e.separators}function a(e){if(!e)throw TypeError(`Hex separators must be non-empty strings`)}function o(e,t,n){for(let r of n)if(e.startsWith(r,t))return r}function s(e){let t=/[A-F]/.test(e),n=/[a-f]/.test(e);return t&&!n?`upper`:`lower`}function c(e){let t=/\r\n|\n/.exec(e);if(t)return t[0]===`\r
85
85
  `?`\r
86
86
  `:`
@@ -127,15 +127,15 @@ function Ir(e,t){ii(e,t);function n(){this.constructor=e}e.prototype=t===null?Ob
127
127
  * SOFTWARE.
128
128
  *
129
129
  */
130
- Oe();var n=q(),r=Y(),i=st(),a=_r(),o=wr(),s=Pr(),c=(K(),t(B)),l=zi(),u=ra(),d=sa();function f(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var p=f(r),m=f(a),h=f(o),g=f(s),_=f(u);let v=`crypto.algorithm`;var y=class{getAlgorithms(){return l.container.resolveAll(v)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let t=new r.AlgorithmIdentifier({algorithm:e.name});return`parameters`in e&&(t.parameters=e.parameters),t}throw Error(`Cannot convert WebCrypto algorithm to ASN.1 algorithm`)}toWebAlgorithm(e){for(let t of this.getAlgorithms()){let n=t.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}};let b=`crypto.algorithmProvider`;l.container.registerSingleton(b,y);var x;let S=`1.3.36.3.3.2.8.1.1`,C=`${S}.1`,w=`${S}.2`,T=`${S}.3`,E=`${S}.4`,D=`${S}.5`,O=`${S}.6`,k=`${S}.7`,A=`${S}.8`,ee=`${S}.9`,j=`${S}.10`,M=`${S}.11`,te=`${S}.12`,ne=`${S}.13`,re=`${S}.14`,N=`brainpoolP160r1`,ie=`brainpoolP160t1`,ae=`brainpoolP192r1`,P=`brainpoolP192t1`,oe=`brainpoolP224r1`,se=`brainpoolP224t1`,ce=`brainpoolP256r1`,le=`brainpoolP256t1`,ue=`brainpoolP320r1`,de=`brainpoolP320t1`,fe=`brainpoolP384r1`,pe=`brainpoolP384t1`,me=`brainpoolP512r1`,he=`brainpoolP512t1`,F=`ECDSA`;e.EcAlgorithm=x=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===`ecdsa`){if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return h.ecdsaWithSHA1;case`sha-256`:return h.ecdsaWithSHA256;case`sha-384`:return h.ecdsaWithSHA384;case`sha-512`:return h.ecdsaWithSHA512}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=h.id_secp256r1;break;case`K-256`:t=x.SECP256K1;break;case`P-384`:t=h.id_secp384r1;break;case`P-521`:t=h.id_secp521r1;break;case N:t=C;break;case ie:t=w;break;case ae:t=T;break;case P:t=E;break;case oe:t=D;break;case se:t=O;break;case ce:t=k;break;case le:t=A;break;case ue:t=ee;break;case de:t=j;break;case fe:t=M;break;case pe:t=te;break;case me:t=ne;break;case he:t=re}if(t)return new r.AlgorithmIdentifier({algorithm:h.id_ecPublicKey,parameters:n.AsnConvert.serialize(new h.ECParameters({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case h.id_ecdsaWithSHA1:return{name:F,hash:{name:`SHA-1`}};case h.id_ecdsaWithSHA256:return{name:F,hash:{name:`SHA-256`}};case h.id_ecdsaWithSHA384:return{name:F,hash:{name:`SHA-384`}};case h.id_ecdsaWithSHA512:return{name:F,hash:{name:`SHA-512`}};case h.id_ecPublicKey:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(n.AsnConvert.parse(e.parameters,h.ECParameters).namedCurve){case h.id_secp256r1:return{name:F,namedCurve:`P-256`};case x.SECP256K1:return{name:F,namedCurve:`K-256`};case h.id_secp384r1:return{name:F,namedCurve:`P-384`};case h.id_secp521r1:return{name:F,namedCurve:`P-521`};case C:return{name:F,namedCurve:N};case w:return{name:F,namedCurve:ie};case T:return{name:F,namedCurve:ae};case E:return{name:F,namedCurve:P};case D:return{name:F,namedCurve:oe};case O:return{name:F,namedCurve:se};case k:return{name:F,namedCurve:ce};case A:return{name:F,namedCurve:le};case ee:return{name:F,namedCurve:ue};case j:return{name:F,namedCurve:de};case M:return{name:F,namedCurve:fe};case te:return{name:F,namedCurve:pe};case ne:return{name:F,namedCurve:me};case re:return{name:F,namedCurve:he}}}return null}},e.EcAlgorithm.SECP256K1=`1.3.132.0.10`,e.EcAlgorithm=x=c.__decorate([l.injectable()],e.EcAlgorithm),l.container.registerSingleton(v,e.EcAlgorithm);let ge=Symbol(`name`),_e=Symbol(`value`);var I=class{constructor(e,t={},n=``){this[ge]=e,this[_e]=n;for(let e in t)this[e]=t[e]}};I.NAME=ge,I.VALUE=_e;var ve=class{static toTextObject(t){let n=new I(`Algorithm Identifier`,{},L.toString(t.algorithm));if(t.parameters)switch(t.algorithm){case h.id_ecPublicKey:{let r=new e.EcAlgorithm().toWebAlgorithm(t);r&&`namedCurve`in r?n[`Named Curve`]=r.namedCurve:n.Parameters=t.parameters;break}default:n.Parameters=t.parameters}return n}},L=class{static toString(e){return this.items[e]||e}};L.items={[g.id_sha1]:`sha1`,[g.id_sha224]:`sha224`,[g.id_sha256]:`sha256`,[g.id_sha384]:`sha384`,[g.id_sha512]:`sha512`,[g.id_rsaEncryption]:`rsaEncryption`,[g.id_sha1WithRSAEncryption]:`sha1WithRSAEncryption`,[g.id_sha224WithRSAEncryption]:`sha224WithRSAEncryption`,[g.id_sha256WithRSAEncryption]:`sha256WithRSAEncryption`,[g.id_sha384WithRSAEncryption]:`sha384WithRSAEncryption`,[g.id_sha512WithRSAEncryption]:`sha512WithRSAEncryption`,[h.id_ecPublicKey]:`ecPublicKey`,[h.id_ecdsaWithSHA1]:`ecdsaWithSHA1`,[h.id_ecdsaWithSHA224]:`ecdsaWithSHA224`,[h.id_ecdsaWithSHA256]:`ecdsaWithSHA256`,[h.id_ecdsaWithSHA384]:`ecdsaWithSHA384`,[h.id_ecdsaWithSHA512]:`ecdsaWithSHA512`,[p.id_kp_serverAuth]:`TLS WWW server authentication`,[p.id_kp_clientAuth]:`TLS WWW client authentication`,[p.id_kp_codeSigning]:`Code Signing`,[p.id_kp_emailProtection]:`E-mail Protection`,[p.id_kp_timeStamping]:`Time Stamping`,[p.id_kp_OCSPSigning]:`OCSP Signing`,[m.id_signedData]:`Signed Data`};var ye=class{static serialize(e){return this.serializeObj(e).join(`
131
- `)}static pad(e=0){return``.padStart(2*e,` `)}static serializeObj(e,t=0){let n=[],r=this.pad(t++),a=``,o=e[I.VALUE];o&&(a=` ${o}`),n.push(`${r}${e[I.NAME]}:${a}`),r=this.pad(t);for(let a in e){if(typeof a==`symbol`)continue;let o=e[a],s=a?`${a}: `:``;if(typeof o==`string`||typeof o==`number`||typeof o==`boolean`)n.push(`${r}${s}${o}`);else if(o instanceof Date)n.push(`${r}${s}${o.toUTCString()}`);else if(Array.isArray(o))for(let e of o)e[I.NAME]=a,n.push(...this.serializeObj(e,t));else if(o instanceof I)o[I.NAME]=a,n.push(...this.serializeObj(o,t));else if(i.BufferSourceConverter.isBufferSource(o))a?(n.push(`${r}${s}`),n.push(...this.serializeBufferSource(o,t+1))):n.push(...this.serializeBufferSource(o,t));else if(`toTextObject`in o){let e=o.toTextObject();e[I.NAME]=a,n.push(...this.serializeObj(e,t))}else throw TypeError(`Cannot serialize data in text format. Unsupported type.`)}return n}static serializeBufferSource(e,t=0){let n=this.pad(t),r=i.BufferSourceConverter.toUint8Array(e),a=[];for(let e=0;e<r.length;){let t=[];for(let n=0;n<16&&e<r.length;n++){n===8&&t.push(``);let i=r[e++].toString(16).padStart(2,`0`);t.push(i)}a.push(`${n}${t.join(` `)}`)}return a}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};ye.oidSerializer=L,ye.algorithmSerializer=ve;var be=class e{constructor(...e){if(e.length===1){let t=e[0];this.rawData=n.AsnConvert.serialize(t),this.onInit(t)}else{let t=n.AsnConvert.parse(e[0],e[1]);this.rawData=i.BufferSourceConverter.toArrayBuffer(e[0]),this.onInit(t)}}equal(t){return t instanceof e&&i.isEqual(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return n.AsnConvert.toString(this.rawData);case`text`:return ye.serialize(this.toTextObject());case`hex`:return i.Convert.ToHex(this.rawData);case`base64`:return i.Convert.ToBase64(this.rawData);case`base64url`:return i.Convert.ToBase64Url(this.rawData);default:throw TypeError(`Argument 'format' is unsupported value`)}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[``]=this.rawData,e}toTextObjectEmpty(e){return new I(this.getTextName(),{},e)}};be.NAME=`ASN`;var xe=class e extends be{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.Extension({extnID:e[0],critical:e[1],extnValue:new n.OctetString(i.BufferSourceConverter.toArrayBuffer(e[2]))})),super(t,r.Extension)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.value,e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty(this.critical?`critical`:void 0);return t[I.NAME]===e.NAME&&(t[I.NAME]=L.toString(this.type)),t}},Se,R=class e{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[Se]=`CryptoProvider`,typeof self<`u`&&typeof crypto<`u`?this.set(e.DEFAULT,crypto):typeof global<`u`&&global.crypto&&global.crypto.subtle&&this.set(e.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(t=e.DEFAULT){let n=this.items.get(t.toLowerCase());if(!n)throw Error(`Cannot get Crypto by name '${t}'`);return n}set(t,n){if(typeof t==`string`){if(!n)throw TypeError(`Argument 'value' is required`);this.items.set(t.toLowerCase(),n)}else this.items.set(e.DEFAULT,t);return this}};Se=Symbol.toStringTag,R.DEFAULT=`default`;let z=new R,Ce=/^[0-2](?:\.[1-9][0-9]*)+$/;function we(e){return new RegExp(Ce).test(e)}var Te=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return we(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}};let Ee=new Te;Ee.register(`CN`,`2.5.4.3`),Ee.register(`L`,`2.5.4.7`),Ee.register(`ST`,`2.5.4.8`),Ee.register(`O`,`2.5.4.10`),Ee.register(`OU`,`2.5.4.11`),Ee.register(`C`,`2.5.4.6`),Ee.register(`DC`,`0.9.2342.19200300.100.1.25`),Ee.register(`E`,`1.2.840.113549.1.9.1`),Ee.register(`G`,`2.5.4.42`),Ee.register(`I`,`2.5.4.43`),Ee.register(`SN`,`2.5.4.4`),Ee.register(`T`,`2.5.4.12`);function De(e,t){return`\\${i.Convert.ToHex(i.Convert.FromUtf8String(t)).toUpperCase()}`}function ke(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,De)}var V=class e{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new Te,this.asn=new r.Name;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];this.extraNames.register(e,n)}this.asn=typeof e==`string`?this.fromString(e):e instanceof r.Name?e:i.BufferSourceConverter.isBufferSource(e)?n.AsnConvert.parse(e,r.Name):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Ee.findId(e),n=[];for(let e of this.asn)for(let r of e)r.type===t&&n.push(r.value.toString());return n}getName(e){return this.extraNames.get(e)||Ee.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${i.Convert.ToHex(e.value.anyValue)}`:ke(e.value.toString())}`).join(`+`)).join(`, `)}toJSON(){let e=[];for(let t of this.asn){let n={};for(let e of t){let t=this.getName(e.type)||e.type;n[t]??(n[t]=[]),n[t].push(e.value.anyValue?`#${i.Convert.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new r.Name,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,i=null,a=`,`;for(;i=n.exec(`${e},`);){let[,e,n]=i,o=n[n.length-1];(o===`,`||o===`+`)&&(n=n.slice(0,n.length-1),i[3]=o);let s=i[3];e=this.getTypeOid(e);let c=this.createAttribute(e,n);a===`+`?t[t.length-1].push(c):t.push(new r.RelativeDistinguishedName([c])),a=s}return t}fromJSON(e){let t=new r.Name;for(let n of e){let e=new r.RelativeDistinguishedName;for(let t in n){let r=this.getTypeOid(t),i=n[t];for(let t of i){let n=this.createAttribute(r,t);e.push(n)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||``),!e)throw Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(t,n){let a=new r.AttributeTypeAndValue({type:t});if(typeof n==`object`)for(let e in n)switch(e){case`ia5String`:a.value.ia5String=n[e];break;case`utf8String`:a.value.utf8String=n[e];break;case`universalString`:a.value.universalString=n[e];break;case`bmpString`:a.value.bmpString=n[e];break;case`printableString`:a.value.printableString=n[e]}else if(n[0]===`#`)a.value.anyValue=i.Convert.FromHex(n.slice(1));else{let r=this.processStringValue(n);t===this.getName(`E`)||t===this.getName(`DC`)?a.value.ia5String=r:e.isPrintableString(r)?a.value.printableString=r:a.value.utf8String=r}return a}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,`
132
- `).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return n.AsnConvert.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.toArrayBuffer())}};let Ae=`Cannot initialize GeneralName from ASN.1 data.`,je=`${Ae} Unsupported string format in use.`,Me=`${Ae} Value doesn't match to GUID regular expression.`,Ne=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Pe=`1.3.6.1.4.1.311.25.1`,Fe=`1.3.6.1.4.1.311.20.2.3`,Ie=`email`,Le=`guid`;var Re=class extends be{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let r=new V(e[1]).toArrayBuffer(),i=n.AsnConvert.parse(r,p.Name);t=new p.GeneralName({directoryName:i});break}case`dns`:t=new p.GeneralName({dNSName:e[1]});break;case Ie:t=new p.GeneralName({rfc822Name:e[1]});break;case Le:{let r=new RegExp(Ne,`i`).exec(e[1]);if(!r)throw Error(`Cannot parse GUID value. Value doesn't match to regular expression`);let a=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(``);t=new p.GeneralName({otherName:new p.OtherName({typeId:Pe,value:n.AsnConvert.serialize(new n.OctetString(i.Convert.FromHex(a)))})});break}case`ip`:t=new p.GeneralName({iPAddress:e[1]});break;case`id`:t=new p.GeneralName({registeredID:e[1]});break;case`upn`:t=new p.GeneralName({otherName:new p.OtherName({typeId:Fe,value:n.AsnConvert.serialize(n.AsnUtf8StringConverter.toASN(e[1]))})});break;case`url`:t=new p.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw Error(`Cannot create GeneralName. Unsupported type of the name`)}else t=i.BufferSourceConverter.isBufferSource(e[0])?n.AsnConvert.parse(e[0],p.GeneralName):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Ie,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=`ip`,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=`url`,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=`id`,this.value=e.registeredID;else if(e.directoryName!=null)this.type=`dn`,this.value=new V(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===Pe){this.type=Le;let t=n.AsnConvert.parse(e.otherName.value,n.OctetString),r=new RegExp(Ne,`i`).exec(i.Convert.ToHex(t));if(!r)throw Error(Me);this.value=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===Fe)this.type=`upn`,this.value=n.AsnConvert.parse(e.otherName.value,p.DirectoryString).toString();else throw Error(je)}else throw Error(je)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case Le:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Ie:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=L.toString(t)),new I(e,void 0,t)}},ze=class extends be{constructor(e){let t;if(e instanceof p.GeneralNames)t=e;else if(Array.isArray(e)){let r=[];for(let t of e)if(t instanceof p.GeneralName)r.push(t);else{let e=n.AsnConvert.parse(new Re(t.type,t.value).rawData,p.GeneralName);r.push(e)}t=new p.GeneralNames(r)}else if(i.BufferSourceConverter.isBufferSource(e))t=n.AsnConvert.parse(e,p.GeneralNames);else throw Error(`Cannot initialize GeneralNames. Incorrect incoming arguments`);super(t)}onInit(e){let t=[];for(let n of e){let e=null;try{e=new Re(n)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let n=t.toTextObject(),r=e[n[I.NAME]];Array.isArray(r)||(r=[],e[n[I.NAME]]=r),r.push(n)}return e}};ze.NAME=`GeneralNames`;let H=`-{5}`,Be=`${`${H}BEGIN ([^\\n]+(?=${H}))${H}`}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)${`${H}END \\1${H}`}`;var U=class{static isPem(e){return typeof e==`string`&&new RegExp(Be,`g`).test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Be,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[\\n]+`,`g`),``),t={type:r[1],headers:[],rawData:i.Convert.FromBase64(e)},a=r[2];if(a){let e=a.split(RegExp(`\\n`,`g`)),n=null;for(let r of e){let[e,i]=r.split(/:(.*)/);if(i===void 0){if(!n)throw Error(`Cannot parse PEM string. Incorrect header value`);n.value+=e.trim()}else n&&t.headers.push(n),n={key:e,value:i.trim()}}n&&t.headers.push(n)}n.push(t)}return n}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw RangeError(`PEM string doesn't contain any objects`);return t[0]}static encode(e,t){if(Array.isArray(e)){let n=[];return t?e.forEach(e=>{if(!i.BufferSourceConverter.isBufferSource(e))throw TypeError(`Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource`);n.push(this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)}))}):e.forEach(e=>{if(!(`type`in e))throw TypeError(`Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut`);n.push(this.encodeStruct(e))}),n.join(`
130
+ Oe();var n=q(),r=Y(),i=st(),a=_r(),o=wr(),s=Pr(),c=(K(),t(B)),l=zi(),u=ra(),d=sa();function f(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}),t.default=e,Object.freeze(t)}var p=f(r),m=f(a),h=f(o),g=f(s),_=f(u);let v=`crypto.algorithm`;var y=class{getAlgorithms(){return l.container.resolveAll(v)}toAsnAlgorithm(e){({...e});for(let t of this.getAlgorithms()){let n=t.toAsnAlgorithm(e);if(n)return n}if(/^[0-9.]+$/.test(e.name)){let t=new r.AlgorithmIdentifier({algorithm:e.name});return`parameters`in e&&(t.parameters=e.parameters),t}throw Error(`Cannot convert WebCrypto algorithm to ASN.1 algorithm`)}toWebAlgorithm(e){for(let t of this.getAlgorithms()){let n=t.toWebAlgorithm(e);if(n)return n}return{name:e.algorithm,parameters:e.parameters}}};let b=`crypto.algorithmProvider`;l.container.registerSingleton(b,y);var x;let S=`1.3.36.3.3.2.8.1.1`,C=`${S}.1`,w=`${S}.2`,T=`${S}.3`,E=`${S}.4`,D=`${S}.5`,O=`${S}.6`,k=`${S}.7`,A=`${S}.8`,ee=`${S}.9`,j=`${S}.10`,M=`${S}.11`,te=`${S}.12`,ne=`${S}.13`,re=`${S}.14`,N=`brainpoolP160r1`,ie=`brainpoolP160t1`,ae=`brainpoolP192r1`,P=`brainpoolP192t1`,oe=`brainpoolP224r1`,se=`brainpoolP224t1`,ce=`brainpoolP256r1`,le=`brainpoolP256t1`,F=`brainpoolP320r1`,ue=`brainpoolP320t1`,de=`brainpoolP384r1`,fe=`brainpoolP384t1`,pe=`brainpoolP512r1`,me=`brainpoolP512t1`,I=`ECDSA`;e.EcAlgorithm=x=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===`ecdsa`){if(`hash`in e)switch((typeof e.hash==`string`?e.hash:e.hash.name).toLowerCase()){case`sha-1`:return h.ecdsaWithSHA1;case`sha-256`:return h.ecdsaWithSHA256;case`sha-384`:return h.ecdsaWithSHA384;case`sha-512`:return h.ecdsaWithSHA512}else if(`namedCurve`in e){let t=``;switch(e.namedCurve){case`P-256`:t=h.id_secp256r1;break;case`K-256`:t=x.SECP256K1;break;case`P-384`:t=h.id_secp384r1;break;case`P-521`:t=h.id_secp521r1;break;case N:t=C;break;case ie:t=w;break;case ae:t=T;break;case P:t=E;break;case oe:t=D;break;case se:t=O;break;case ce:t=k;break;case le:t=A;break;case F:t=ee;break;case ue:t=j;break;case de:t=M;break;case fe:t=te;break;case pe:t=ne;break;case me:t=re}if(t)return new r.AlgorithmIdentifier({algorithm:h.id_ecPublicKey,parameters:n.AsnConvert.serialize(new h.ECParameters({namedCurve:t}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case h.id_ecdsaWithSHA1:return{name:I,hash:{name:`SHA-1`}};case h.id_ecdsaWithSHA256:return{name:I,hash:{name:`SHA-256`}};case h.id_ecdsaWithSHA384:return{name:I,hash:{name:`SHA-384`}};case h.id_ecdsaWithSHA512:return{name:I,hash:{name:`SHA-512`}};case h.id_ecPublicKey:if(!e.parameters)throw TypeError(`Cannot get required parameters from EC algorithm`);switch(n.AsnConvert.parse(e.parameters,h.ECParameters).namedCurve){case h.id_secp256r1:return{name:I,namedCurve:`P-256`};case x.SECP256K1:return{name:I,namedCurve:`K-256`};case h.id_secp384r1:return{name:I,namedCurve:`P-384`};case h.id_secp521r1:return{name:I,namedCurve:`P-521`};case C:return{name:I,namedCurve:N};case w:return{name:I,namedCurve:ie};case T:return{name:I,namedCurve:ae};case E:return{name:I,namedCurve:P};case D:return{name:I,namedCurve:oe};case O:return{name:I,namedCurve:se};case k:return{name:I,namedCurve:ce};case A:return{name:I,namedCurve:le};case ee:return{name:I,namedCurve:F};case j:return{name:I,namedCurve:ue};case M:return{name:I,namedCurve:de};case te:return{name:I,namedCurve:fe};case ne:return{name:I,namedCurve:pe};case re:return{name:I,namedCurve:me}}}return null}},e.EcAlgorithm.SECP256K1=`1.3.132.0.10`,e.EcAlgorithm=x=c.__decorate([l.injectable()],e.EcAlgorithm),l.container.registerSingleton(v,e.EcAlgorithm);let he=Symbol(`name`),ge=Symbol(`value`);var L=class{constructor(e,t={},n=``){this[he]=e,this[ge]=n;for(let e in t)this[e]=t[e]}};L.NAME=he,L.VALUE=ge;var _e=class{static toTextObject(t){let n=new L(`Algorithm Identifier`,{},R.toString(t.algorithm));if(t.parameters)switch(t.algorithm){case h.id_ecPublicKey:{let r=new e.EcAlgorithm().toWebAlgorithm(t);r&&`namedCurve`in r?n[`Named Curve`]=r.namedCurve:n.Parameters=t.parameters;break}default:n.Parameters=t.parameters}return n}},R=class{static toString(e){return this.items[e]||e}};R.items={[g.id_sha1]:`sha1`,[g.id_sha224]:`sha224`,[g.id_sha256]:`sha256`,[g.id_sha384]:`sha384`,[g.id_sha512]:`sha512`,[g.id_rsaEncryption]:`rsaEncryption`,[g.id_sha1WithRSAEncryption]:`sha1WithRSAEncryption`,[g.id_sha224WithRSAEncryption]:`sha224WithRSAEncryption`,[g.id_sha256WithRSAEncryption]:`sha256WithRSAEncryption`,[g.id_sha384WithRSAEncryption]:`sha384WithRSAEncryption`,[g.id_sha512WithRSAEncryption]:`sha512WithRSAEncryption`,[h.id_ecPublicKey]:`ecPublicKey`,[h.id_ecdsaWithSHA1]:`ecdsaWithSHA1`,[h.id_ecdsaWithSHA224]:`ecdsaWithSHA224`,[h.id_ecdsaWithSHA256]:`ecdsaWithSHA256`,[h.id_ecdsaWithSHA384]:`ecdsaWithSHA384`,[h.id_ecdsaWithSHA512]:`ecdsaWithSHA512`,[p.id_kp_serverAuth]:`TLS WWW server authentication`,[p.id_kp_clientAuth]:`TLS WWW client authentication`,[p.id_kp_codeSigning]:`Code Signing`,[p.id_kp_emailProtection]:`E-mail Protection`,[p.id_kp_timeStamping]:`Time Stamping`,[p.id_kp_OCSPSigning]:`OCSP Signing`,[m.id_signedData]:`Signed Data`};var ve=class{static serialize(e){return this.serializeObj(e).join(`
131
+ `)}static pad(e=0){return``.padStart(2*e,` `)}static serializeObj(e,t=0){let n=[],r=this.pad(t++),a=``,o=e[L.VALUE];o&&(a=` ${o}`),n.push(`${r}${e[L.NAME]}:${a}`),r=this.pad(t);for(let a in e){if(typeof a==`symbol`)continue;let o=e[a],s=a?`${a}: `:``;if(typeof o==`string`||typeof o==`number`||typeof o==`boolean`)n.push(`${r}${s}${o}`);else if(o instanceof Date)n.push(`${r}${s}${o.toUTCString()}`);else if(Array.isArray(o))for(let e of o)e[L.NAME]=a,n.push(...this.serializeObj(e,t));else if(o instanceof L)o[L.NAME]=a,n.push(...this.serializeObj(o,t));else if(i.BufferSourceConverter.isBufferSource(o))a?(n.push(`${r}${s}`),n.push(...this.serializeBufferSource(o,t+1))):n.push(...this.serializeBufferSource(o,t));else if(`toTextObject`in o){let e=o.toTextObject();e[L.NAME]=a,n.push(...this.serializeObj(e,t))}else throw TypeError(`Cannot serialize data in text format. Unsupported type.`)}return n}static serializeBufferSource(e,t=0){let n=this.pad(t),r=i.BufferSourceConverter.toUint8Array(e),a=[];for(let e=0;e<r.length;){let t=[];for(let n=0;n<16&&e<r.length;n++){n===8&&t.push(``);let i=r[e++].toString(16).padStart(2,`0`);t.push(i)}a.push(`${n}${t.join(` `)}`)}return a}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}};ve.oidSerializer=R,ve.algorithmSerializer=_e;var ye=class e{constructor(...e){if(e.length===1){let t=e[0];this.rawData=n.AsnConvert.serialize(t),this.onInit(t)}else{let t=n.AsnConvert.parse(e[0],e[1]);this.rawData=i.BufferSourceConverter.toArrayBuffer(e[0]),this.onInit(t)}}equal(t){return t instanceof e&&i.isEqual(t.rawData,this.rawData)}toString(e=`text`){switch(e){case`asn`:return n.AsnConvert.toString(this.rawData);case`text`:return ve.serialize(this.toTextObject());case`hex`:return i.Convert.ToHex(this.rawData);case`base64`:return i.Convert.ToBase64(this.rawData);case`base64url`:return i.Convert.ToBase64Url(this.rawData);default:throw TypeError(`Argument 'format' is unsupported value`)}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[``]=this.rawData,e}toTextObjectEmpty(e){return new L(this.getTextName(),{},e)}};ye.NAME=`ASN`;var be=class e extends ye{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.Extension({extnID:e[0],critical:e[1],extnValue:new n.OctetString(i.BufferSourceConverter.toArrayBuffer(e[2]))})),super(t,r.Extension)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.value,e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty(this.critical?`critical`:void 0);return t[L.NAME]===e.NAME&&(t[L.NAME]=R.toString(this.type)),t}},xe,Se=class e{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&e.extractable!==void 0}constructor(){this.items=new Map,this[xe]=`CryptoProvider`,typeof self<`u`&&typeof crypto<`u`?this.set(e.DEFAULT,crypto):typeof global<`u`&&global.crypto&&global.crypto.subtle&&this.set(e.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(t=e.DEFAULT){let n=this.items.get(t.toLowerCase());if(!n)throw Error(`Cannot get Crypto by name '${t}'`);return n}set(t,n){if(typeof t==`string`){if(!n)throw TypeError(`Argument 'value' is required`);this.items.set(t.toLowerCase(),n)}else this.items.set(e.DEFAULT,t);return this}};xe=Symbol.toStringTag,Se.DEFAULT=`default`;let z=new Se,Ce=/^[0-2](?:\.[1-9][0-9]*)+$/;function we(e){return new RegExp(Ce).test(e)}var Te=class{constructor(e={}){this.items={};for(let t in e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return we(e)?e:this.get(e)}register(e,t){this.items[e]=t,this.items[t]=e}};let Ee=new Te;Ee.register(`CN`,`2.5.4.3`),Ee.register(`L`,`2.5.4.7`),Ee.register(`ST`,`2.5.4.8`),Ee.register(`O`,`2.5.4.10`),Ee.register(`OU`,`2.5.4.11`),Ee.register(`C`,`2.5.4.6`),Ee.register(`DC`,`0.9.2342.19200300.100.1.25`),Ee.register(`E`,`1.2.840.113549.1.9.1`),Ee.register(`G`,`2.5.4.42`),Ee.register(`I`,`2.5.4.43`),Ee.register(`SN`,`2.5.4.4`),Ee.register(`T`,`2.5.4.12`);function De(e,t){return`\\${i.Convert.ToHex(i.Convert.FromUtf8String(t)).toUpperCase()}`}function ke(e){return e.replace(/([,+"\\<>;])/g,`\\$1`).replace(/^([ #])/,`\\$1`).replace(/([ ]$)/,`\\$1`).replace(/([\r\n\t])/,De)}var V=class e{static isASCII(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,t={}){this.extraNames=new Te,this.asn=new r.Name;for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e)){let n=t[e];this.extraNames.register(e,n)}this.asn=typeof e==`string`?this.fromString(e):e instanceof r.Name?e:i.BufferSourceConverter.isBufferSource(e)?n.AsnConvert.parse(e,r.Name):this.fromJSON(e)}getField(e){let t=this.extraNames.findId(e)||Ee.findId(e),n=[];for(let e of this.asn)for(let r of e)r.type===t&&n.push(r.value.toString());return n}getName(e){return this.extraNames.get(e)||Ee.get(e)}toString(){return this.asn.map(e=>e.map(e=>`${this.getName(e.type)||e.type}=${e.value.anyValue?`#${i.Convert.ToHex(e.value.anyValue)}`:ke(e.value.toString())}`).join(`+`)).join(`, `)}toJSON(){let e=[];for(let t of this.asn){let n={};for(let e of t){let t=this.getName(e.type)||e.type;n[t]??(n[t]=[]),n[t].push(e.value.anyValue?`#${i.Convert.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(n)}return e}fromString(e){let t=new r.Name,n=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,i=null,a=`,`;for(;i=n.exec(`${e},`);){let[,e,n]=i,o=n[n.length-1];(o===`,`||o===`+`)&&(n=n.slice(0,n.length-1),i[3]=o);let s=i[3];e=this.getTypeOid(e);let c=this.createAttribute(e,n);a===`+`?t[t.length-1].push(c):t.push(new r.RelativeDistinguishedName([c])),a=s}return t}fromJSON(e){let t=new r.Name;for(let n of e){let e=new r.RelativeDistinguishedName;for(let t in n){let r=this.getTypeOid(t),i=n[t];for(let t of i){let n=this.createAttribute(r,t);e.push(n)}}t.push(e)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||``),!e)throw Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(t,n){let a=new r.AttributeTypeAndValue({type:t});if(typeof n==`object`)for(let e in n)switch(e){case`ia5String`:a.value.ia5String=n[e];break;case`utf8String`:a.value.utf8String=n[e];break;case`universalString`:a.value.universalString=n[e];break;case`bmpString`:a.value.bmpString=n[e];break;case`printableString`:a.value.printableString=n[e]}else if(n[0]===`#`)a.value.anyValue=i.Convert.FromHex(n.slice(1));else{let r=this.processStringValue(n);t===this.getName(`E`)||t===this.getName(`DC`)?a.value.ia5String=r:e.isPrintableString(r)?a.value.printableString=r:a.value.utf8String=r}return a}processStringValue(e){let t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,`
132
+ `).replace(/\\0d/gi,`\r`).replace(/\\0g/gi,` `).replace(/\\(.)/g,`$1`)}toArrayBuffer(){return n.AsnConvert.serialize(this.asn)}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.toArrayBuffer())}};let Ae=`Cannot initialize GeneralName from ASN.1 data.`,je=`${Ae} Unsupported string format in use.`,Me=`${Ae} Value doesn't match to GUID regular expression.`,Ne=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Pe=`1.3.6.1.4.1.311.25.1`,Fe=`1.3.6.1.4.1.311.20.2.3`,Ie=`email`,Le=`guid`;var Re=class extends ye{constructor(...e){let t;if(e.length===2)switch(e[0]){case`dn`:{let r=new V(e[1]).toArrayBuffer(),i=n.AsnConvert.parse(r,p.Name);t=new p.GeneralName({directoryName:i});break}case`dns`:t=new p.GeneralName({dNSName:e[1]});break;case Ie:t=new p.GeneralName({rfc822Name:e[1]});break;case Le:{let r=new RegExp(Ne,`i`).exec(e[1]);if(!r)throw Error(`Cannot parse GUID value. Value doesn't match to regular expression`);let a=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(``);t=new p.GeneralName({otherName:new p.OtherName({typeId:Pe,value:n.AsnConvert.serialize(new n.OctetString(i.Convert.FromHex(a)))})});break}case`ip`:t=new p.GeneralName({iPAddress:e[1]});break;case`id`:t=new p.GeneralName({registeredID:e[1]});break;case`upn`:t=new p.GeneralName({otherName:new p.OtherName({typeId:Fe,value:n.AsnConvert.serialize(n.AsnUtf8StringConverter.toASN(e[1]))})});break;case`url`:t=new p.GeneralName({uniformResourceIdentifier:e[1]});break;default:throw Error(`Cannot create GeneralName. Unsupported type of the name`)}else t=i.BufferSourceConverter.isBufferSource(e[0])?n.AsnConvert.parse(e[0],p.GeneralName):e[0];super(t)}onInit(e){if(e.dNSName!=null)this.type=`dns`,this.value=e.dNSName;else if(e.rfc822Name!=null)this.type=Ie,this.value=e.rfc822Name;else if(e.iPAddress!=null)this.type=`ip`,this.value=e.iPAddress;else if(e.uniformResourceIdentifier!=null)this.type=`url`,this.value=e.uniformResourceIdentifier;else if(e.registeredID!=null)this.type=`id`,this.value=e.registeredID;else if(e.directoryName!=null)this.type=`dn`,this.value=new V(e.directoryName).toString();else if(e.otherName!=null){if(e.otherName.typeId===Pe){this.type=Le;let t=n.AsnConvert.parse(e.otherName.value,n.OctetString),r=new RegExp(Ne,`i`).exec(i.Convert.ToHex(t));if(!r)throw Error(Me);this.value=r.slice(1).map((e,t)=>t<3?i.Convert.ToHex(new Uint8Array(i.Convert.FromHex(e)).reverse()):e).join(`-`)}else if(e.otherName.typeId===Fe)this.type=`upn`,this.value=n.AsnConvert.parse(e.otherName.value,p.DirectoryString).toString();else throw Error(je)}else throw Error(je)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case`dn`:case`dns`:case Le:case`ip`:case`id`:case`upn`:case`url`:e=this.type.toUpperCase();break;case Ie:e=`Email`;break;default:throw Error(`Unsupported GeneralName type`)}let t=this.value;return this.type===`id`&&(t=R.toString(t)),new L(e,void 0,t)}},ze=class extends ye{constructor(e){let t;if(e instanceof p.GeneralNames)t=e;else if(Array.isArray(e)){let r=[];for(let t of e)if(t instanceof p.GeneralName)r.push(t);else{let e=n.AsnConvert.parse(new Re(t.type,t.value).rawData,p.GeneralName);r.push(e)}t=new p.GeneralNames(r)}else if(i.BufferSourceConverter.isBufferSource(e))t=n.AsnConvert.parse(e,p.GeneralNames);else throw Error(`Cannot initialize GeneralNames. Incorrect incoming arguments`);super(t)}onInit(e){let t=[];for(let n of e){let e=null;try{e=new Re(n)}catch{continue}t.push(e)}this.items=t}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let t of this.items){let n=t.toTextObject(),r=e[n[L.NAME]];Array.isArray(r)||(r=[],e[n[L.NAME]]=r),r.push(n)}return e}};ze.NAME=`GeneralNames`;let H=`-{5}`,Be=`${`${H}BEGIN ([^\\n]+(?=${H}))${H}`}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)${`${H}END \\1${H}`}`;var U=class{static isPem(e){return typeof e==`string`&&new RegExp(Be,`g`).test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,``);let t=new RegExp(Be,`g`),n=[],r=null;for(;r=t.exec(e);){let e=r[3].replace(RegExp(`[\\n]+`,`g`),``),t={type:r[1],headers:[],rawData:i.Convert.FromBase64(e)},a=r[2];if(a){let e=a.split(RegExp(`\\n`,`g`)),n=null;for(let r of e){let[e,i]=r.split(/:(.*)/);if(i===void 0){if(!n)throw Error(`Cannot parse PEM string. Incorrect header value`);n.value+=e.trim()}else n&&t.headers.push(n),n={key:e,value:i.trim()}}n&&t.headers.push(n)}n.push(t)}return n}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){let t=this.decode(e);if(!t.length)throw RangeError(`PEM string doesn't contain any objects`);return t[0]}static encode(e,t){if(Array.isArray(e)){let n=[];return t?e.forEach(e=>{if(!i.BufferSourceConverter.isBufferSource(e))throw TypeError(`Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource`);n.push(this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)}))}):e.forEach(e=>{if(!(`type`in e))throw TypeError(`Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut`);n.push(this.encodeStruct(e))}),n.join(`
133
133
  `)}if(!t)throw Error(`Required argument 'tag' is missed`);return this.encodeStruct({type:t,rawData:i.BufferSourceConverter.toArrayBuffer(e)})}static encodeStruct(e){let t=e.type.toLocaleUpperCase(),n=[];if(n.push(`-----BEGIN ${t}-----`),e.headers?.length){for(let t of e.headers)n.push(`${t.key}: ${t.value}`);n.push(``)}let r=i.Convert.ToBase64(e.rawData),a,o=0,s=[];for(;o<r.length&&(r.length-o<64?a=r.substring(o):(a=r.substring(o,o+64),o+=64),a.length!==0)&&(s.push(a),!(a.length<64)););return n.push(...s),n.push(`-----END ${t}-----`),n.join(`
134
- `)}};U.CertificateTag=`CERTIFICATE`,U.CrlTag=`CRL`,U.CertificateRequestTag=`CERTIFICATE REQUEST`,U.PublicKeyTag=`PUBLIC KEY`,U.PrivateKeyTag=`PRIVATE KEY`;var W=class e extends be{static isAsnEncoded(e){return i.BufferSourceConverter.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(U.isPem(e))return U.decode(e)[0];if(i.Convert.isHex(e))return i.Convert.FromHex(e);if(i.Convert.isBase64(e))return i.Convert.FromBase64(e);if(i.Convert.isBase64Url(e))return i.Convert.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=i.Convert.ToBinary(e);return U.isPem(t)?U.decode(t)[0]:i.Convert.isHex(t)?i.Convert.FromHex(t):i.Convert.isBase64(t)?i.Convert.FromBase64(t):i.Convert.isBase64Url(t)?i.Convert.FromBase64Url(t):i.BufferSourceConverter.toArrayBuffer(e)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return U.encode(this.rawData,this.tag);default:return super.toString(e)}}},Ve=class e extends W{static async create(t,n=z.get()){if(t instanceof e)return t;if(R.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(i.BufferSourceConverter.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){W.isAsnEncoded(e)?super(e,r.SubjectPublicKeyInfo):super(e),this.tag=U.PublicKeyTag}async export(...e){let t,i=[`verify`],a={hash:`SHA-256`,...this.algorithm};e.length>1?(a=e[0]||a,i=e[1]||i,t=e[2]||z.get()):t=e[0]||z.get();let o=this.rawData,c=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return c.algorithm.algorithm===s.id_RSASSA_PSS&&(o=He(c,o)),t.subtle.importKey(`spki`,o,a,!0,i)}onInit(e){let t=l.container.resolve(b),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case s.id_rsaEncryption:{let t=n.AsnConvert.parse(e.subjectPublicKey,s.RSAPublicKey),a=i.BufferSourceConverter.toUint8Array(t.modulus);r.publicExponent=i.BufferSourceConverter.toUint8Array(t.publicExponent),r.modulusLength=(a[0]?a:a.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,i=`SHA-1`;e.length===1?typeof e[0]==`string`?(i=e[0],t=z.get()):t=e[0]:e.length===2?(i=e[0],t=e[1]):t=z.get();let a=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return await t.subtle.digest(i,a.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);switch(e.Algorithm=ye.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case o.id_ecPublicKey:e[`EC Point`]=t.subjectPublicKey;break;case s.id_rsaEncryption:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function He(e,t){return e.algorithm=new r.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null}),t=n.AsnConvert.serialize(e),t}var Ue=class e extends xe{static async create(t,n=!1,r=z.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new p.AuthorityKeyIdentifier({keyIdentifier:new p.KeyIdentifier(i.Convert.FromHex(e[0]))});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=t.name instanceof ze?n.AsnConvert.parse(t.name.rawData,p.GeneralNames):t.name,a=new p.AuthorityKeyIdentifier({authorityCertIssuer:r,authorityCertSerialNumber:i.Convert.FromHex(t.serialNumber)});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(a))}}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.AuthorityKeyIdentifier);t.keyIdentifier&&(this.keyId=i.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?i.Convert.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=n.AsnConvert.parse(this.value,p.AuthorityKeyIdentifier);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new ze(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Ue.NAME=`Authority Key Identifier`;var We=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.BasicConstraints);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new r.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(r.id_ce_basicConstraints,e[2],n.AsnConvert.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e[`Path Length`]=this.pathLength),e}};We.NAME=`Basic Constraints`,e.ExtendedKeyUsage=void 0,(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(e.ExtendedKeyUsage||={});var Ge=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.ExtendedKeyUsage);this.usages=t.map(e=>e)}else{let t=new p.ExtendedKeyUsage(e[0]);super(p.id_ce_extKeyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>L.toString(e)).join(`, `),e}};Ge.NAME=`Extended Key Usages`,e.KeyUsageFlags=void 0,(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(e.KeyUsageFlags||={});var Ke=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.KeyUsage);this.usages=t.toNumber()}else{let t=new r.KeyUsage(e[0]);super(r.id_ce_keyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,r.KeyUsage).toJSON().join(`, `),e}};Ke.NAME=`Key Usages`;var qe=class e extends xe{static async create(t,n=!1,r=z.get()){let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier);this.keyId=i.Convert.ToHex(t)}else{let t=typeof e[0]==`string`?i.Convert.FromHex(e[0]):e[0],r=new p.SubjectKeyIdentifier(t);super(p.id_ce_subjectKeyIdentifier,e[1],n.AsnConvert.serialize(r)),this.keyId=i.Convert.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier),e}};qe.NAME=`Subject Key Identifier`;var Je=class extends xe{constructor(...e){i.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(p.id_ce_subjectAltName,e[1],new ze(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.SubjectAlternativeName);this.names=new ze(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Je.NAME=`Subject Alternative Name`;var G=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new xe(e),n=this.items.get(t.type);return n?new n(e):t}};G.items=new Map;var Ye=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.CertificatePolicies);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],r=e[1]??!1,i=new p.CertificatePolicies(t.map(e=>new p.PolicyInformation({policyIdentifier:e})));super(p.id_ce_certificatePolicies,r,n.AsnConvert.serialize(i)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new I(``,{},L.toString(e))),e}};Ye.NAME=`Certificate Policies`,G.register(p.id_ce_certificatePolicies,Ye);var Xe=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new p.DistributionPoint({distributionPoint:new p.DistributionPointName({fullName:[new p.GeneralName({uniformResourceIdentifier:e})]})})),r=new p.CRLDistributionPoints(t);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(r))}else{let t=new p.CRLDistributionPoints(e[0]);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.CRLDistributionPoints);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new Re(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Xe.NAME=`CRL Distribution Points`;var Ze=class extends xe{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof p.AuthorityInfoAccessSyntax){let t=new p.AuthorityInfoAccessSyntax(e[0]);super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=new p.AuthorityInfoAccessSyntax;$e(r,t,p.id_ad_ocsp,`ocsp`),$e(r,t,p.id_ad_caIssuers,`caIssuers`),$e(r,t,p.id_ad_timeStamping,`timeStamping`),$e(r,t,p.id_ad_caRepository,`caRepository`),super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(r))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],n.AsnConvert.parse(e.extnValue,p.AuthorityInfoAccessSyntax).forEach(e=>{switch(e.accessMethod){case p.id_ad_ocsp:this.ocsp.push(new Re(e.accessLocation));break;case p.id_ad_caIssuers:this.caIssuers.push(new Re(e.accessLocation));break;case p.id_ad_timeStamping:this.timeStamping.push(new Re(e.accessLocation));break;case p.id_ad_caRepository:this.caRepository.push(new Re(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Qe(e,`OCSP`,this.ocsp),this.caIssuers.length&&Qe(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&Qe(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&Qe(e,`CA Repository`,this.caRepository),e}};Ze.NAME=`Authority Info Access`;function Qe(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new I(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[I.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function $e(e,t,r,i){let a=t[i];a&&(Array.isArray(a)?a:[a]).forEach(t=>{typeof t==`string`&&(t=new Re(`url`,t)),e.push(new p.AccessDescription({accessMethod:r,accessLocation:n.AsnConvert.parse(t.rawData,p.GeneralName)}))})}var et=class e extends be{constructor(...e){let t;if(i.BufferSourceConverter.isBufferSource(e[0]))t=i.BufferSourceConverter.toArrayBuffer(e[0]);else{let a=e[0],o=Array.isArray(e[1])?e[1].map(e=>i.BufferSourceConverter.toArrayBuffer(e)):[];t=n.AsnConvert.serialize(new r.Attribute({type:a,values:o}))}super(t,r.Attribute)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new I(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[I.NAME]===e.NAME&&(t[I.NAME]=L.toString(this.type)),t}};et.NAME=`Attribute`;var tt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=new _.ChallengePassword({printableString:e[0]});super(_.id_pkcs9_at_challengePassword,[n.AsnConvert.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],_.ChallengePassword);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[I.VALUE]=this.password,e}};tt.NAME=`Challenge Password`;var nt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=e[0],r=new p.Extensions;for(let e of t)r.push(n.AsnConvert.parse(e.rawData,p.Extension));super(_.id_pkcs9_at_extensionRequest,[n.AsnConvert.serialize(r)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],p.Extensions);this.items=e.map(e=>G.create(n.AsnConvert.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[I.NAME]]=n;return e}};nt.NAME=`Extensions`;var rt=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new et(e),n=this.items.get(t.type);return n?new n(e):t}};rt.items=new Map;let it=`crypto.signatureFormatter`;var at=class{toAsnSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}},ot;e.RsaAlgorithm=ot=class{static createPssParams(e,t){let i=ot.getHashAlgorithm(e);return i?new g.RsaSaPssParams({hashAlgorithm:i,maskGenAlgorithm:new r.AlgorithmIdentifier({algorithm:g.id_mgf1,parameters:n.AsnConvert.serialize(i)}),saltLength:t}):null}static getHashAlgorithm(e){let t=l.container.resolve(b);return typeof e==`string`?t.toAsnAlgorithm({name:e}):typeof e==`object`&&e&&`name`in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash==`string`)t=e.hash;else if(e.hash&&typeof e.hash==`object`&&`name`in e.hash&&typeof e.hash.name==`string`)t=e.hash.name.toUpperCase();else throw Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:g.id_sha1WithRSAEncryption,parameters:null});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:g.id_sha256WithRSAEncryption,parameters:null});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:g.id_sha384WithRSAEncryption,parameters:null});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:g.id_sha512WithRSAEncryption,parameters:null})}}else return new r.AlgorithmIdentifier({algorithm:g.id_rsaEncryption,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength==`number`))throw Error(`Cannot get 'saltLength' from 'alg' argument`);let t=ot.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:n.AsnConvert.serialize(t)})}return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case g.id_rsaEncryption:return{name:`RSASSA-PKCS1-v1_5`};case g.id_sha1WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case g.id_sha256WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case g.id_sha384WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case g.id_sha512WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case g.id_RSASSA_PSS:if(e.parameters){let t=n.AsnConvert.parse(e.parameters,g.RsaSaPssParams);return{name:`RSA-PSS`,hash:l.container.resolve(b).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}},e.RsaAlgorithm=ot=c.__decorate([l.injectable()],e.RsaAlgorithm),l.container.registerSingleton(v,e.RsaAlgorithm),e.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:s.id_sha1});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:s.id_sha256});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:s.id_sha384});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:s.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case s.id_sha1:return{name:`SHA-1`};case s.id_sha256:return{name:`SHA-256`};case s.id_sha384:return{name:`SHA-384`};case s.id_sha512:return{name:`SHA-512`}}return null}},e.ShaAlgorithm=c.__decorate([l.injectable()],e.ShaAlgorithm),l.container.registerSingleton(v,e.ShaAlgorithm);var ct=class e{addPadding(e,t){let n=i.BufferSourceConverter.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r}removePadding(e,t=!1){let n=i.BufferSourceConverter.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,r){if(t.name===`ECDSA`){let a=t.namedCurve,s=e.namedCurveSize.get(a)||e.defaultNamedCurveSize,c=new o.ECDSASigValue,l=i.BufferSourceConverter.toUint8Array(r);return c.r=this.removePadding(l.slice(0,s),!0),c.s=this.removePadding(l.slice(s,s+s),!0),n.AsnConvert.serialize(c)}return null}toWebSignature(t,r){if(t.name===`ECDSA`){let a=n.AsnConvert.parse(r,o.ECDSASigValue),s=t.namedCurve,c=e.namedCurveSize.get(s)||e.defaultNamedCurveSize,l=this.addPadding(c,this.removePadding(a.r)),u=this.addPadding(c,this.removePadding(a.s));return i.combine(l,u)}return null}};ct.namedCurveSize=new Map,ct.defaultNamedCurveSize=32;let lt=`1.3.101.110`,ut=`1.3.101.111`,dt=`1.3.101.112`,ft=`1.3.101.113`;e.EdAlgorithm=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=dt;break;case`x25519`:t=lt;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=dt;break;case`ed448`:t=ft}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=lt;break;case`x448`:t=ut}}return t?new r.AlgorithmIdentifier({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dt:return{name:`Ed25519`};case ft:return{name:`EdDSA`,namedCurve:`Ed448`};case lt:return{name:`X25519`};case ut:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}},e.EdAlgorithm=c.__decorate([l.injectable()],e.EdAlgorithm),l.container.registerSingleton(v,e.EdAlgorithm);var pt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,d.CertificationRequest):super(e),this.tag=U.CertificateRequestTag}onInit(e){this.tbs=n.AsnConvert.serialize(e.certificationRequestInfo),this.publicKey=new Ve(e.certificationRequestInfo.subjectPKInfo);let t=l.container.resolve(b);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>rt.create(n.AsnConvert.serialize(e)));let r=this.getAttribute(u.id_pkcs9_at_extensionRequest);this.extensions=[],r instanceof nt&&(this.extensions=r.items),this.subjectName=new V(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=z.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=l.container.resolveAll(it).reverse(),i=null;for(let e of r)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,d.CertificationRequest),i=t.certificationRequestInfo,a=new I(``,{Version:`${r.Version[i.version]} (${i.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new I(``);for(let t of this.attributes){let n=t.toTextObject();e[n[I.NAME]]=n}a.Attributes=e}return e.Data=a,e.Signature=new I(``,{Algorithm:ye.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};pt.NAME=`PKCS#10 Certificate Request`;var mt=class{static async create(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);let i=await t.subtle.exportKey(`spki`,e.keys.publicKey),a=new d.CertificationRequest({certificationRequestInfo:new d.CertificationRequestInfo({subjectPKInfo:n.AsnConvert.parse(i,r.SubjectPublicKeyInfo)})});if(e.name){let t=e.name instanceof V?e.name:new V(e.name);a.certificationRequestInfo.subject=n.AsnConvert.parse(t.toArrayBuffer(),r.Name)}if(e.attributes)for(let t of e.attributes)a.certificationRequestInfo.attributes.push(n.AsnConvert.parse(t.rawData,r.Attribute));if(e.extensions&&e.extensions.length){let t=new r.Attribute({type:u.id_pkcs9_at_extensionRequest}),i=new r.Extensions;for(let t of e.extensions)i.push(n.AsnConvert.parse(t.rawData,r.Extension));t.values.push(n.AsnConvert.serialize(i)),a.certificationRequestInfo.attributes.push(t)}let o={...e.signingAlgorithm,...e.keys.privateKey.algorithm};a.signatureAlgorithm=l.container.resolve(b).toAsnAlgorithm(o);let s=n.AsnConvert.serialize(a.certificationRequestInfo),c=await t.subtle.sign(o,e.keys.privateKey,s),f=l.container.resolveAll(it).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(o,c),p)break;if(!p)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return a.signature=p,new pt(n.AsnConvert.serialize(a))}},ht=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.Certificate):super(e),this.tag=U.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=n.AsnConvert.serialize(t),this.serialNumber=i.Convert.ToHex(t.serialNumber),this.subjectName=new V(t.subject),this.subject=new V(t.subject).toString(),this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;let a=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!a)throw Error(`Cannot get 'notBefore' value`);this.notBefore=a;let o=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!o)throw Error(`Cannot get 'notAfter' value`);this.notAfter=o,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>G.create(n.AsnConvert.serialize(e)))),this.publicKey=new Ve(t.subjectPublicKeyInfo)}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=z.get()){let n,r,a=e.publicKey;try{if(!a)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in a)n={...a.publicKey.algorithm,...this.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);else if(a instanceof Ve)n={...a.algorithm,...this.signatureAlgorithm},r=await a.export(n,[`verify`],t);else if(i.BufferSourceConverter.isBufferSource(a)){let e=new Ve(a);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...a.algorithm,...this.signatureAlgorithm},r=a}catch{return!1}let o=l.container.resolveAll(it).reverse(),s=null;for(let e of o)if(s=e.toWebSignature(n,this.signature),s)break;if(!s)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let c=await t.subtle.verify(this.signatureAlgorithm,r,s,this.tbs);if(e.signatureOnly)return c;{let t=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=z.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.Certificate),i=t.tbsCertificate,a=new I(``,{Version:`${r.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":ye.serializeAlgorithm(i.signature),Issuer:this.issuer,Validity:new I(``,{"Not Before":i.validity.notBefore.getTime(),"Not After":i.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(i.issuerUniqueID&&(a[`Issuer Unique ID`]=i.issuerUniqueID),i.subjectUniqueID&&(a[`Subject Unique ID`]=i.subjectUniqueID),this.extensions.length){let e=new I(``);for(let t of this.extensions){let n=t.toTextObject();e[n[I.NAME]]=n}a.Extensions=e}return e.Data=a,e.Signature=new I(``,{Algorithm:ye.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};ht.NAME=`Certificate`;var gt=class extends Array{constructor(e){if(super(),W.isAsnEncoded(e))this.import(e);else if(e instanceof ht)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new m.SignedData;t.version=1,t.encapContentInfo.eContentType=m.id_data,t.encapContentInfo.eContent=new m.EncapsulatedContent({single:new n.OctetString}),t.certificates=new m.CertificateSet(this.map(e=>new m.CertificateChoices({certificate:n.AsnConvert.parse(e.rawData,r.Certificate)})));let i=new m.ContentInfo({contentType:m.id_signedData,content:n.AsnConvert.serialize(t)}),a=n.AsnConvert.serialize(i);return e===`raw`?a:this.toString(e)}import(e){let t=W.toArrayBuffer(e),r=n.AsnConvert.parse(t,m.ContentInfo);if(r.contentType!==m.id_signedData)throw TypeError(`Cannot parse CMS package. Incoming data is not a SignedData object.`);let i=n.AsnConvert.parse(r.content,m.SignedData);this.clear();for(let e of i.certificates||[])e.certificate&&this.push(new ht(e.certificate))}clear(){for(;this.pop(););}toString(e=`pem`){let t=this.export(`raw`);switch(e){case`pem`:return U.encode(t,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
135
- `);case`asn`:return n.AsnConvert.toString(t);case`hex`:return i.Convert.ToHex(t);case`base64`:return i.Convert.ToBase64(t);case`base64url`:return i.Convert.ToBase64Url(t);case`text`:return ye.serialize(this.toTextObject());default:throw TypeError(`Argument 'format' is unsupported value`)}}toTextObject(){let e=n.AsnConvert.parse(this.export(`raw`),m.ContentInfo),t=n.AsnConvert.parse(e.content,m.SignedData);return new I(`X509Certificates`,{"Content Type":L.toString(e.contentType),Content:new I(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new I(``,{Certificate:this.map(e=>e.toTextObject())})})})}},_t=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=z.get()){let n=new gt(e),r=e;for(;r=await this.findIssuer(r,t);){let e=await r.getThumbprint(t);for(let r of n){let n=await r.getThumbprint(t);if(i.isEqual(e,n))throw Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(r)}return n}async findIssuer(e,t=z.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(p.id_ce_authorityKeyIdentifier);for(let a of this.certificates)if(a.subject===e.issuer){if(r){if(r.keyId){let e=a.getExtension(p.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==r.keyId)continue}else if(r.certId){let e=a.getExtension(p.id_ce_subjectAltName);if(e&&!(r.certId.serialNumber===a.serialNumber&&i.isEqual(n.AsnConvert.serialize(r.certId.name),n.AsnConvert.serialize(e))))continue}}try{let n={...a.publicKey.algorithm,...e.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);if(!await e.verify({publicKey:r,signatureOnly:!0},t))continue}catch{continue}return a}}return null}},vt=class{static async createSelfSigned(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=z.get()){let r;r=e.publicKey instanceof Ve?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:i.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let a=e.serialNumber?i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&a[0]===0&&(a[1]|=128);let o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),c=new p.Certificate({tbsCertificate:new p.TBSCertificate({version:p.Version.v3,serialNumber:a,validity:new p.Validity({notBefore:o,notAfter:s}),extensions:new p.Extensions(e.extensions?.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[]),subjectPublicKeyInfo:n.AsnConvert.parse(r,p.SubjectPublicKeyInfo)})});if(e.subject){let t=e.subject instanceof V?e.subject:new V(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);c.tbsCertificate.issuer=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}let u={hash:`SHA-256`},d=`signingKey`in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},f=l.container.resolve(b);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(d);let m=n.AsnConvert.serialize(c.tbsCertificate),h=`signingKey`in e?await t.subtle.sign(d,e.signingKey,m):e.signature,g=l.container.resolveAll(it).reverse(),_=null;for(let e of g)if(_=e.toAsnSignature(d,h),_)break;if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return c.signatureValue=_,new ht(n.AsnConvert.serialize(c))}};e.X509CrlReason=void 0,(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(e.X509CrlReason||={});var yt=class extends be{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.RevokedCertificate({userCertificate:e[0],revocationDate:new r.Time(e[1]),crlEntryExtensions:e[2]})),super(t,r.RevokedCertificate)}onInit(e){this.serialNumber=i.Convert.ToHex(e.userCertificate),this.revocationDate=e.revocationDate.getTime(),this.extensions=[],e.crlEntryExtensions&&(this.extensions=e.crlEntryExtensions.map(e=>{let t=G.create(n.AsnConvert.serialize(e));switch(t.type){case r.id_ce_cRLReasons:this.reason=n.AsnConvert.parse(t.value,r.CRLReason).reason;break;case r.id_ce_invalidityDate:this.invalidity=n.AsnConvert.parse(t.value,r.InvalidityDate).value}return t}))}},bt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=U.CrlTag}onInit(e){let t=e.tbsCertList;this.tbs=n.AsnConvert.serialize(t),this.version=t.version;let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.tbsCertListSignatureAlgorithm=t.signature,this.certListSignatureAlgorithm=e.signatureAlgorithm,this.signature=e.signature,this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let i=t.thisUpdate.getTime();if(!i)throw Error(`Cannot get 'thisUpdate' value`);this.thisUpdate=i;let a=t.nextUpdate?.getTime();this.nextUpdate=a,this.entries=t.revokedCertificates?.map(e=>new yt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>G.create(n.AsnConvert.serialize(e))))}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e,t=z.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n,r,i=e.publicKey;try{i instanceof ht?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Ve?(n={...i.algorithm,...this.signature},r=await i.export(n,[`verify`])):(n={...i.algorithm,...this.signature},r=i)}catch{return!1}let a=l.container.resolveAll(it).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}findRevoked(e){let t=typeof e==`string`?e:e.serialNumber;for(let e of this.entries)if(e.serialNumber===t)return e;return null}},xt=class{static async create(e,t=z.get()){let a=e.issuer instanceof V?e.issuer:new V(e.issuer),o=new p.CertificateList({tbsCertList:new p.TBSCertList({version:p.Version.v2,issuer:n.AsnConvert.parse(a.toArrayBuffer(),p.Name),thisUpdate:new r.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new r.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new p.Extensions(e.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let t of e.entries){let a=W.toArrayBuffer(t.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(e=>i.isEqual(e.userCertificate,a))>-1)throw Error(`Certificate serial number ${t.serialNumber} already exists in tbsCertList`);let s=new r.RevokedCertificate({userCertificate:a,revocationDate:new r.Time(t.revocationDate||new Date)});if(s.crlEntryExtensions=`extensions`in t&&t.extensions?.length?t.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension)):[],!(t instanceof yt)&&(t.reason&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_cRLReasons,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.CRLReason(t.reason)))})),t.invalidity&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_invalidityDate,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.InvalidityDate(t.invalidity)))})),t.issuer)){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_certificateIssuer,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(n.AsnConvert.parse(t.toArrayBuffer(),p.Name)))}))}o.tbsCertList.revokedCertificates.push(s)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},c=l.container.resolve(b);o.tbsCertList.signature=o.signatureAlgorithm=c.toAsnAlgorithm(s);let u=n.AsnConvert.serialize(o.tbsCertList),d=await t.subtle.sign(s,e.signingKey,u),f=l.container.resolveAll(it).reverse(),m=null;for(let e of f)if(m=e.toAsnSignature(s,d),m)break;if(!m)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signature=m,new bt(n.AsnConvert.serialize(o))}};G.register(p.id_ce_basicConstraints,We),G.register(p.id_ce_extKeyUsage,Ge),G.register(p.id_ce_keyUsage,Ke),G.register(p.id_ce_subjectKeyIdentifier,qe),G.register(p.id_ce_authorityKeyIdentifier,Ue),G.register(p.id_ce_subjectAltName,Je),G.register(p.id_ce_cRLDistributionPoints,Xe),G.register(p.id_pe_authorityInfoAccess,Ze),rt.register(_.id_pkcs9_at_challengePassword,tt),rt.register(_.id_pkcs9_at_extensionRequest,nt),l.container.registerSingleton(it,at),l.container.registerSingleton(it,ct),ct.namedCurveSize.set(`P-256`,32),ct.namedCurveSize.set(`K-256`,32),ct.namedCurveSize.set(`P-384`,48),ct.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=be,e.AsnDefaultSignatureFormatter=at,e.AsnEcSignatureFormatter=ct,e.Attribute=et,e.AttributeFactory=rt,e.AuthorityInfoAccessExtension=Ze,e.AuthorityKeyIdentifierExtension=Ue,e.BasicConstraintsExtension=We,e.CRLDistributionPointsExtension=Xe,e.CertificatePolicyExtension=Ye,e.ChallengePasswordAttribute=tt,e.CryptoProvider=R,e.DefaultAlgorithmSerializer=ve,e.ExtendedKeyUsageExtension=Ge,e.Extension=xe,e.ExtensionFactory=G,e.ExtensionsAttribute=nt,e.GeneralName=Re,e.GeneralNames=ze,e.KeyUsagesExtension=Ke,e.Name=V,e.NameIdentifier=Te,e.OidSerializer=L,e.PemConverter=U,e.Pkcs10CertificateRequest=pt,e.Pkcs10CertificateRequestGenerator=mt,e.PublicKey=Ve,e.SubjectAlternativeNameExtension=Je,e.SubjectKeyIdentifierExtension=qe,e.TextConverter=ye,e.TextObject=I,e.X509Certificate=ht,e.X509CertificateGenerator=vt,e.X509Certificates=gt,e.X509ChainBuilder=_t,e.X509Crl=bt,e.X509CrlEntry=yt,e.X509CrlGenerator=xt,e.cryptoProvider=z,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=it,e.idEd25519=dt,e.idEd448=ft,e.idX25519=lt,e.idX448=ut}));De(),ca();var la;(function(e){e.Der=`der`,e.Raw=`raw`})(la||={});const ua=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,da=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,fa=()=>ua?`browser`:da?`node`:`purejs`,pa=async(e,t)=>{let n=t??fa();switch(n){case`browser`:return(await import(`./webcrypto-DbGdF7IH.mjs`)).signWithApiKey(e);case`node`:return(await import(`./nodecrypto-CoPNNPzf.mjs`)).signWithApiKey(e);case`purejs`:return(await import(`./purejs-xzcexc4T.mjs`)).signWithApiKey(e);default:throw Error(`Unsupported runtime: ${n}`)}};var ma=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n={publicKey:this.apiPublicKey,scheme:`SIGNATURE_SCHEME_TK_API_P256`,signature:t};return{stampHeaderName:`X-Stamp`,stampHeaderValue:F(JSON.stringify(n))}}async sign(e,t){switch(t){case la.Raw:{let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=Te(t);return s(n)}case la.Der:return pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},ha=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function ga(){let e=p(`prime256v1`);return e.generateKeys(),va(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const _a=/^[0-9a-f]{64}$/i;function va(e){if(!_a.test(e))throw new ha(`P-256 private key must be 64 hex characters`);let t=e.toLowerCase(),n=p(`prime256v1`);try{n.setPrivateKey(Buffer.from(t,`hex`))}catch{throw new ha(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function ya(e){try{let t=f.convertKey(e,`prime256v1`,`hex`,`hex`,`uncompressed`),n=Buffer.isBuffer(t)?t:Buffer.from(t,`hex`);return n.length===65?n:null}catch{return null}}function ba(e){let t=ya(e);if(t===null)throw new ha(`value is not a valid P-256 public key`);return xa(t)}function xa(e){let t=e.subarray(1,33).toString(`base64url`),n=e.subarray(33,65).toString(`base64url`);return m(`sha256`).update(`{"crv":"P-256","kty":"EC","x":"${t}","y":"${n}"}`,`utf8`).digest(`base64url`)}const Sa=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,Ca=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function wa(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function Ta(e){let t=Ea(e.keypair),n={...t,identityUrl:Da(e.identityUrl??wa(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=Oa(n,{method:e.method,url:e.url,body:t},{nonce:g(16).toString(`base64url`),createdAt:new Date}),i=new Headers(e.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return new Request(e,{headers:i})}}}function Ea(e){let t=ya(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:Ma(t,e.privateKeyHex),keyId:xa(t)}}function Da(e){if(!Sa.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function Oa(e,t,n){if(!Ca.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ka(t.body),i=`"${e.identityUrl}"`,a=`("@method" "@target-uri" "content-digest" "signature-agent");created=${Math.floor(n.createdAt.getTime()/1e3)};keyid="${e.keyId}";nonce="${n.nonce}";alg="ecdsa-p256-sha256"`,o=[`"@method": ${t.method.toUpperCase()}`,`"@target-uri": ${Aa(new URL(t.url))}`,`"content-digest": ${r}`,`"signature-agent": ${i}`,`"@signature-params": ${a}`].join(`
136
- `),s=_(`sha256`,Buffer.from(o,`utf8`),{key:e.signingKey,dsaEncoding:`ieee-p1363`});return{"Content-Digest":r,"Signature-Agent":i,"Signature-Input":`sig=${a}`,Signature:`sig=:${s.toString(`base64`)}:`}}function ka(e){return`sha-256=:${m(`sha256`).update(e??``).digest(`base64`)}:`}function Aa(e){return`${e.protocol}//${ja(e)}${e.pathname}${e.search}`}function ja(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function Ma(e,t){return h({key:{kty:`EC`,crv:`P-256`,d:Buffer.from(t,`hex`).toString(`base64url`),x:e.subarray(1,33).toString(`base64url`),y:e.subarray(33,65).toString(`base64url`)},format:`jwk`})}var Na=`0.3.0`;const Pa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Fa=Na;function Ia(e,t){if(!Pa.test(e))throw Error(`${t} must be a valid HTTP token`)}function La(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Ra(e){let t=`catena-agent-client/${Fa}`;if(!e)return t;Ia(e.name,`appInfo.name`),e.version!==void 0&&Ia(e.version,`appInfo.version`),e.url!==void 0&&La(e.url,`appInfo.url`);let n=e.version===void 0?e.name:`${e.name}/${e.version}`;return`${e.url===void 0?n:`${n} (${e.url})`} ${t}`}const za=d.object({paymentCredential:d.object({protocol:d.picklist([`mpp`,`x402`]),value:d.string()})});function Ba(e,t){let n=d.safeParse(za,e);return n.success&&n.output.paymentCredential.protocol===t?n.output.paymentCredential.value:void 0}const Va=`offer-receipt`,Ha=8192,Ua=d.pipe(d.string(),d.maxLength(Ha),d.regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,`Expected a JWS compact serialization`)),Wa=d.optional(d.pipe(d.number(),d.integer(),d.minValue(0))),Ga=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{130}$/,`Expected a 65-byte hex signature`)),Ka=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),acceptIndex:Wa,payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),acceptIndex:Wa,signature:Ua})]),qa=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),signature:Ua})]),Ja=d.object({[Va]:d.object({info:d.object({offers:d.array(d.unknown())})})}),Ya=d.object({[Va]:d.object({info:d.object({receipt:d.unknown()})})}),Xa=d.looseObject({version:d.literal(1),resourceUrl:d.pipe(d.string(),d.maxLength(2048)),scheme:d.pipe(d.string(),d.maxLength(64)),network:d.pipe(d.string(),d.maxLength(64)),asset:d.pipe(d.string(),d.maxLength(128)),payTo:d.pipe(d.string(),d.maxLength(128)),amount:d.pipe(d.string(),d.regex(/^\d+$/),d.maxLength(78)),validUntil:d.optional(d.pipe(d.number(),d.integer(),d.minValue(0)))});function Za(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Qa(e){if(e.format===`eip712`){let t=d.safeParse(Xa,e.payload);return t.success?t.output:void 0}let t=e.signature.split(`.`)[1];try{let e=d.safeParse(Xa,Za(t));return e.success?e.output:void 0}catch{return}}function $a(e,t){return e.toLowerCase()===t.toLowerCase()}function eo(e,t){return e.scheme===t.scheme&&e.network===t.network&&$a(e.asset,t.asset)&&$a(e.payTo,t.payTo)&&e.amount===t.amount}function to(e){return new TextEncoder().encode(JSON.stringify(e)).length<=Ha}function no(e,t){let n=d.safeParse(Ja,e);if(n.success)for(let e of n.output[Va].info.offers){let n=d.safeParse(Ka,e);if(!n.success)continue;let r=Qa(n.output);if(r!==void 0&&eo(r,t)&&to(n.output))return n.output}}function ro(e){let t=d.safeParse(Ya,e);if(!t.success)return;let n=d.safeParse(qa,t.output[Va].info.receipt);if(n.success&&to(n.output))return n.output}const io=d.pipe(d.string(),d.regex(/\S/,`Response enum values must not be blank`));function ao(e){return io}const oo=d.object({amount:d.string(),asset_id:d.string()}),so=d.pipe(d.string(),d.isoTimestamp()),co=d.object({success:d.literal(!0)}),lo=d.object({id:d.string(),name:d.string(),status:d.string(),organizationId:d.string()}),uo=d.object({agent:lo}),fo=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],po=d.object({id:d.string(),ruleType:ao(fo),thresholdAmount:d.optional(oo),thresholdCount:d.optional(d.number()),action:ao([`block`,`require_approval`]),requiredApprovals:d.number(),accountAggregationScope:ao([`per_account`,`across_accounts`]),actorAggregationScope:ao([`per_agent`,`per_policy`]),displayOrder:d.number()}),mo=d.object({id:d.string(),organizationId:d.string(),policyId:d.string(),capability:ao([`query_balance`,`read`,`send`,`transfer`]),accountId:d.string(),rules:d.array(po),createdAt:so,updatedAt:so}),ho=[`allow`,`block`,`require_approval`],go=[`open`,`restricted`],_o=ao(ho),vo=d.object({mode:ao(go),allowedCounterparties:d.optional(d.array(d.string())),createAction:d.optional(_o),requestPaymentDetailsAction:d.optional(_o),allowCreate:d.optional(d.boolean())}),yo=d.object({id:d.optional(d.string()),description:d.optional(d.string()),version:d.optional(d.number()),name:d.string(),capabilities:d.array(d.string()),counterpartyRules:d.optional(vo),policyCapabilities:d.array(mo),kind:d.optional(d.picklist([`base`,`override`])),expiresAt:d.optional(d.string())}),bo=d.object({policy:yo}),xo=d.object({accounts:d.array(d.object({id:d.string(),name:d.string(),type:d.string(),currency:d.string()}))}),So=d.object({accountId:d.string(),balance:oo,balances:d.optional(d.object({total:oo,available:oo}))}),Co=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],wo=[`pending`,`processing`,`completed`,`failed`,`reversed`],To=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],Eo=[`ach`,`wire`,`on-chain`],Do=d.object({id:d.string(),type:ao(Co),action:d.optional(d.string()),status:ao(wo),movementStatus:ao(To),direction:d.picklist([`incoming`,`outgoing`]),amount:oo,fee:oo,currency:d.string(),network:d.optional(d.string()),counterpartyName:d.optional(d.string()),method:d.optional(ao([`ach`,`wire`,`on-chain`])),memo:d.optional(d.string()),description:d.optional(d.string()),txHash:d.optional(d.string()),createdAt:so,completedAt:d.optional(so)}),Oo=d.object({accountId:d.string(),transactions:d.array(Do),total:d.number()}),ko=d.object({accountId:d.string(),address:d.string(),liquidationAddressId:d.optional(d.string()),source:ao([`wallet`,`liquidation`])}),Ao=d.object({type:d.literal(`wallet`),walletAddress:d.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)),network:d.custom(e=>typeof e==`string`&&e.length>0)}),jo=d.object({id:d.string(),name:d.string(),status:d.optional(d.string()),rails:d.array(d.object({id:d.string(),type:d.string(),walletAddress:d.optional(d.string()),network:d.optional(d.string()),bankName:d.optional(d.string()),accountNumber:d.optional(d.string())}))}),Mo=d.object({counterparties:d.array(jo)}),No=d.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),Po=d.object({type:d.literal(`submit_stamp`),signingRequestId:d.string(),signer:d.object({algorithm:d.literal(`p256`),publicKeyHex:d.string()}),preparedBody:d.object({body:d.string(),bodyHash:d.string(),expiresAt:so,prepareToken:d.string()})}),Fo=[`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`mpp`,`policy_override`],Io=d.object({id:d.string(),sourceNetwork:d.string(),destinationNetwork:d.string(),state:ao([`burning`,`attesting`,`minting`,`ready`,`delivering`,`delivered`,`failed`,`manual_review`]),nextStep:ao([`wait`,`continue`,`done`,`blocked`]),readyAt:d.nullable(so),deliveredAt:d.nullable(so),failureReason:d.nullable(d.string())}),Lo=d.object({id:d.string(),status:No,crossChain:Io,nextAction:Po}),Ro=d.object({id:d.string(),accountId:d.optional(d.string()),type:ao(Fo),status:No,reasons:d.array(d.string()),expiresAt:d.optional(d.nullable(so),null),replayed:d.optional(d.boolean(),!1),data:d.optional(d.nullable(d.record(d.string(),d.unknown())),null),metadata:d.optional(d.object({dataUrl:d.nullable(d.string())})),crossChain:d.optional(Io),nextAction:d.optional(Po)});function zo(e){let{nextAction:t,...n}=e;return n}const Bo=d.object({x402:d.object({paymentSignature:d.string()})});function Vo(e){let t=Ba(e,`x402`);if(t!==void 0)return t;let n=d.safeParse(Bo,e);return n.success?n.output.x402.paymentSignature:void 0}const Ho=d.picklist(Eo),Uo=d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),method:Ho,memo:d.optional(d.string()),description:d.optional(d.string())}),Wo=d.object({type:d.literal(`transfer`),accountId:d.string(),toAccountId:d.string(),amount:d.string(),memo:d.optional(d.string()),description:d.optional(d.string())}),Go={type:d.literal(`create_counterparty`),name:d.string()},Ko=d.union([d.object({...Go,email:d.optional(d.string()),rail:d.nonOptional(d.unknown())}),d.object({...Go,email:d.string()})]),qo=d.object({type:d.literal(`request_counterparty_details`),counterpartyId:d.string(),methods:d.pipe(d.object({bank:d.boolean(),wallet:d.boolean()}),d.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),Jo=d.looseObject({scheme:d.string(),network:d.string(),asset:d.string(),amount:d.string(),payTo:d.string(),maxTimeoutSeconds:d.number()}),Yo=d.looseObject({url:d.string(),serviceName:d.fallback(d.optional(d.pipe(d.string(),d.maxLength(255))),void 0)}),Xo=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{40}$/,`Expected a 20-byte hex address`)),Zo=d.pipe(d.string(),d.maxLength(78),d.regex(/^(0|[1-9]\d*)$/,`Expected a canonical decimal integer string`)),Qo=d.object({from:Xo,to:Xo,value:Zo,validAfter:Zo,validBefore:Zo,nonce:d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{64}$/,`Expected a 32-byte hex nonce`))}),$o=d.object({type:d.literal(`x402`),accountId:d.string(),paymentRequirements:Jo,resource:d.optional(Yo),authorization:d.optional(Qo),signedOffer:d.optional(Ka)}),es=d.object({id:d.string(),realm:d.string(),method:d.picklist([`evm`,`usdc`]),intent:d.literal(`charge`),request:d.string(),description:d.optional(d.string()),digest:d.optional(d.string()),expires:d.string(),header:d.optional(d.literal(`Payment-Authorization`)),opaque:d.optional(d.string())}),ts=d.object({url:d.string(),serviceName:d.optional(d.string())}),ns=d.object({type:d.literal(`mpp`),accountId:d.string(),challenge:es,resource:d.optional(ts)}),rs=[`send`,`transfer`],is=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(rs),limitType:d.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:d.strictObject({amount:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/),d.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:d.literal(`USD`)})}),as=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(rs),limitType:d.picklist([`hourly_count`,`daily_count`]),newLimit:d.strictObject({count:d.pipe(d.number(),d.integer(),d.minValue(1))})}),os=d.pipe(d.array(d.union([is,as])),d.minLength(1),d.maxLength(10),d.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),ss=d.object({type:d.literal(`policy_override`),operations:os,durationSeconds:d.pipe(d.number(),d.integer(),d.minValue(60),d.maxValue(604800)),reason:d.pipe(d.string(),d.trim(),d.minLength(1),d.maxLength(280))}),cs=d.union([Uo,Wo,Ko,qo,$o,ns,ss]);function ls(e){let t=d.parse(cs,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const us=d.object({intent:Ro});var ds=class extends Error{status;code;details;constructor(e,t,n,r){super(n?`API error ${e} [${n}]: ${t}`:`API error ${e}: ${t}`),this.name=`ApiError`,this.status=e,this.code=n,this.details=r}},fs=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms. The server may still have processed a state-changing request; follow that operation's documented recovery procedure before retrying.`),this.name=`TimeoutError`,this.timeoutMs=e}};const ps=d.object({error:d.nullish(d.string()),message:d.nullish(d.string()),code:d.nullish(d.string()),details:d.nullish(d.record(d.string(),d.unknown()))});async function ms(e){let t=d.safeParse(ps,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new ds(e.status,n.message,n.code??n.error,n.details??void 0):new ds(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0)}async function hs(e,t){if(!e.ok)throw await ms(e);return d.parse(t,await e.json())}var gs=class extends Error{intentId;outcome;constructor(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);super(e.outcome===`not-submitted`?`Intent ${e.intentId} was created but never submitted; no money moved: ${t}`:`Intent ${e.intentId} submission could not be confirmed: ${t}; poll getIntent("${e.intentId}") to a terminal status and resubmit only after blocked or failed`,{cause:e.cause}),this.name=`IntentSubmitError`,this.intentId=e.intentId,this.outcome=e.outcome}};const _s=2147483647;var vs=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){let t=e.timeout===void 0?8e4:e.timeout;if(!Number.isInteger(t)||t<=0||t>_s)throw TypeError(`timeout must be a positive integer no greater than ${_s}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ra(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=va(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=Ta({keypair:this.#r,baseUrl:this.#e,identityUrl:e.identityUrl})}#s(e){let t=new Headers({"Content-Type":`application/json`});for(let[e,n]of Object.entries(this.#n))t.set(e,n);for(let[n,r]of Object.entries(e??{}))t.set(n,r);return t.set(`User-Agent`,this.#t),t.delete(`Authorization`),t}async#c(e){let t=new URL(`${this.#e}/v1/agent-api${e.path}`);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,r);let n=new Request(t,{method:e.method,headers:this.#s(e.headers),body:e.body===void 0?null:JSON.stringify(e.body)});return this.#i.sign(n)}async#l(e,t){return this.#u(await this.#c(e),t)}async#u(e,t){let n=new AbortController,r=new Request(e,{signal:n.signal}),i;try{let e=new Promise((e,t)=>{i=setTimeout(()=>{let e=new fs(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>hs(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},uo)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},co)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},bo)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},xo)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},So)}async listAccountTransactions(e,t={}){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/transactions`,query:{start:t.start,end:t.end,limit:t.limit?.toString(),offset:t.offset?.toString()}},Oo)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},ko)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Mo)}async submitIntent(e){let t=await this.#d({...e,idempotencyKey:e.idempotencyKey??crypto.randomUUID()}),n=t.nextAction;if(!n)return zo(t);let r;try{let e=await this.#f(n);r=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(t.id)}/submit-stamp`,body:{preparedBody:n.preparedBody,stamp:e}})}catch(e){throw new gs({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#p(r,t.replayed)}catch(e){throw new gs({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:ls(e.action)},headers:{"Idempotency-Key":e.idempotencyKey}},Ro)}async#f(e){if(e.signer.publicKeyHex.toLowerCase()!==this.#r.publicKeyHex.toLowerCase())throw Error(`Local signer public key does not match requested signer ${e.signer.publicKeyHex}; linked credential has ${this.#r.publicKeyHex}`);let t=await new ma({apiPublicKey:this.#r.publicKeyHex,apiPrivateKey:this.#r.privateKeyHex}).stamp(e.preparedBody.body);return{publicKeyHex:this.#r.publicKeyHex,stampHeaderName:t.stampHeaderName,stampHeaderValue:t.stampHeaderValue}}async#p(e,t){let n=zo((await this.#u(e,us)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return zo(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},Ro))}async continueIntent(e){let t=await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/continue`,headers:{"Idempotency-Key":e.idempotencyKey??crypto.randomUUID()}},Lo),n;try{let r=await this.#f(t.nextAction);n=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/submit-stamp`,body:{preparedBody:t.nextAction.preparedBody,stamp:r}})}catch(t){throw new gs({intentId:e.intentId,outcome:`not-submitted`,cause:t})}try{return await this.#p(n,!1)}catch(t){throw new gs({intentId:e.intentId,outcome:`unknown`,cause:t})}}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},co)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash,...e.receipt!==void 0&&{receipt:e.receipt}}},co)}};function ys(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ha(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new vs({...e,privateKeyHex:t})}function bs(e){let t=se(e);return e instanceof ds&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(bs(e)),process.exit(1)}const xs=d.string(),Ss=d.boolean();function Cs(e){return e===void 0}function ws(e){return e.issues?.[0]?.message??`Invalid value`}function Ts(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Es(e,t,n,r){let i=d.safeParse(e,t);return i.success?i.output:Ts(n,ws(i),t,r)}function Ds(e,t){let n=t.schema??xs;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=Cs(e)?t.default:e;if(Cs(i)){t.required===!0&&X(`${r} is required`);return}return Es(n,i,r,t.showValueInError===!0)}}}function Z(e){return Ds(`string`,e)}function Os(e){return Ds(`positional`,e)}function ks(e){let t=e.schema??xs;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Es(t,n,r,e.showValueInError===!0))}}}function As(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=Cs(t)?e.default:t;if(Cs(r)){e.required===!0&&X(`${n} is required`);return}return Es(Ss,r,n,!1)}}}function js(e){return Ms(`string`,e)}function Ms(e,t){return Ds(e,{description:t.description,required:t.required,default:t.default,schema:d.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function Ns(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Ps(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z0-9])([A-Z][a-z])/g,`$1 $2`).split(/[ _-]/).filter(e=>e.length>0)}function Fs(e){return Ps(e).join(`-`).toLowerCase()}function Is(e){return Ps(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Ls(e){return[`--${e}`,`--${Fs(e)}`,`--${Is(e)}`]}function Rs(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function zs(e,t,n){let r=e.indexOf(`--`),i=r===-1?e.length:r,a=[...e.slice(0,i).filter(e=>!e.startsWith(`--no-`)),...e.slice(i)],o=new Set(Ls(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Ls(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=Rs(t);if(o.has(n)){r===void 0?(c.push(a[e+1]??``),e++):c.push(r);continue}s.has(n)&&r===void 0&&e++}return c}function Bs(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Bs(t)])),label(t){return Ns(t,e[t])},parse(t,n){let r=(r,i)=>{if(i.repeatable!==!0)return t[r];if(n===void 0)throw Error(`parse() needs the command's raw argv to collect the repeatable --${r} flag`);return zs(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),Ns(e,t))]))}}}const Vs=Z({description:`Credential profile name`}),Hs=As({description:`Print compact single-line JSON (for piping)`,default:!1}),Us=/^[a-zA-Z0-9_-]+$/,Ws=d.pipe(d.string(`ID must be a string`),d.minLength(1,`ID must not be empty`),d.maxLength(256,`ID is too long (max 256 characters)`),d.regex(Us,`ID may only contain letters, digits, hyphens, and underscores`));d.picklist([`base`,`base-sepolia`,`arc`,`solana`]),d.picklist([`usdc`]),d.picklist([`evm`,`svm`]);const Gs=/^0x[0-9a-fA-F]{40}$/;d.pipe(d.string(),d.trim(),d.regex(Gs,`Must be a 0x-prefixed hex wallet address`),d.brand(`EvmAddress`)),d.picklist([`always`,`testnet`,`preview`]),d.picklist([`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`]);const Ks=[`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`],qs=[`wallet-wallet-transfer`],Js=[{network:`base`,networkLabel:`Base`,addressFamily:`evm`,blockExplorerUrl:`https://basescan.org`,blockExplorerName:`Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,caip2:`eip155:8453`,caip19:`eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`always`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Ks,provider:{alchemyNetwork:`base`,alchemyDeposit:{transferEmitterAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,transferDecimals:6,webhook:`enabled`},bridgePaymentRail:`base`}},{network:`base-sepolia`,networkLabel:`Base Sepolia`,addressFamily:`evm`,isTestnet:!0,blockExplorerUrl:`https://sepolia.basescan.org`,blockExplorerName:`Sepolia Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,caip2:`eip155:84532`,caip19:`eip155:84532/erc20:0x036CbD53842c5426634e7929541eC2318f3dCF7e`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`testnet`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:qs,provider:{alchemyNetwork:`base-sepolia`,alchemyDeposit:{transferEmitterAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,transferDecimals:6,webhook:`enabled`}}},{network:`arc`,networkLabel:`Arc`,addressFamily:`evm`,blockExplorerUrl:`https://arc-scan.org`,blockExplorerName:`ArcScan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x3600000000000000000000000000000000000000`,caip2:`eip155:5042`,caip19:`eip155:5042/erc20:0x3600000000000000000000000000000000000000`,finality:`block-inclusion`,gasTokenIsTrackedAsset:!0,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:qs,provider:{alchemyNetwork:`arc`,alchemyDeposit:{transferEmitterAddress:`0xfffffffffffffffffffffffffffffffffffffffe`,transferDecimals:18,webhook:`disabled`},sendMode:`self-broadcast`}},{network:`solana`,networkLabel:`Solana`,addressFamily:`svm`,blockExplorerUrl:`https://solscan.io`,blockExplorerName:`Solscan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,caip2:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,caip19:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:Ks,provider:{alchemyNotify:{webhook:`enabled`},bridgePaymentRail:`solana`}}];function Ys(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){for(let t of Object.values(e))Ys(t);Object.freeze(e)}}Ys(Js);const Xs=Js;function Zs(e){return{id:e.network,label:e.networkLabel,addressFamily:e.addressFamily,blockExplorerUrl:e.blockExplorerUrl,blockExplorerName:e.blockExplorerName,...e.isTestnet?{isTestnet:!0}:{}}}function Qs(e){return{id:e.asset,label:e.assetLabel,decimals:e.assetDecimals}}function $s(e){return{network:e.network,asset:e.asset,contractAddress:e.contractAddress}}function ec(e){return{id:`${e.network}-usdc`,label:`${e.networkLabel} USDC`,network:e.network,asset:`usdc`}}function tc(e){let t=[];for(let n of e)t.some(e=>e.id===n.network)||t.push(Zs(n));return t}function nc(e){let t=[],n=new Set;for(let r of e)n.has(r.asset)||(n.add(r.asset),t.push(Qs(r)));return t}function rc(e){return e.asset===`usdc`}const ic=tc(Xs);nc(Xs),Xs.map($s),Xs.filter(rc).map(ec);function ac(e,t){return`${e}:${t}`}new Map(Xs.map(e=>[ac(e.network,e.asset),e])),new Map(ic.map(e=>[e.id,e]));const oc=[`usdc`],sc=`base`,cc=d.pipe(d.string(),d.trim(),d.guard(e=>Gs.test(e),`Must be a 0x-prefixed hex wallet address`));function lc(e){return Z({description:e.description,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),...e.default===void 0?{}:{default:e.default}})}const uc=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],dc=d.pipe(d.string(),d.regex(/^0[23][0-9a-f]{64}$/)),fc=d.pipe(d.string(),d.regex(/^[0-9a-f]{64}$/)),pc=d.object({status:d.picklist(uc),publicKeyHex:d.optional(dc),reason:d.optional(d.string())}),mc=d.object({algorithm:d.literal(`p256`),privateKeyHex:fc,publicKeyHex:dc,registration:pc}),hc=d.object({version:d.literal(`signer-1`),signer:mc}),gc=d.object({version:d.literal(1),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp())}),_c=d.object({version:d.literal(2),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp()),signer:mc}),vc=d.object({version:d.literal(3),signer:mc}),yc=d.variant(`version`,[gc,_c,vc]),bc=d.variant(`version`,[hc,gc,_c,vc]);function xc(e){return d.parse(yc,e)}function Sc(e){return d.parse(bc,e)}function Cc(e){let t=d.safeParse(bc,e);return t.success?t.output:null}function wc(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function Tc(e,t){try{return Sc(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Ec(e){return xc({version:3,signer:e})}function Dc(e){return JSON.stringify(e)}function Oc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function kc(e){return(t,n)=>Ac(e,t,n)}function Ac(e,t,n){return new Promise((r,i)=>{let a=y(e,[...t],{stdio:[`pipe`,`pipe`,`pipe`]}),o=[],s=[],c=!1,l=!1,u=null,d=null,f=null,p=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),r(e))},m=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),i(e))};d=setTimeout(()=>{l=!0,a.kill(`SIGTERM`),f=setTimeout(()=>{a.kill(`SIGKILL`),p({stdout:o.join(``),stderr:s.join(``),status:124})},1e3)},3e4),a.stdout.setEncoding(`utf8`),a.stderr.setEncoding(`utf8`),a.stdout.on(`data`,e=>o.push(e)),a.stderr.on(`data`,e=>s.push(e)),a.on(`error`,t=>{m(Error(`Unable to run ${e}: ${t.message}`))}),a.on(`close`,t=>{if(u!==null&&t===0){m(Error(`Unable to write to ${e} stdin: ${u.message}`));return}p({stdout:o.join(``),stderr:s.join(``),status:l?124:t})}),a.stdin.on(`error`,e=>{u=e});try{a.stdin.end(n)}catch(t){m(t instanceof Error?Error(`Unable to write to ${e} stdin: ${t.message}`):Error(`Unable to write to ${e} stdin`))}})}const jc=`catena-agent`;function Mc(e){if(!Us.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Nc=kc(`/usr/bin/secret-tool`);function Pc(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function Fc(e,t){if(t.status===0)return;let n=Ic(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Ic(e){let t=e.stderr.toLowerCase();return e.status===124?`secret service operation timed out`:t.includes(`cannot autolaunch`)||t.includes(`dbus`)||t.includes(`d-bus`)||t.includes(`org.freedesktop.secrets`)?`secret service session is unavailable`:/\blocked\b/.test(t)?`secret service keyring appears to be locked`:t.includes(`authorization`)||t.includes(`denied`)||t.includes(`not authorized`)?`secret service authorization was denied`:`secret service operation failed; ensure the Secret Service session is available and unlocked`}function Lc(e){return e instanceof Error?e.message.includes(`ENOENT`)?Error(`Linux Secret Service credential operation failed: /usr/bin/secret-tool was not found. Install libsecret-tools and ensure a Secret Service keyring is available.`,{cause:e}):e:Error(String(e))}var Rc=class{runSecretTool;constructor(e={}){if((e.platform??process.platform)!==`linux`)throw Error(`Linux Secret Service credential storage is only supported on Linux`);this.runSecretTool=e.runSecretTool??Nc}async save(e,t){let n=Sc(t),r=Mc(e);if(await this.savePassword(r,Dc(n)),!Oc(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(Mc(e))}async delete(e){await this.deletePassword(Mc(e))}async savePassword(e,t){Fc(`save`,await this.runSecretToolCommand([`store`,`--label`,`${jc} ${e}`,`app`,jc,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,jc,`account`,e]);return Pc(t)?null:(Fc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:Tc(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,jc,`account`,e]);Pc(t)||Fc(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Lc(e)}}};const zc=kc(`/usr/bin/security`),Bc=d.object({version:d.literal(1),encoding:d.literal(`base64-json`),chunks:d.pipe(d.number(),d.integer(),d.minValue(1),d.maxValue(64)),sha256:d.pipe(d.string(),d.regex(/^[a-f0-9]{64}$/))});function Vc(e){return e.status===44}function Hc(e,t){return`${e}:chunk:${t}`}function Uc(e){let t=JSON.parse(e),n=Cc(t);if(n!==null)return{kind:`direct`,payload:n};let r=d.safeParse(Bc,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function Wc(e,t){if(t.status===0)return;let n=Gc(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function Gc(e){let t=e.stderr.toLowerCase();return e.status===124?`keychain operation timed out`:t.includes(`stdin isn't a terminal`)?`parent process has no terminal`:t.includes(`user interaction is not allowed`)?`keychain user interaction is not allowed`:t.includes(`authorization`)||t.includes(`denied`)?`keychain authorization was denied`:t.includes(`locked`)?`keychain appears to be locked`:null}function Kc(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)throw Error(`macOS Keychain credential values cannot contain control characters`)}return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function qc(e,t){return[`add-generic-password`,`-s`,Kc(jc),`-a`,Kc(e),`-w`,Kc(t),`-U`].join(` `)+`
137
- `}var Jc=class{runSecurity;constructor(e={}){if((e.platform??process.platform)!==`darwin`)throw Error(`macOS Keychain credential storage is only supported on macOS`);this.runSecurity=e.runSecurity??zc}async save(e,t){let n=Sc(t),r=Mc(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,Dc(n)),!Oc(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=Mc(e),n=await this.resolveKeychainItem(t);return n===null?null:n.kind===`direct`?n.payload:this.resolveLegacyPayload(t,n.manifest)}async delete(e){let t=Mc(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){Wc(`save`,await this.runSecurity([`-i`],qc(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,jc,`-w`]);return Vc(t)?null:(Wc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Uc(t)}async resolveDirectPassword(e){let t=await this.resolveKeychainItem(e);if(t===null)return null;if(t.kind!==`direct`)throw Error(`macOS Keychain credential direct verification failed`);return t.payload}async resolveLegacyPayload(e,t){let n=[];for(let r=0;r<t.chunks;r++){let t=await this.resolvePassword(Hc(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(m(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return Sc(JSON.parse(Buffer.from(r,`base64`).toString(`utf8`)))}async resolveLegacyChunkCount(e,t){let n=await this.resolvePassword(e);if(n===null)return 0;try{let e=Uc(n);return e.kind===`legacy`?e.manifest.chunks:0}catch{return t}}async deleteChunks(e,t){for(let n=0;n<t;n++)await this.deletePassword(Hc(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,jc]);Vc(t)||Wc(`delete`,t)}};function Yc(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new Jc({platform:t});if(t===`linux`)return new Rc({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const Xc=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function Zc(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||Xc.test(t)}function Qc(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&Zc(t.hostname)}function $c(e,t){if(!Qc(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const el=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,tl=d.object({status:d.optional(d.literal(`linked`),`linked`),api_url:d.pipe(d.string(),d.minLength(1)),agent_id:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Us))}),nl=d.object({status:d.literal(`pending_connection`),api_url:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Us)),created_at:d.pipe(d.string(),d.isoTimestamp())}),rl=d.variant(`status`,[tl,nl]),il=d.union([rl,d.pipe(d.looseObject({api_url:d.optional(d.undefined()),bank_url:d.pipe(d.string(),d.minLength(1))}),d.transform(({bank_url:e,...t})=>({...t,api_url:e})),rl)]);d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),rl),directories:d.optional(d.record(d.string(),d.string()))});const al=d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),d.unknown()),directories:d.optional(d.record(d.string(),d.unknown()))});function ol(){return te(process.env.HOME??ee(),`.catena`)}function sl(){return te(ol(),`profiles.json`)}function cl(e){return el.test(e)}function ll(e){if(!cl(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function ul(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function dl(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${bs(e)}`,{cause:e})}if(typeof n==`object`&&n&&`version`in n){let e=n;if(e.version!==1)throw Error(`profiles.json version ${String(e.version)} is not supported (expected 1)`)}let r=d.parse(al,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!cl(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=d.safeParse(il,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(ll(r.default_profile),!Object.hasOwn(i,r.default_profile)))throw Error(`profiles.json default_profile "${r.default_profile}" is not linked`);let a={};for(let[e,n]of Object.entries(r.directories??{})){if(!M(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!cl(n)){t?.(`profiles: dropping malformed directory binding "${e}"`);continue}a[e]=n}return{version:1,...r.default_profile===void 0?{}:{default_profile:r.default_profile},profiles:i,...Object.keys(a).length===0?{}:{directories:a}}}function fl(e){try{return dl(T(sl(),`utf-8`),e)}catch(e){if(e instanceof Error&&ul(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function pl(){w(ol(),{recursive:!0,mode:448}),x(ol(),448)}function ml(e){pl();let t=sl(),n=`${t}.${g(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
- `,{encoding:`utf-8`,mode:384}),D(n,t)}function hl(e,t){ll(e);let n=d.parse(rl,t);$c(n.api_url,`profile "${e}" api_url`);let r=fl();ml({...r,profiles:{...r.profiles,[e]:n}})}function gl(e){return e.status===`linked`}function _l(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function vl(e,t){let n=Object.entries(fl().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>gl(n)&&n.agent_id===e&&_l(n.api_url,t));return n===void 0?null:n[0]}function yl(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function bl(e){ll(e);let t=fl(),{[e]:n,...r}=t.profiles;ml({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...yl(t.directories,t=>t!==e)})}function xl(e){try{return E(ne(e))}catch{return ne(e)}}function Sl(e){return fl().directories?.[xl(e)]??null}function Cl(e,t){ll(t);let n=fl();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=xl(e);return ml({...n,directories:{...n.directories,[r]:t}}),r}function wl(e){let t=fl(),n=xl(e);if(t.directories===void 0||!Object.hasOwn(t.directories,n))return{directory:n,removed:!1};let{[n]:r,...i}=t.directories,{directories:a,...o}=t;return ml({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function Tl(e){return ll(e),fl().profiles[e]??null}function El(){return`client_${g(16).toString(`hex`)}`}function Dl(e,t){let n=Tl(e);return t.agent_id===void 0?Ol(e,t.api_url,n):kl(e,t.api_url,t.agent_id,n)}function Ol(e,t,n){if(n?.status===`linked`)throw Error(`Profile "${e}" is already linked. Choose a different profile name to start agent connection.`);let r=(n?.status===`pending_connection`&&_l(n.api_url,t)?n.client_instance_id:null)??El();return hl(e,{status:`pending_connection`,api_url:t,client_instance_id:r,created_at:n?.status===`pending_connection`?n.created_at:new Date().toISOString()}),r}function kl(e,t,n,r){if(r?.status===`linked`){if(r.agent_id!==n)throw Error(`Profile "${e}" is already linked to a different agent (${r.agent_id}). Link ${n} under a different --profile, or run 'catena unlink --profile ${e}' first to repoint it (add --force if that agent's credential is missing or revoked).`);if(!_l(r.api_url,t))throw Error(`Profile "${e}" is already linked to this agent on a different Catena API (${r.api_url}). Link under a different --profile, or run 'catena unlink --profile ${e}' first (add --force if that credential is missing or revoked).`);return r.client_instance_id}let i=(r?.status===`pending_connection`&&_l(r.api_url,t)?r.client_instance_id:null)??El();return hl(e,{status:`linked`,api_url:t,agent_id:n,client_instance_id:i}),i}function Al(e){ll(e);let t=fl();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);ml({...t,default_profile:e})}function jl(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return cl(t)?t:`agent`}function Ml(e,t){if(!t(e))return e;for(let n=2;;n++){let r=`${e.slice(0,64-String(n).length-1)}-${n}`;if(!t(r))return r}}function Nl(e){ll(e.reservationName),ll(e.profileName);let t=d.parse(rl,e.profile);$c(t.api_url,`profile "${e.profileName}" api_url`);let n=fl(),{[e.reservationName]:r,...i}=n.profiles;if(!Object.hasOwn(n.profiles,e.reservationName)||r.client_instance_id!==t.client_instance_id)throw Error(`Link reservation "${e.reservationName}" changed during setup (a concurrent link from this directory?). Re-run 'catena link'.`);if(e.profileName!==e.reservationName&&Object.hasOwn(i,e.profileName))throw Error(`Profile "${e.profileName}" already exists; cannot finalize link under that name.`);let a=Object.fromEntries(Object.entries(n.directories??{}).map(([t,n])=>[t,n===e.reservationName?e.profileName:n]));ml({version:1,...n.default_profile===void 0?{}:{default_profile:n.default_profile===e.reservationName?e.profileName:n.default_profile},profiles:{...i,[e.profileName]:t},...Object.keys(a).length===0?{}:{directories:a}})}function Pl(e){return e??Yc()}async function Fl(e,t){let n;try{n=Tl(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:bs(t)}}if(n===null)return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:`Profile "${e.profileName}" is not linked. Run 'catena link --profile ${e.profileName}' to authenticate.`};try{$c(n.api_url,`profile "${e.profileName}" api_url`)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:bs(t)}}if(n.status===`pending_connection`)return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" is waiting for agent connection approval. Run 'catena link --profile ${e.profileName}' to finish setup.`};let r;try{r=await Pl(t).resolve(n.client_instance_id)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}: ${bs(t)}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}}return r===null||r.version===`signer-1`?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:r.version===1?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential for ${n.agent_id} has no signing key. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:{ok:!0,profileName:e.profileName,apiUrl:n.api_url,agentId:n.agent_id,clientInstanceId:n.client_instance_id,signer:r.signer}}const Il=`https://api.catena.com`,Ll=`CATENA_SECRET_KEY`;function Rl(e,t){let n=e[t]?.trim();return n===void 0||n.length===0?void 0:n}function zl(e=process.env){return Rl(e,Ll)!==void 0}function Bl(e=process.env){let t=Rl(e,Ll);if(t===void 0)return null;let n=Rl(e,`CATENA_API_URL`)??`https://api.catena.com`;return $c(n,`CATENA_API_URL`),{apiUrl:n,privateKeyHex:t}}const Vl=`CATENA_PROFILE`;function Hl(e,t,n,r){if(e.directories===void 0)return null;let i;try{i=E(t)}catch{return null}let a=Object.entries(e.directories).map(([e,t])=>[e.replace(/\/+$/,``)||`/`,t]).filter(([e])=>i===e||i.startsWith(e===`/`?`/`:`${e}/`)).toSorted(([e],[t])=>t.length-e.length),o=null;for(let[t,n]of a){if(Object.hasOwn(e.profiles,n))return n;o??=`${t} -> "${n}"`}if(o===null)return null;if(n===`error`)throw Error(`This directory is bound to a profile that no longer exists (${o}). Run 'catena profiles unbind' here, bind it with 'catena profiles bind <name>', or run 'catena link' to re-establish it.`);return r?.(`profiles: ignoring stale directory binding ${o}`),null}function Ul(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return ll(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!cl(e.env))throw Error(`${Vl} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=Hl(t,e.cwd,n,e.log);if(r!==null)return{name:r,source:`directory`}}return t.default_profile===void 0?null:{name:t.default_profile,source:`default`}}function Wl(e){return Ul(e,fl(e.log),`ignore`)}function Gl(e){let t=fl(e.log),n=Ul(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>gl(e)).map(([e])=>e);if(i.length===1){let[e]=i;return{name:e,source:`single`}}if(i.length===0){if(r.length===1){let[e]=r;return{name:e,source:`single`}}return r.length>1&&e.log?.(`profiles: ignoring ${r.length} pending profiles (${r.toSorted().join(`, `)}); none is linked`),{name:`default`,source:`fallback`}}throw Error(`Multiple profiles exist and none is selected (${i.toSorted().join(`, `)}). Pass --profile <name>, set ${Vl}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function Kl(){try{return Object.entries(fl().profiles).filter(([,e])=>gl(e)).map(([e])=>e).toSorted()}catch{return[]}}function ql(e=process.env){let t=e[Vl]?.trim();if(t!==void 0&&t.length>0)return`profiles: signing with ${Ll}; ${Vl}=${t} is ignored. Pass --profile ${t} to use that profile.`;let n=Kl();if(n.length===0)return null;let r=n.length===1?`profile`:`profiles`;return`profiles: signing with ${Ll}; ${n.length} linked ${r} ignored (${n.join(`, `)}). Pass --profile <name> to use one.`}const Jl={name:`catena-cli`,version:oe},Yl=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function Xl(e,t){if(!Yl.test(e))throw Error(`${t} must be a valid HTTP token`)}function Zl(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Ql(e){Xl(e.name,`appInfo.name`),e.version!==void 0&&Xl(e.version,`appInfo.version`),e.url!==void 0&&Zl(e.url,`appInfo.url`);let t=e.version===void 0?e.name:`${e.name}/${e.version}`;return{"User-Agent":e.url===void 0?t:`${t} (${e.url})`}}function $l(e){return ys({baseUrl:e.apiUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:Jl})}function eu(){return Yc()}function tu(e){try{return ys({baseUrl:e.apiUrl,privateKeyHex:e.privateKeyHex,appInfo:Jl})}catch(e){return X(`${Ll} is not usable: ${bs(e)}`)}}async function nu(e){if(e===void 0){let e;try{e=Bl()}catch(e){return X(e)}if(e!==null){let t=ql();return t!==null&&console.error(t),tu(e)}}let t;try{t=Gl({flag:e,env:process.env[Vl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await Fl({profileName:t,fallbackApiUrl:Il},void 0);return n.ok||X(n.message),$l(n)}const ru=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),iu=new Set([`signature_auth_disabled`,`missing_auth`]);function au(e,t,n=process.env){if(!(e instanceof ds)||e.code===void 0)return e;let r=t===void 0?`catena link`:`catena link --profile ${t}`;return ru.has(e.code)?t===void 0&&zl(n)?Error(`Catena rejected the ${Ll} signing key (${e.code}). Create a secret key in the Catena console under the agent's Secret keys tab, then update ${Ll}.`):Error(`Catena rejected this machine's signing key (${e.code}). Run '${r}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${Jl.version}) is no longer supported by the Catena API. Run 'npm i -g @catena/cli' and retry.`):iu.has(e.code)?Error(`This Catena API does not support key-based authentication (${e.code}). Upgrade it, or use an older CLI release that authenticates with session tokens.`):e.code===`invalid_signature`&&e.message.includes(`created_out_of_window`)?Error(`Catena rejected this request's timestamp (created_out_of_window). Check this machine's system clock and retry.`):e}function ou(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function su(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function cu(e,t){try{return await t(await nu(e))}catch(t){return X(au(t,e))}}function lu(e,t){return async(n,r)=>{let i=await cu(e,n);return ou(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return lu(su(e),{compact:e.json===!0})}const uu=d.pipe(d.string(),d.regex(/^\d+$/,`must be a non-negative integer`),d.transform(Number),d.maxValue(2**53-1,`must be at most ${2**53-1}`)),du=d.pipe(uu,d.maxValue(200,`must be at most 200`)),fu={profile:Vs,json:Hs},pu=Q(fu),mu=Q({account:Os({description:`Account id`,required:!0,schema:Ws}),...fu}),hu=Q({account:Os({description:`Account id`,required:!0,schema:Ws}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:du}),offset:Z({description:`Number of transactions to skip for pagination`,schema:uu}),...fu}),gu=Q({account:Os({description:`Account id`,required:!0,schema:Ws}),network:lc({description:`Deposit network; defaults to ${sc}. Availability depends on the connected environment.`,default:sc}),asset:Z({description:`Deposit asset; known value: ${oc.join(`|`)}`,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),default:`usdc`}),...fu}),_u=c({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:pu.args,async run({args:e}){await $(pu.parse(e))(e=>e.listAccounts())}}),vu=c({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:mu.args,async run({args:e}){let t=mu.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),yu=c({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:hu.args,async run({args:e}){let t=hu.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),bu=c({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:gu.args,async run({args:e}){let t=gu.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),xu=c({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:_u,balance:vu,transactions:yu,"deposit-address":bu}}),Su=d.pipe(d.string(`Idempotency key must be a string`),d.minLength(1,`Idempotency key must not be empty`),d.maxLength(255,`Idempotency key is too long (max 255 characters)`)),Cu=d.pipe(d.string(),d.minLength(1,`must not be empty`)),wu=d.pipe(d.string(),d.trim(),d.email(`must be a valid email address`)),Tu={profile:Vs,json:Hs},Eu=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:cc}),network:lc({description:`Only counterparties with a wallet rail on this network (e.g. base)`}),...Tu}),Du=Z({description:`Counterparty name`,required:!0,schema:Cu}),Ou=Z({description:`Optional contact email`,schema:wu}),ku=Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Su}),Au=Q({name:Du,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:wu}),"idempotency-key":ku,...Tu}),ju=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:Cu}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:wu}),"idempotency-key":ku,...Tu}),Mu=Q({name:Du,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:Cu}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:Cu}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:Cu}),"account-type":js({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:Cu}),"address-city":Z({description:`City`,required:!0,schema:Cu}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:Cu}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:Cu}),"address-country":Z({description:`Default USA`}),email:Ou,"idempotency-key":ku,...Tu}),Nu=Q({name:Du,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:Cu}),network:lc({description:`Wallet network; defaults to ${sc}. Availability depends on the connected environment.`,default:sc}),email:Ou,"idempotency-key":ku,...Tu}),Pu=Q({counterparty:Os({description:`Counterparty id`,required:!0,schema:Ws}),bank:As({description:`Request bank account details`,default:!1}),wallet:As({description:`Request wallet details`,default:!1}),"idempotency-key":ku,...Tu}),Fu=c({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:Eu.args,async run({args:e}){let t=Eu.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function Iu(e){return e&&e.length>0?e:void 0}function Lu(e){let t=Iu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`bank`,bankName:e[`bank-name`],routingNumber:e[`routing-number`],accountNumber:e[`account-number`],addressStreet:e[`address-street`],addressCity:e[`address-city`],addressState:e[`address-state`],addressPostalCode:e[`address-postal-code`],...e[`account-type`]?{accountType:e[`account-type`]}:{},...e[`address-country`]?{addressCountry:e[`address-country`]}:{}}}}function Ru(e){let t=Iu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function zu(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Bu=c({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:Au.args,async run({args:e}){let t=Au.parse(e);await $(t)(e=>e.submitIntent({action:zu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Vu=c({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:Mu.args,async run({args:e}){let t=Mu.parse(e),n=Lu(t);await $(t)(e=>e.submitIntent({action:n,...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Hu=c({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:Nu.args,async run({args:e}){let t=Nu.parse(e);await $(t)(e=>e.submitIntent({action:Ru(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Uu=c({meta:{name:`create`,description:`Request counterparty creation through the policy engine. Without a subcommand, --name and --email create a record without payment details and send no email.`},args:ju.args,default:`email`,subCommands:{email:Bu,bank:Vu,wallet:Hu}}),Wu=c({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:Pu.args,async run({args:e}){let t=Pu.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),Gu=c({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Fu,create:Uu,"request-details":Wu}}),Ku=4e3;async function qu(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function Ju(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),qu()):e}const Yu=Q({message:Os({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Vs,json:Hs}),Xu=c({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:Yu.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=Yu.parse(e),n=(await Ju(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>Ku&&X(`<message>: must be at most ${Ku} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function Zu(e){return`# Catena CLI Agent Guide
134
+ `)}};U.CertificateTag=`CERTIFICATE`,U.CrlTag=`CRL`,U.CertificateRequestTag=`CERTIFICATE REQUEST`,U.PublicKeyTag=`PUBLIC KEY`,U.PrivateKeyTag=`PRIVATE KEY`;var W=class e extends ye{static isAsnEncoded(e){return i.BufferSourceConverter.isBufferSource(e)||typeof e==`string`}static toArrayBuffer(e){if(typeof e==`string`){if(U.isPem(e))return U.decode(e)[0];if(i.Convert.isHex(e))return i.Convert.FromHex(e);if(i.Convert.isBase64(e))return i.Convert.FromBase64(e);if(i.Convert.isBase64Url(e))return i.Convert.FromBase64Url(e);throw TypeError(`Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url`)}{let t=i.Convert.ToBinary(e);return U.isPem(t)?U.decode(t)[0]:i.Convert.isHex(t)?i.Convert.FromHex(t):i.Convert.isBase64(t)?i.Convert.FromBase64(t):i.Convert.isBase64Url(t)?i.Convert.FromBase64Url(t):i.BufferSourceConverter.toArrayBuffer(e)}}constructor(...t){e.isAsnEncoded(t[0])?super(e.toArrayBuffer(t[0]),t[1]):super(t[0])}toString(e=`pem`){switch(e){case`pem`:return U.encode(this.rawData,this.tag);default:return super.toString(e)}}},Ve=class e extends W{static async create(t,n=z.get()){if(t instanceof e)return t;if(Se.isCryptoKey(t)){if(t.type!==`public`)throw TypeError(`Public key is required`);let r=await n.subtle.exportKey(`spki`,t);return new e(r)}if(t.publicKey)return t.publicKey;if(i.BufferSourceConverter.isBufferSource(t))return new e(t);throw TypeError(`Unsupported PublicKeyType`)}constructor(e){W.isAsnEncoded(e)?super(e,r.SubjectPublicKeyInfo):super(e),this.tag=U.PublicKeyTag}async export(...e){let t,i=[`verify`],a={hash:`SHA-256`,...this.algorithm};e.length>1?(a=e[0]||a,i=e[1]||i,t=e[2]||z.get()):t=e[0]||z.get();let o=this.rawData,c=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return c.algorithm.algorithm===s.id_RSASSA_PSS&&(o=He(c,o)),t.subtle.importKey(`spki`,o,a,!0,i)}onInit(e){let t=l.container.resolve(b),r=this.algorithm=t.toWebAlgorithm(e.algorithm);switch(e.algorithm.algorithm){case s.id_rsaEncryption:{let t=n.AsnConvert.parse(e.subjectPublicKey,s.RSAPublicKey),a=i.BufferSourceConverter.toUint8Array(t.modulus);r.publicExponent=i.BufferSourceConverter.toUint8Array(t.publicExponent),r.modulusLength=(a[0]?a:a.slice(1)).byteLength<<3;break}}}async getThumbprint(...e){let t,n=`SHA-1`;return e.length>=1&&!e[0]?.subtle?(n=e[0]||n,t=e[1]||z.get()):t=e[0]||z.get(),await t.subtle.digest(n,this.rawData)}async getKeyIdentifier(...e){let t,i=`SHA-1`;e.length===1?typeof e[0]==`string`?(i=e[0],t=z.get()):t=e[0]:e.length===2?(i=e[0],t=e[1]):t=z.get();let a=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);return await t.subtle.digest(i,a.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.SubjectPublicKeyInfo);switch(e.Algorithm=ve.serializeAlgorithm(t.algorithm),t.algorithm.algorithm){case o.id_ecPublicKey:e[`EC Point`]=t.subjectPublicKey;break;case s.id_rsaEncryption:default:e[`Raw Data`]=t.subjectPublicKey}return e}};function He(e,t){return e.algorithm=new r.AlgorithmIdentifier({algorithm:s.id_rsaEncryption,parameters:null}),t=n.AsnConvert.serialize(e),t}var Ue=class e extends be{static async create(t,n=!1,r=z.get()){if(`name`in t&&`serialNumber`in t)return new e(t,n);let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(typeof e[0]==`string`){let t=new p.AuthorityKeyIdentifier({keyIdentifier:new p.KeyIdentifier(i.Convert.FromHex(e[0]))});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=t.name instanceof ze?n.AsnConvert.parse(t.name.rawData,p.GeneralNames):t.name,a=new p.AuthorityKeyIdentifier({authorityCertIssuer:r,authorityCertSerialNumber:i.Convert.FromHex(t.serialNumber)});super(p.id_ce_authorityKeyIdentifier,e[1],n.AsnConvert.serialize(a))}}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.AuthorityKeyIdentifier);t.keyIdentifier&&(this.keyId=i.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?i.Convert.ToHex(t.authorityCertSerialNumber):``})}toTextObject(){let e=this.toTextObjectWithoutValue(),t=n.AsnConvert.parse(this.value,p.AuthorityKeyIdentifier);return t.authorityCertIssuer&&(e[`Authority Issuer`]=new ze(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e[`Authority Serial Number`]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[``]=t.keyIdentifier),e}};Ue.NAME=`Authority Key Identifier`;var We=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.BasicConstraints);this.ca=t.cA,this.pathLength=t.pathLenConstraint}else{let t=new r.BasicConstraints({cA:e[0],pathLenConstraint:e[1]});super(r.id_ce_basicConstraints,e[2],n.AsnConvert.serialize(t)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),this.pathLength!==void 0&&(e[`Path Length`]=this.pathLength),e}};We.NAME=`Basic Constraints`,e.ExtendedKeyUsage=void 0,(function(e){e.serverAuth=`1.3.6.1.5.5.7.3.1`,e.clientAuth=`1.3.6.1.5.5.7.3.2`,e.codeSigning=`1.3.6.1.5.5.7.3.3`,e.emailProtection=`1.3.6.1.5.5.7.3.4`,e.timeStamping=`1.3.6.1.5.5.7.3.8`,e.ocspSigning=`1.3.6.1.5.5.7.3.9`})(e.ExtendedKeyUsage||={});var Ge=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.ExtendedKeyUsage);this.usages=t.map(e=>e)}else{let t=new p.ExtendedKeyUsage(e[0]);super(p.id_ce_extKeyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=this.usages.map(e=>R.toString(e)).join(`, `),e}};Ge.NAME=`Extended Key Usages`,e.KeyUsageFlags=void 0,(function(e){e[e.digitalSignature=1]=`digitalSignature`,e[e.nonRepudiation=2]=`nonRepudiation`,e[e.keyEncipherment=4]=`keyEncipherment`,e[e.dataEncipherment=8]=`dataEncipherment`,e[e.keyAgreement=16]=`keyAgreement`,e[e.keyCertSign=32]=`keyCertSign`,e[e.cRLSign=64]=`cRLSign`,e[e.encipherOnly=128]=`encipherOnly`,e[e.decipherOnly=256]=`decipherOnly`})(e.KeyUsageFlags||={});var Ke=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,r.KeyUsage);this.usages=t.toNumber()}else{let t=new r.KeyUsage(e[0]);super(r.id_ce_keyUsage,e[1],n.AsnConvert.serialize(t)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,r.KeyUsage).toJSON().join(`, `),e}};Ke.NAME=`Key Usages`;var qe=class e extends be{static async create(t,n=!1,r=z.get()){let a=await(await Ve.create(t,r)).getKeyIdentifier(r);return new e(i.Convert.ToHex(a),n)}constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier);this.keyId=i.Convert.ToHex(t)}else{let t=typeof e[0]==`string`?i.Convert.FromHex(e[0]):e[0],r=new p.SubjectKeyIdentifier(t);super(p.id_ce_subjectKeyIdentifier,e[1],n.AsnConvert.serialize(r)),this.keyId=i.Convert.ToHex(t)}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[``]=n.AsnConvert.parse(this.value,p.SubjectKeyIdentifier),e}};qe.NAME=`Subject Key Identifier`;var Je=class extends be{constructor(...e){i.BufferSourceConverter.isBufferSource(e[0])?super(e[0]):super(p.id_ce_subjectAltName,e[1],new ze(e[0]||[]).rawData)}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.SubjectAlternativeName);this.names=new ze(t)}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(let n in t)e[n]=t[n];return e}};Je.NAME=`Subject Alternative Name`;var G=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new be(e),n=this.items.get(t.type);return n?new n(e):t}};G.items=new Map;var Ye=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0])){super(e[0]);let t=n.AsnConvert.parse(this.value,p.CertificatePolicies);this.policies=t.map(e=>e.policyIdentifier)}else{let t=e[0],r=e[1]??!1,i=new p.CertificatePolicies(t.map(e=>new p.PolicyInformation({policyIdentifier:e})));super(p.id_ce_certificatePolicies,r,n.AsnConvert.serialize(i)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new L(``,{},R.toString(e))),e}};Ye.NAME=`Certificate Policies`,G.register(p.id_ce_certificatePolicies,Ye);var Xe=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(Array.isArray(e[0])&&typeof e[0][0]==`string`){let t=e[0].map(e=>new p.DistributionPoint({distributionPoint:new p.DistributionPointName({fullName:[new p.GeneralName({uniformResourceIdentifier:e})]})})),r=new p.CRLDistributionPoints(t);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(r))}else{let t=new p.CRLDistributionPoints(e[0]);super(p.id_ce_cRLDistributionPoints,e[1],n.AsnConvert.serialize(t))}this.distributionPoints??=[]}onInit(e){super.onInit(e);let t=n.AsnConvert.parse(e.extnValue,p.CRLDistributionPoints);this.distributionPoints=t}toTextObject(){let e=this.toTextObjectWithoutValue();return e[`Distribution Point`]=this.distributionPoints.map(e=>{let t={};return e.distributionPoint&&(t[``]=e.distributionPoint.fullName?.map(e=>new Re(e).toString()).join(`, `)),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t[`CRL Issuer`]=e.cRLIssuer.map(e=>e.toString()).join(`, `)),t}),e}};Xe.NAME=`CRL Distribution Points`;var Ze=class extends be{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else if(e[0]instanceof p.AuthorityInfoAccessSyntax){let t=new p.AuthorityInfoAccessSyntax(e[0]);super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(t))}else{let t=e[0],r=new p.AuthorityInfoAccessSyntax;$e(r,t,p.id_ad_ocsp,`ocsp`),$e(r,t,p.id_ad_caIssuers,`caIssuers`),$e(r,t,p.id_ad_timeStamping,`timeStamping`),$e(r,t,p.id_ad_caRepository,`caRepository`),super(p.id_pe_authorityInfoAccess,e[1],n.AsnConvert.serialize(r))}this.ocsp??=[],this.caIssuers??=[],this.timeStamping??=[],this.caRepository??=[]}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],n.AsnConvert.parse(e.extnValue,p.AuthorityInfoAccessSyntax).forEach(e=>{switch(e.accessMethod){case p.id_ad_ocsp:this.ocsp.push(new Re(e.accessLocation));break;case p.id_ad_caIssuers:this.caIssuers.push(new Re(e.accessLocation));break;case p.id_ad_timeStamping:this.timeStamping.push(new Re(e.accessLocation));break;case p.id_ad_caRepository:this.caRepository.push(new Re(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&Qe(e,`OCSP`,this.ocsp),this.caIssuers.length&&Qe(e,`CA Issuers`,this.caIssuers),this.timeStamping.length&&Qe(e,`Time Stamping`,this.timeStamping),this.caRepository.length&&Qe(e,`CA Repository`,this.caRepository),e}};Ze.NAME=`Authority Info Access`;function Qe(e,t,n){if(n.length===1)e[t]=n[0].toTextObject();else{let r=new L(``);n.forEach((e,t)=>{let n=e.toTextObject(),i=`${n[L.NAME]} ${t+1}`,a=r[i];Array.isArray(a)||(a=[],r[i]=a),a.push(n)}),e[t]=r}}function $e(e,t,r,i){let a=t[i];a&&(Array.isArray(a)?a:[a]).forEach(t=>{typeof t==`string`&&(t=new Re(`url`,t)),e.push(new p.AccessDescription({accessMethod:r,accessLocation:n.AsnConvert.parse(t.rawData,p.GeneralName)}))})}var et=class e extends ye{constructor(...e){let t;if(i.BufferSourceConverter.isBufferSource(e[0]))t=i.BufferSourceConverter.toArrayBuffer(e[0]);else{let a=e[0],o=Array.isArray(e[1])?e[1].map(e=>i.BufferSourceConverter.toArrayBuffer(e)):[];t=n.AsnConvert.serialize(new r.Attribute({type:a,values:o}))}super(t,r.Attribute)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new L(``,{"":e})),e}toTextObjectWithoutValue(){let t=this.toTextObjectEmpty();return t[L.NAME]===e.NAME&&(t[L.NAME]=R.toString(this.type)),t}};et.NAME=`Attribute`;var tt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=new _.ChallengePassword({printableString:e[0]});super(_.id_pkcs9_at_challengePassword,[n.AsnConvert.serialize(t)])}this.password??=``}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],_.ChallengePassword);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[L.VALUE]=this.password,e}};tt.NAME=`Challenge Password`;var nt=class extends et{constructor(...e){if(i.BufferSourceConverter.isBufferSource(e[0]))super(e[0]);else{let t=e[0],r=new p.Extensions;for(let e of t)r.push(n.AsnConvert.parse(e.rawData,p.Extension));super(_.id_pkcs9_at_extensionRequest,[n.AsnConvert.serialize(r)])}this.items??=[]}onInit(e){if(super.onInit(e),this.values[0]){let e=n.AsnConvert.parse(this.values[0],p.Extensions);this.items=e.map(e=>G.create(n.AsnConvert.serialize(e)))}}toTextObject(){let e=this.toTextObjectWithoutValue(),t=this.items.map(e=>e.toTextObject());for(let n of t)e[n[L.NAME]]=n;return e}};nt.NAME=`Extensions`;var rt=class{static register(e,t){this.items.set(e,t)}static create(e){let t=new et(e),n=this.items.get(t.type);return n?new n(e):t}};rt.items=new Map;let it=`crypto.signatureFormatter`;var at=class{toAsnSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return i.BufferSourceConverter.toArrayBuffer(t)}},ot;e.RsaAlgorithm=ot=class{static createPssParams(e,t){let i=ot.getHashAlgorithm(e);return i?new g.RsaSaPssParams({hashAlgorithm:i,maskGenAlgorithm:new r.AlgorithmIdentifier({algorithm:g.id_mgf1,parameters:n.AsnConvert.serialize(i)}),saltLength:t}):null}static getHashAlgorithm(e){let t=l.container.resolve(b);return typeof e==`string`?t.toAsnAlgorithm({name:e}):typeof e==`object`&&e&&`name`in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`rsassa-pkcs1-v1_5`:if(`hash`in e){let t;if(typeof e.hash==`string`)t=e.hash;else if(e.hash&&typeof e.hash==`object`&&`name`in e.hash&&typeof e.hash.name==`string`)t=e.hash.name.toUpperCase();else throw Error(`Cannot get hash algorithm name`);switch(t.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:g.id_sha1WithRSAEncryption,parameters:null});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:g.id_sha256WithRSAEncryption,parameters:null});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:g.id_sha384WithRSAEncryption,parameters:null});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:g.id_sha512WithRSAEncryption,parameters:null})}}else return new r.AlgorithmIdentifier({algorithm:g.id_rsaEncryption,parameters:null});break;case`rsa-pss`:if(`hash`in e){if(!(`saltLength`in e&&typeof e.saltLength==`number`))throw Error(`Cannot get 'saltLength' from 'alg' argument`);let t=ot.createPssParams(e.hash,e.saltLength);if(!t)throw Error(`Cannot create PSS parameters`);return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:n.AsnConvert.serialize(t)})}return new r.AlgorithmIdentifier({algorithm:g.id_RSASSA_PSS,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case g.id_rsaEncryption:return{name:`RSASSA-PKCS1-v1_5`};case g.id_sha1WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-1`}};case g.id_sha256WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case g.id_sha384WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-384`}};case g.id_sha512WithRSAEncryption:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-512`}};case g.id_RSASSA_PSS:if(e.parameters){let t=n.AsnConvert.parse(e.parameters,g.RsaSaPssParams);return{name:`RSA-PSS`,hash:l.container.resolve(b).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:`RSA-PSS`}}return null}},e.RsaAlgorithm=ot=c.__decorate([l.injectable()],e.RsaAlgorithm),l.container.registerSingleton(v,e.RsaAlgorithm),e.ShaAlgorithm=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case`sha-1`:return new r.AlgorithmIdentifier({algorithm:s.id_sha1});case`sha-256`:return new r.AlgorithmIdentifier({algorithm:s.id_sha256});case`sha-384`:return new r.AlgorithmIdentifier({algorithm:s.id_sha384});case`sha-512`:return new r.AlgorithmIdentifier({algorithm:s.id_sha512})}return null}toWebAlgorithm(e){switch(e.algorithm){case s.id_sha1:return{name:`SHA-1`};case s.id_sha256:return{name:`SHA-256`};case s.id_sha384:return{name:`SHA-384`};case s.id_sha512:return{name:`SHA-512`}}return null}},e.ShaAlgorithm=c.__decorate([l.injectable()],e.ShaAlgorithm),l.container.registerSingleton(v,e.ShaAlgorithm);var ct=class e{addPadding(e,t){let n=i.BufferSourceConverter.toUint8Array(t),r=new Uint8Array(e);return r.set(n,e-n.length),r}removePadding(e,t=!1){let n=i.BufferSourceConverter.toUint8Array(e);for(let e=0;e<n.length;e++)if(n[e]){n=n.slice(e);break}if(t&&n[0]>127){let e=new Uint8Array(n.length+1);return e.set(n,1),e.buffer}return n.buffer}toAsnSignature(t,r){if(t.name===`ECDSA`){let a=t.namedCurve,s=e.namedCurveSize.get(a)||e.defaultNamedCurveSize,c=new o.ECDSASigValue,l=i.BufferSourceConverter.toUint8Array(r);return c.r=this.removePadding(l.slice(0,s),!0),c.s=this.removePadding(l.slice(s,s+s),!0),n.AsnConvert.serialize(c)}return null}toWebSignature(t,r){if(t.name===`ECDSA`){let a=n.AsnConvert.parse(r,o.ECDSASigValue),s=t.namedCurve,c=e.namedCurveSize.get(s)||e.defaultNamedCurveSize,l=this.addPadding(c,this.removePadding(a.r)),u=this.addPadding(c,this.removePadding(a.s));return i.combine(l,u)}return null}};ct.namedCurveSize=new Map,ct.defaultNamedCurveSize=32;let lt=`1.3.101.110`,ut=`1.3.101.111`,dt=`1.3.101.112`,ft=`1.3.101.113`;e.EdAlgorithm=class{toAsnAlgorithm(e){let t=null;switch(e.name.toLowerCase()){case`ed25519`:t=dt;break;case`x25519`:t=lt;break;case`eddsa`:switch(e.namedCurve.toLowerCase()){case`ed25519`:t=dt;break;case`ed448`:t=ft}break;case`ecdh-es`:switch(e.namedCurve.toLowerCase()){case`x25519`:t=lt;break;case`x448`:t=ut}}return t?new r.AlgorithmIdentifier({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case dt:return{name:`Ed25519`};case ft:return{name:`EdDSA`,namedCurve:`Ed448`};case lt:return{name:`X25519`};case ut:return{name:`ECDH-ES`,namedCurve:`X448`}}return null}},e.EdAlgorithm=c.__decorate([l.injectable()],e.EdAlgorithm),l.container.registerSingleton(v,e.EdAlgorithm);var pt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,d.CertificationRequest):super(e),this.tag=U.CertificateRequestTag}onInit(e){this.tbs=n.AsnConvert.serialize(e.certificationRequestInfo),this.publicKey=new Ve(e.certificationRequestInfo.subjectPKInfo);let t=l.container.resolve(b);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map(e=>rt.create(n.AsnConvert.serialize(e)));let r=this.getAttribute(u.id_pkcs9_at_extensionRequest);this.extensions=[],r instanceof nt&&(this.extensions=r.items),this.subjectName=new V(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(let t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter(t=>t.type===e)}getExtension(e){for(let t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter(t=>t.type===e)}async verify(e=z.get()){let t={...this.publicKey.algorithm,...this.signatureAlgorithm},n=await this.publicKey.export(t,[`verify`],e),r=l.container.resolveAll(it).reverse(),i=null;for(let e of r)if(i=e.toWebSignature(t,this.signature),i)break;if(!i)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return await e.subtle.verify(this.signatureAlgorithm,n,i,this.tbs)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,d.CertificationRequest),i=t.certificationRequestInfo,a=new L(``,{Version:`${r.Version[i.version]} (${i.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){let e=new L(``);for(let t of this.attributes){let n=t.toTextObject();e[n[L.NAME]]=n}a.Attributes=e}return e.Data=a,e.Signature=new L(``,{Algorithm:ve.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}};pt.NAME=`PKCS#10 Certificate Request`;var mt=class{static async create(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);let i=await t.subtle.exportKey(`spki`,e.keys.publicKey),a=new d.CertificationRequest({certificationRequestInfo:new d.CertificationRequestInfo({subjectPKInfo:n.AsnConvert.parse(i,r.SubjectPublicKeyInfo)})});if(e.name){let t=e.name instanceof V?e.name:new V(e.name);a.certificationRequestInfo.subject=n.AsnConvert.parse(t.toArrayBuffer(),r.Name)}if(e.attributes)for(let t of e.attributes)a.certificationRequestInfo.attributes.push(n.AsnConvert.parse(t.rawData,r.Attribute));if(e.extensions&&e.extensions.length){let t=new r.Attribute({type:u.id_pkcs9_at_extensionRequest}),i=new r.Extensions;for(let t of e.extensions)i.push(n.AsnConvert.parse(t.rawData,r.Extension));t.values.push(n.AsnConvert.serialize(i)),a.certificationRequestInfo.attributes.push(t)}let o={...e.signingAlgorithm,...e.keys.privateKey.algorithm};a.signatureAlgorithm=l.container.resolve(b).toAsnAlgorithm(o);let s=n.AsnConvert.serialize(a.certificationRequestInfo),c=await t.subtle.sign(o,e.keys.privateKey,s),f=l.container.resolveAll(it).reverse(),p=null;for(let e of f)if(p=e.toAsnSignature(o,c),p)break;if(!p)throw Error(`Cannot convert WebCrypto signature value to ASN.1 format`);return a.signature=p,new pt(n.AsnConvert.serialize(a))}},ht=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.Certificate):super(e),this.tag=U.CertificateTag}onInit(e){let t=e.tbsCertificate;this.tbs=n.AsnConvert.serialize(t),this.serialNumber=i.Convert.ToHex(t.serialNumber),this.subjectName=new V(t.subject),this.subject=new V(t.subject).toString(),this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;let a=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!a)throw Error(`Cannot get 'notBefore' value`);this.notBefore=a;let o=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!o)throw Error(`Cannot get 'notAfter' value`);this.notAfter=o,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map(e=>G.create(n.AsnConvert.serialize(e)))),this.publicKey=new Ve(t.subjectPublicKeyInfo)}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e={},t=z.get()){let n,r,a=e.publicKey;try{if(!a)n={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(n,[`verify`],t);else if(`publicKey`in a)n={...a.publicKey.algorithm,...this.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);else if(a instanceof Ve)n={...a.algorithm,...this.signatureAlgorithm},r=await a.export(n,[`verify`],t);else if(i.BufferSourceConverter.isBufferSource(a)){let e=new Ve(a);n={...e.algorithm,...this.signatureAlgorithm},r=await e.export(n,[`verify`],t)}else n={...a.algorithm,...this.signatureAlgorithm},r=a}catch{return!1}let o=l.container.resolveAll(it).reverse(),s=null;for(let e of o)if(s=e.toWebSignature(n,this.signature),s)break;if(!s)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);let c=await t.subtle.verify(this.signatureAlgorithm,r,s,this.tbs);if(e.signatureOnly)return c;{let t=(e.date||new Date).getTime();return c&&this.notBefore.getTime()<t&&t<this.notAfter.getTime()}}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}async isSelfSigned(e=z.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),t=n.AsnConvert.parse(this.rawData,r.Certificate),i=t.tbsCertificate,a=new L(``,{Version:`${r.Version[i.version]} (${i.version})`,"Serial Number":i.serialNumber,"Signature Algorithm":ve.serializeAlgorithm(i.signature),Issuer:this.issuer,Validity:new L(``,{"Not Before":i.validity.notBefore.getTime(),"Not After":i.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(i.issuerUniqueID&&(a[`Issuer Unique ID`]=i.issuerUniqueID),i.subjectUniqueID&&(a[`Subject Unique ID`]=i.subjectUniqueID),this.extensions.length){let e=new L(``);for(let t of this.extensions){let n=t.toTextObject();e[n[L.NAME]]=n}a.Extensions=e}return e.Data=a,e.Signature=new L(``,{Algorithm:ve.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}};ht.NAME=`Certificate`;var gt=class extends Array{constructor(e){if(super(),W.isAsnEncoded(e))this.import(e);else if(e instanceof ht)this.push(e);else if(Array.isArray(e))for(let t of e)this.push(t)}export(e){let t=new m.SignedData;t.version=1,t.encapContentInfo.eContentType=m.id_data,t.encapContentInfo.eContent=new m.EncapsulatedContent({single:new n.OctetString}),t.certificates=new m.CertificateSet(this.map(e=>new m.CertificateChoices({certificate:n.AsnConvert.parse(e.rawData,r.Certificate)})));let i=new m.ContentInfo({contentType:m.id_signedData,content:n.AsnConvert.serialize(t)}),a=n.AsnConvert.serialize(i);return e===`raw`?a:this.toString(e)}import(e){let t=W.toArrayBuffer(e),r=n.AsnConvert.parse(t,m.ContentInfo);if(r.contentType!==m.id_signedData)throw TypeError(`Cannot parse CMS package. Incoming data is not a SignedData object.`);let i=n.AsnConvert.parse(r.content,m.SignedData);this.clear();for(let e of i.certificates||[])e.certificate&&this.push(new ht(e.certificate))}clear(){for(;this.pop(););}toString(e=`pem`){let t=this.export(`raw`);switch(e){case`pem`:return U.encode(t,`CMS`);case`pem-chain`:return this.map(e=>e.toString(`pem`)).join(`
135
+ `);case`asn`:return n.AsnConvert.toString(t);case`hex`:return i.Convert.ToHex(t);case`base64`:return i.Convert.ToBase64(t);case`base64url`:return i.Convert.ToBase64Url(t);case`text`:return ve.serialize(this.toTextObject());default:throw TypeError(`Argument 'format' is unsupported value`)}}toTextObject(){let e=n.AsnConvert.parse(this.export(`raw`),m.ContentInfo),t=n.AsnConvert.parse(e.content,m.SignedData);return new L(`X509Certificates`,{"Content Type":R.toString(e.contentType),Content:new L(``,{Version:`${m.CMSVersion[t.version]} (${t.version})`,Certificates:new L(``,{Certificate:this.map(e=>e.toTextObject())})})})}},_t=class{constructor(e={}){this.certificates=[],e.certificates&&(this.certificates=e.certificates)}async build(e,t=z.get()){let n=new gt(e),r=e;for(;r=await this.findIssuer(r,t);){let e=await r.getThumbprint(t);for(let r of n){let n=await r.getThumbprint(t);if(i.isEqual(e,n))throw Error(`Cannot build a certificate chain. Circular dependency.`)}n.push(r)}return n}async findIssuer(e,t=z.get()){if(!await e.isSelfSigned(t)){let r=e.getExtension(p.id_ce_authorityKeyIdentifier);for(let a of this.certificates)if(a.subject===e.issuer){if(r){if(r.keyId){let e=a.getExtension(p.id_ce_subjectKeyIdentifier);if(e&&e.keyId!==r.keyId)continue}else if(r.certId){let e=a.getExtension(p.id_ce_subjectAltName);if(e&&!(r.certId.serialNumber===a.serialNumber&&i.isEqual(n.AsnConvert.serialize(r.certId.name),n.AsnConvert.serialize(e))))continue}}try{let n={...a.publicKey.algorithm,...e.signatureAlgorithm},r=await a.publicKey.export(n,[`verify`],t);if(!await e.verify({publicKey:r,signatureOnly:!0},t))continue}catch{continue}return a}}return null}},vt=class{static async createSelfSigned(e,t=z.get()){if(!e.keys.privateKey)throw Error(`Bad field 'keys' in 'params' argument. 'privateKey' is empty`);if(!e.keys.publicKey)throw Error(`Bad field 'keys' in 'params' argument. 'publicKey' is empty`);return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},t)}static async create(e,t=z.get()){let r;r=e.publicKey instanceof Ve?e.publicKey.rawData:`publicKey`in e.publicKey?e.publicKey.publicKey.rawData:i.BufferSourceConverter.isBufferSource(e.publicKey)?e.publicKey:await t.subtle.exportKey(`spki`,e.publicKey);let a=e.serialNumber?i.BufferSourceConverter.toUint8Array(i.Convert.FromHex(e.serialNumber)):t.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&a[0]===0&&(a[1]|=128);let o=e.notBefore||new Date,s=e.notAfter||new Date(o.getTime()+31536e6),c=new p.Certificate({tbsCertificate:new p.TBSCertificate({version:p.Version.v3,serialNumber:a,validity:new p.Validity({notBefore:o,notAfter:s}),extensions:new p.Extensions(e.extensions?.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[]),subjectPublicKeyInfo:n.AsnConvert.parse(r,p.SubjectPublicKeyInfo)})});if(e.subject){let t=e.subject instanceof V?e.subject:new V(e.subject);c.tbsCertificate.subject=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}if(e.issuer){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);c.tbsCertificate.issuer=n.AsnConvert.parse(t.toArrayBuffer(),p.Name)}let u={hash:`SHA-256`},d=`signingKey`in e?{...u,...e.signingAlgorithm,...e.signingKey.algorithm}:{...u,...e.signingAlgorithm},f=l.container.resolve(b);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(d);let m=n.AsnConvert.serialize(c.tbsCertificate),h=`signingKey`in e?await t.subtle.sign(d,e.signingKey,m):e.signature,g=l.container.resolveAll(it).reverse(),_=null;for(let e of g)if(_=e.toAsnSignature(d,h),_)break;if(!_)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return c.signatureValue=_,new ht(n.AsnConvert.serialize(c))}};e.X509CrlReason=void 0,(function(e){e[e.unspecified=0]=`unspecified`,e[e.keyCompromise=1]=`keyCompromise`,e[e.cACompromise=2]=`cACompromise`,e[e.affiliationChanged=3]=`affiliationChanged`,e[e.superseded=4]=`superseded`,e[e.cessationOfOperation=5]=`cessationOfOperation`,e[e.certificateHold=6]=`certificateHold`,e[e.removeFromCRL=8]=`removeFromCRL`,e[e.privilegeWithdrawn=9]=`privilegeWithdrawn`,e[e.aACompromise=10]=`aACompromise`})(e.X509CrlReason||={});var yt=class extends ye{constructor(...e){let t;t=i.BufferSourceConverter.isBufferSource(e[0])?i.BufferSourceConverter.toArrayBuffer(e[0]):n.AsnConvert.serialize(new r.RevokedCertificate({userCertificate:e[0],revocationDate:new r.Time(e[1]),crlEntryExtensions:e[2]})),super(t,r.RevokedCertificate)}onInit(e){this.serialNumber=i.Convert.ToHex(e.userCertificate),this.revocationDate=e.revocationDate.getTime(),this.extensions=[],e.crlEntryExtensions&&(this.extensions=e.crlEntryExtensions.map(e=>{let t=G.create(n.AsnConvert.serialize(e));switch(t.type){case r.id_ce_cRLReasons:this.reason=n.AsnConvert.parse(t.value,r.CRLReason).reason;break;case r.id_ce_invalidityDate:this.invalidity=n.AsnConvert.parse(t.value,r.InvalidityDate).value}return t}))}},bt=class extends W{constructor(e){W.isAsnEncoded(e)?super(e,r.CertificateList):super(e),this.tag=U.CrlTag}onInit(e){let t=e.tbsCertList;this.tbs=n.AsnConvert.serialize(t),this.version=t.version;let r=l.container.resolve(b);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.tbsCertListSignatureAlgorithm=t.signature,this.certListSignatureAlgorithm=e.signatureAlgorithm,this.signature=e.signature,this.issuerName=new V(t.issuer),this.issuer=this.issuerName.toString();let i=t.thisUpdate.getTime();if(!i)throw Error(`Cannot get 'thisUpdate' value`);this.thisUpdate=i;let a=t.nextUpdate?.getTime();this.nextUpdate=a,this.entries=t.revokedCertificates?.map(e=>new yt(n.AsnConvert.serialize(e)))||[],this.extensions=[],t.crlExtensions&&(this.extensions=t.crlExtensions.map(e=>G.create(n.AsnConvert.serialize(e))))}getExtension(e){for(let t of this.extensions)if(typeof e==`string`){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter(t=>typeof e==`string`?t.type===e:t instanceof e)}async verify(e,t=z.get()){if(!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm))throw Error(`algorithm identifier in the sequence tbsCertList and CertificateList mismatch`);let n,r,i=e.publicKey;try{i instanceof ht?(n={...i.publicKey.algorithm,...i.signatureAlgorithm},r=await i.publicKey.export(n,[`verify`])):i instanceof Ve?(n={...i.algorithm,...this.signature},r=await i.export(n,[`verify`])):(n={...i.algorithm,...this.signature},r=i)}catch{return!1}let a=l.container.resolveAll(it).reverse(),o=null;for(let e of a)if(o=e.toWebSignature(n,this.signature),o)break;if(!o)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return await t.subtle.verify(this.signatureAlgorithm,r,o,this.tbs)}async getThumbprint(...e){let t,n=`SHA-1`;return e[0]&&(e[0].subtle?t=e[0]:(n=e[0]||n,t=e[1])),t??=z.get(),await t.subtle.digest(n,this.rawData)}findRevoked(e){let t=typeof e==`string`?e:e.serialNumber;for(let e of this.entries)if(e.serialNumber===t)return e;return null}},xt=class{static async create(e,t=z.get()){let a=e.issuer instanceof V?e.issuer:new V(e.issuer),o=new p.CertificateList({tbsCertList:new p.TBSCertList({version:p.Version.v2,issuer:n.AsnConvert.parse(a.toArrayBuffer(),p.Name),thisUpdate:new r.Time(e.thisUpdate||new Date)})});if(e.nextUpdate&&(o.tbsCertList.nextUpdate=new r.Time(e.nextUpdate)),e.extensions&&e.extensions.length&&(o.tbsCertList.crlExtensions=new p.Extensions(e.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension))||[])),e.entries&&e.entries.length){o.tbsCertList.revokedCertificates=[];for(let t of e.entries){let a=W.toArrayBuffer(t.serialNumber);if(o.tbsCertList.revokedCertificates.findIndex(e=>i.isEqual(e.userCertificate,a))>-1)throw Error(`Certificate serial number ${t.serialNumber} already exists in tbsCertList`);let s=new r.RevokedCertificate({userCertificate:a,revocationDate:new r.Time(t.revocationDate||new Date)});if(s.crlEntryExtensions=`extensions`in t&&t.extensions?.length?t.extensions.map(e=>n.AsnConvert.parse(e.rawData,p.Extension)):[],!(t instanceof yt)&&(t.reason&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_cRLReasons,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.CRLReason(t.reason)))})),t.invalidity&&s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_invalidityDate,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(new p.InvalidityDate(t.invalidity)))})),t.issuer)){let t=e.issuer instanceof V?e.issuer:new V(e.issuer);s.crlEntryExtensions.push(new p.Extension({extnID:p.id_ce_certificateIssuer,critical:!1,extnValue:new n.OctetString(n.AsnConvert.serialize(n.AsnConvert.parse(t.toArrayBuffer(),p.Name)))}))}o.tbsCertList.revokedCertificates.push(s)}}let s={...e.signingAlgorithm,...e.signingKey.algorithm},c=l.container.resolve(b);o.tbsCertList.signature=o.signatureAlgorithm=c.toAsnAlgorithm(s);let u=n.AsnConvert.serialize(o.tbsCertList),d=await t.subtle.sign(s,e.signingKey,u),f=l.container.resolveAll(it).reverse(),m=null;for(let e of f)if(m=e.toAsnSignature(s,d),m)break;if(!m)throw Error(`Cannot convert ASN.1 signature value to WebCrypto format`);return o.signature=m,new bt(n.AsnConvert.serialize(o))}};G.register(p.id_ce_basicConstraints,We),G.register(p.id_ce_extKeyUsage,Ge),G.register(p.id_ce_keyUsage,Ke),G.register(p.id_ce_subjectKeyIdentifier,qe),G.register(p.id_ce_authorityKeyIdentifier,Ue),G.register(p.id_ce_subjectAltName,Je),G.register(p.id_ce_cRLDistributionPoints,Xe),G.register(p.id_pe_authorityInfoAccess,Ze),rt.register(_.id_pkcs9_at_challengePassword,tt),rt.register(_.id_pkcs9_at_extensionRequest,nt),l.container.registerSingleton(it,at),l.container.registerSingleton(it,ct),ct.namedCurveSize.set(`P-256`,32),ct.namedCurveSize.set(`K-256`,32),ct.namedCurveSize.set(`P-384`,48),ct.namedCurveSize.set(`P-521`,66),e.AlgorithmProvider=y,e.AsnData=ye,e.AsnDefaultSignatureFormatter=at,e.AsnEcSignatureFormatter=ct,e.Attribute=et,e.AttributeFactory=rt,e.AuthorityInfoAccessExtension=Ze,e.AuthorityKeyIdentifierExtension=Ue,e.BasicConstraintsExtension=We,e.CRLDistributionPointsExtension=Xe,e.CertificatePolicyExtension=Ye,e.ChallengePasswordAttribute=tt,e.CryptoProvider=Se,e.DefaultAlgorithmSerializer=_e,e.ExtendedKeyUsageExtension=Ge,e.Extension=be,e.ExtensionFactory=G,e.ExtensionsAttribute=nt,e.GeneralName=Re,e.GeneralNames=ze,e.KeyUsagesExtension=Ke,e.Name=V,e.NameIdentifier=Te,e.OidSerializer=R,e.PemConverter=U,e.Pkcs10CertificateRequest=pt,e.Pkcs10CertificateRequestGenerator=mt,e.PublicKey=Ve,e.SubjectAlternativeNameExtension=Je,e.SubjectKeyIdentifierExtension=qe,e.TextConverter=ve,e.TextObject=L,e.X509Certificate=ht,e.X509CertificateGenerator=vt,e.X509Certificates=gt,e.X509ChainBuilder=_t,e.X509Crl=bt,e.X509CrlEntry=yt,e.X509CrlGenerator=xt,e.cryptoProvider=z,e.diAlgorithm=v,e.diAlgorithmProvider=b,e.diAsnSignatureFormatter=it,e.idEd25519=dt,e.idEd448=ft,e.idX25519=lt,e.idX448=ut}));De(),ca();var la;(function(e){e.Der=`der`,e.Raw=`raw`})(la||={});const ua=typeof window<`u`&&window.document!==void 0&&typeof crypto<`u`&&crypto.subtle!==void 0,da=typeof process<`u`&&process.versions!=null&&process.versions.node!=null,fa=()=>ua?`browser`:da?`node`:`purejs`,pa=async(e,t)=>{let n=t??fa();switch(n){case`browser`:return(await import(`./webcrypto-DIO-H-XA.mjs`)).signWithApiKey(e);case`node`:return(await import(`./nodecrypto-GFkDS5iF.mjs`)).signWithApiKey(e);case`purejs`:return(await import(`./purejs-CRJs90lt.mjs`)).signWithApiKey(e);default:throw Error(`Unsupported runtime: ${n}`)}};var ma=class{constructor(e){this.apiPublicKey=e.apiPublicKey,this.apiPrivateKey=e.apiPrivateKey,this.runtimeOverride=e.runtimeOverride}async stamp(e){let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n={publicKey:this.apiPublicKey,scheme:`SIGNATURE_SCHEME_TK_API_P256`,signature:t};return{stampHeaderName:`X-Stamp`,stampHeaderValue:I(JSON.stringify(n))}}async sign(e,t){switch(t){case la.Raw:{let t=await pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride),n=Te(t);return o(n)}case la.Der:return pa({publicKey:this.apiPublicKey,privateKey:this.apiPrivateKey,content:e},this.runtimeOverride);default:throw Error(`Unsupported signature format: ${t}`)}}},ha=class extends Error{constructor(e){super(e),this.name=`InvalidKeyError`}};function ga(){let e=p(`prime256v1`);return e.generateKeys(),va(e.getPrivateKey().toString(`hex`).padStart(64,`0`))}const _a=/^[0-9a-f]{64}$/i;function va(e){if(!_a.test(e))throw new ha(`P-256 private key must be 64 hex characters`);let t=e.toLowerCase(),n=p(`prime256v1`);try{n.setPrivateKey(Buffer.from(t,`hex`))}catch{throw new ha(`value is not a valid P-256 private key (scalar out of range)`)}return{algorithm:`p256`,privateKeyHex:t,publicKeyHex:n.getPublicKey(`hex`,`compressed`)}}function ya(e){try{let t=f.convertKey(e,`prime256v1`,`hex`,`hex`,`uncompressed`),n=Buffer.isBuffer(t)?t:Buffer.from(t,`hex`);return n.length===65?n:null}catch{return null}}function ba(e){let t=ya(e);if(t===null)throw new ha(`value is not a valid P-256 public key`);return xa(t)}function xa(e){let t=e.subarray(1,33).toString(`base64url`),n=e.subarray(33,65).toString(`base64url`);return m(`sha256`).update(`{"crv":"P-256","kty":"EC","x":"${t}","y":"${n}"}`,`utf8`).digest(`base64url`)}const Sa=/^https?:\/\/[\x21\x23-\x7e]{1,255}$/,Ca=/^[\x21\x23-\x3a\x3c-\x7e]{1,128}$/;function wa(e,t){return`${e.replace(/\/+$/,``)}/agent-keys/${t}`}function Ta(e){let t=Ea(e.keypair),n={...t,identityUrl:Da(e.identityUrl??wa(e.baseUrl,t.keyId))};return{sign:async e=>{let t=new Uint8Array(await e.clone().arrayBuffer()),r=Oa(n,{method:e.method,url:e.url,body:t},{nonce:g(16).toString(`base64url`),createdAt:new Date}),i=new Headers(e.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return new Request(e,{headers:i})}}}function Ea(e){let t=ya(e.publicKeyHex);if(t===null)throw Error(`signer keypair has an invalid P-256 public key`);return{signingKey:Ma(t,e.privateKeyHex),keyId:xa(t)}}function Da(e){if(!Sa.test(e))throw Error(`identity URL is outside the signature profile: "${e}"`);return e}function Oa(e,t,n){if(!Ca.test(n.nonce))throw Error(`nonce is outside the signature profile`);let r=ka(t.body),i=`"${e.identityUrl}"`,a=`("@method" "@target-uri" "content-digest" "signature-agent");created=${Math.floor(n.createdAt.getTime()/1e3)};keyid="${e.keyId}";nonce="${n.nonce}";alg="ecdsa-p256-sha256"`,o=[`"@method": ${t.method.toUpperCase()}`,`"@target-uri": ${Aa(new URL(t.url))}`,`"content-digest": ${r}`,`"signature-agent": ${i}`,`"@signature-params": ${a}`].join(`
136
+ `),s=_(`sha256`,Buffer.from(o,`utf8`),{key:e.signingKey,dsaEncoding:`ieee-p1363`});return{"Content-Digest":r,"Signature-Agent":i,"Signature-Input":`sig=${a}`,Signature:`sig=:${s.toString(`base64`)}:`}}function ka(e){return`sha-256=:${m(`sha256`).update(e??``).digest(`base64`)}:`}function Aa(e){return`${e.protocol}//${ja(e)}${e.pathname}${e.search}`}function ja(e){let t=e.host.toLowerCase();return e.protocol===`https:`&&e.port===`443`||e.protocol===`http:`&&e.port===`80`?e.hostname.toLowerCase():t}function Ma(e,t){return h({key:{kty:`EC`,crv:`P-256`,d:Buffer.from(t,`hex`).toString(`base64url`),x:e.subarray(1,33).toString(`base64url`),y:e.subarray(33,65).toString(`base64url`)},format:`jwk`})}var Na=`0.4.0`;const Pa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Fa=Na;function Ia(e,t){if(!Pa.test(e))throw Error(`${t} must be a valid HTTP token`)}function La(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function Ra(e){let t=`catena-agent-client/${Fa}`;if(!e)return t;Ia(e.name,`appInfo.name`),e.version!==void 0&&Ia(e.version,`appInfo.version`),e.url!==void 0&&La(e.url,`appInfo.url`);let n=e.version===void 0?e.name:`${e.name}/${e.version}`;return`${e.url===void 0?n:`${n} (${e.url})`} ${t}`}const za=d.object({paymentCredential:d.object({protocol:d.picklist([`mpp`,`x402`]),value:d.string()})});function Ba(e,t){let n=d.safeParse(za,e);return n.success&&n.output.paymentCredential.protocol===t?n.output.paymentCredential.value:void 0}const Va=`offer-receipt`,Ha=8192,Ua=d.pipe(d.string(),d.maxLength(Ha),d.regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,`Expected a JWS compact serialization`)),Wa=d.optional(d.pipe(d.number(),d.integer(),d.minValue(0))),Ga=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{130}$/,`Expected a 65-byte hex signature`)),Ka=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),acceptIndex:Wa,payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),acceptIndex:Wa,signature:Ua})]),qa=d.variant(`format`,[d.looseObject({format:d.literal(`eip712`),payload:d.record(d.string(),d.unknown()),signature:Ga}),d.looseObject({format:d.literal(`jws`),signature:Ua})]),Ja=d.object({[Va]:d.object({info:d.object({offers:d.array(d.unknown())})})}),Ya=d.object({[Va]:d.object({info:d.object({receipt:d.unknown()})})}),Xa=d.looseObject({version:d.literal(1),resourceUrl:d.pipe(d.string(),d.maxLength(2048)),scheme:d.pipe(d.string(),d.maxLength(64)),network:d.pipe(d.string(),d.maxLength(64)),asset:d.pipe(d.string(),d.maxLength(128)),payTo:d.pipe(d.string(),d.maxLength(128)),amount:d.pipe(d.string(),d.regex(/^\d+$/),d.maxLength(78)),validUntil:d.optional(d.pipe(d.number(),d.integer(),d.minValue(0)))});function Za(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Qa(e){if(e.format===`eip712`){let t=d.safeParse(Xa,e.payload);return t.success?t.output:void 0}let t=e.signature.split(`.`)[1];try{let e=d.safeParse(Xa,Za(t));return e.success?e.output:void 0}catch{return}}function $a(e,t){return e.toLowerCase()===t.toLowerCase()}function eo(e,t){return e.scheme===t.scheme&&e.network===t.network&&$a(e.asset,t.asset)&&$a(e.payTo,t.payTo)&&e.amount===t.amount}function to(e){return new TextEncoder().encode(JSON.stringify(e)).length<=Ha}function no(e,t){let n=d.safeParse(Ja,e);if(n.success)for(let e of n.output[Va].info.offers){let n=d.safeParse(Ka,e);if(!n.success)continue;let r=Qa(n.output);if(r!==void 0&&eo(r,t)&&to(n.output))return n.output}}function ro(e){let t=d.safeParse(Ya,e);if(!t.success)return;let n=d.safeParse(qa,t.output[Va].info.receipt);if(n.success&&to(n.output))return n.output}const io=d.pipe(d.string(),d.regex(/\S/,`Response enum values must not be blank`));function ao(e){return io}const oo=d.object({amount:d.string(),asset_id:d.string()}),so=d.pipe(d.string(),d.isoTimestamp()),co=d.object({success:d.literal(!0)}),lo=d.object({id:d.string(),name:d.string(),status:d.string(),organizationId:d.string()}),uo=d.object({agent:lo}),fo=[`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`,`hourly_count`,`daily_count`],po=d.object({id:d.string(),ruleType:ao(fo),thresholdAmount:d.optional(oo),thresholdCount:d.optional(d.number()),action:ao([`block`,`require_approval`]),requiredApprovals:d.number(),accountAggregationScope:ao([`per_account`,`across_accounts`]),actorAggregationScope:ao([`per_agent`,`per_policy`]),displayOrder:d.number()}),mo=d.object({id:d.string(),organizationId:d.string(),policyId:d.string(),capability:ao([`query_balance`,`read`,`send`,`transfer`]),accountId:d.string(),rules:d.array(po),createdAt:so,updatedAt:so}),ho=[`allow`,`block`,`require_approval`],go=[`open`,`restricted`],_o=ao(ho),vo=d.object({mode:ao(go),allowedCounterparties:d.optional(d.array(d.string())),createAction:d.optional(_o),requestPaymentDetailsAction:d.optional(_o),allowCreate:d.optional(d.boolean())}),yo=d.object({id:d.optional(d.string()),description:d.optional(d.string()),version:d.optional(d.number()),name:d.string(),capabilities:d.array(d.string()),counterpartyRules:d.optional(vo),policyCapabilities:d.array(mo),kind:d.optional(d.picklist([`base`,`override`])),expiresAt:d.optional(d.string())}),bo=d.object({policy:yo}),xo=d.object({accounts:d.array(d.object({id:d.string(),name:d.string(),type:d.string(),currency:d.string()}))}),So=d.object({accountId:d.string(),balance:oo,balances:d.optional(d.object({total:oo,available:oo,byNetwork:d.optional(d.array(d.object({network:d.string(),total:oo,available:oo})))}))}),Co=[`operator-send`,`operator-transfer`,`operator-deposit`,`operator-refund`,`microdeposit`],wo=[`pending`,`processing`,`completed`,`failed`,`reversed`],To=[`initiated`,`provider_pending`,`processing`,`completed`,`failed`,`reversed`,`manual_review`],Eo=[`ach`,`wire`,`on-chain`],Do=d.object({id:d.string(),type:ao(Co),action:d.optional(d.string()),status:ao(wo),movementStatus:ao(To),direction:d.picklist([`incoming`,`outgoing`]),amount:oo,fee:oo,currency:d.string(),network:d.optional(d.string()),counterpartyName:d.optional(d.string()),method:d.optional(ao([`ach`,`wire`,`on-chain`])),memo:d.optional(d.string()),description:d.optional(d.string()),txHash:d.optional(d.string()),createdAt:so,completedAt:d.optional(so)}),Oo=d.object({accountId:d.string(),transactions:d.array(Do),total:d.number()}),ko=d.object({accountId:d.string(),address:d.string(),liquidationAddressId:d.optional(d.string()),source:ao([`wallet`,`liquidation`])}),Ao=d.object({type:d.literal(`wallet`),walletAddress:d.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)),network:d.custom(e=>typeof e==`string`&&e.length>0)}),jo=d.object({id:d.string(),name:d.string(),status:d.optional(d.string()),rails:d.array(d.object({id:d.string(),type:d.string(),walletAddress:d.optional(d.string()),network:d.optional(d.string()),bankName:d.optional(d.string()),accountNumber:d.optional(d.string())}))}),Mo=d.object({counterparties:d.array(jo)}),No=d.picklist([`pending`,`processing`,`completed`,`blocked`,`failed`]),Po=d.object({type:d.literal(`submit_stamp`),signingRequestId:d.string(),signer:d.object({algorithm:d.literal(`p256`),publicKeyHex:d.string()}),preparedBody:d.object({body:d.string(),bodyHash:d.string(),expiresAt:so,prepareToken:d.string()}),movement:d.optional(d.object({planId:d.string(),signerAddress:d.string(),digests:d.array(d.string()),instructions:d.array(d.looseObject({kind:d.string(),network:d.string(),signerAddress:d.string(),digest:d.string(),payload:d.record(d.string(),d.unknown())}))}))}),Fo=[`send`,`transfer`,`create_counterparty`,`request_counterparty_details`,`x402`,`mpp`,`policy_override`],Io=d.object({id:d.string(),sourceNetwork:d.string(),destinationNetwork:d.string(),state:ao([`burning`,`attesting`,`minting`,`ready`,`delivering`,`delivered`,`failed`,`manual_review`]),nextStep:ao([`wait`,`continue`,`done`,`blocked`]),readyAt:d.nullable(so),deliveredAt:d.nullable(so),failureReason:d.nullable(d.string())}),Lo=d.object({planId:d.string(),nextStep:ao([`wait`,`continue`,`done`,`blocked`])}),Ro=d.object({planId:d.string()}),zo=d.object({id:d.string(),status:No,crossChain:d.optional(Io),movement:d.optional(Ro),nextAction:Po}),Bo=d.object({id:d.string(),accountId:d.optional(d.string()),type:ao(Fo),status:No,reasons:d.array(d.string()),expiresAt:d.optional(d.nullable(so),null),replayed:d.optional(d.boolean(),!1),data:d.optional(d.nullable(d.record(d.string(),d.unknown())),null),metadata:d.optional(d.object({dataUrl:d.nullable(d.string())})),crossChain:d.optional(Io),movement:d.optional(Lo),nextAction:d.optional(Po)});function Vo(e){let{nextAction:t,...n}=e;return n}const Ho=d.object({x402:d.object({paymentSignature:d.string()})});function Uo(e){let t=Ba(e,`x402`);if(t!==void 0)return t;let n=d.safeParse(Ho,e);return n.success?n.output.x402.paymentSignature:void 0}d.picklist(Eo);const Wo={ach:d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),description:d.optional(d.string()),method:d.literal(`ach`),memo:d.optional(d.string())}),wire:d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),description:d.optional(d.string()),method:d.literal(`wire`),memo:d.optional(d.string())}),"on-chain":d.object({type:d.literal(`send`),accountId:d.optional(d.pipe(d.string(),d.minLength(1))),counterpartyRailId:d.string(),amount:d.string(),description:d.optional(d.string()),method:d.literal(`on-chain`),memo:d.optional(d.string())})},Go=d.variant(`method`,[Wo.ach,Wo.wire,Wo[`on-chain`]]),Ko=d.object({type:d.literal(`transfer`),accountId:d.string(),toAccountId:d.string(),amount:d.string(),memo:d.optional(d.string()),description:d.optional(d.string())}),qo={type:d.literal(`create_counterparty`),name:d.string()},Jo=d.union([d.object({...qo,email:d.optional(d.string()),rail:d.nonOptional(d.unknown())}),d.object({...qo,email:d.string()})]),Yo=d.object({type:d.literal(`request_counterparty_details`),counterpartyId:d.string(),methods:d.pipe(d.object({bank:d.boolean(),wallet:d.boolean()}),d.check(({bank:e,wallet:t})=>e||t,`Select at least one payment method to request`))}),Xo=d.looseObject({scheme:d.string(),network:d.string(),asset:d.string(),amount:d.string(),payTo:d.string(),maxTimeoutSeconds:d.number()}),Zo=d.looseObject({url:d.string(),serviceName:d.fallback(d.optional(d.pipe(d.string(),d.maxLength(255))),void 0)}),Qo=d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{40}$/,`Expected a 20-byte hex address`)),$o=d.pipe(d.string(),d.maxLength(78),d.regex(/^(0|[1-9]\d*)$/,`Expected a canonical decimal integer string`)),es=d.object({from:Qo,to:Qo,value:$o,validAfter:$o,validBefore:$o,nonce:d.pipe(d.string(),d.regex(/^0x[0-9a-fA-F]{64}$/,`Expected a 32-byte hex nonce`))}),ts=d.object({type:d.literal(`x402`),accountId:d.string(),paymentRequirements:Xo,resource:d.optional(Zo),authorization:d.optional(es),signedOffer:d.optional(Ka)}),ns=d.object({id:d.string(),realm:d.string(),method:d.picklist([`evm`,`usdc`]),intent:d.literal(`charge`),request:d.string(),description:d.optional(d.string()),digest:d.optional(d.string()),expires:d.string(),header:d.optional(d.literal(`Payment-Authorization`)),opaque:d.optional(d.string())}),rs=d.object({url:d.string(),serviceName:d.optional(d.string())}),is=d.object({type:d.literal(`mpp`),accountId:d.string(),challenge:ns,resource:d.optional(rs)}),as=[`send`,`transfer`],os=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(as),limitType:d.picklist([`per_transaction_amount`,`daily_amount`,`weekly_amount`,`monthly_amount`]),newLimit:d.strictObject({amount:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/),d.check(e=>Number(e)>0,`The amount must be greater than zero`)),assetId:d.literal(`USD`)})}),ss=d.strictObject({type:d.literal(`increase_limit`),accountId:d.pipe(d.string(),d.minLength(1)),capability:d.picklist(as),limitType:d.picklist([`hourly_count`,`daily_count`]),newLimit:d.strictObject({count:d.pipe(d.number(),d.integer(),d.minValue(1))})}),cs=d.pipe(d.array(d.union([os,ss])),d.minLength(1),d.maxLength(10),d.check(e=>new Set(e.map(e=>`${e.accountId}|${e.capability}|${e.limitType}`)).size===e.length,`Each account, capability, and limit type may appear only once`)),ls=d.object({type:d.literal(`policy_override`),operations:cs,durationSeconds:d.pipe(d.number(),d.integer(),d.minValue(60),d.maxValue(604800)),reason:d.pipe(d.string(),d.trim(),d.minLength(1),d.maxLength(280))}),us=d.union([Go,Ko,Jo,Yo,ts,is,ls]);function ds(e){let t=d.parse(us,e);return t.type===`send`||t.type===`transfer`?{...t,amount:{amount:t.amount,asset_id:`USD`}}:t.type===`policy_override`?{...t,schemaVersion:1}:t}const fs=d.object({intent:Bo});var ps=class extends Error{status;code;details;fields;constructor(e,t,n,r,i){let a=Object.entries(i??{}).map(([e,t])=>e===`request`?t:`${e}: ${t}`).join(`; `),o=a?`${t}: ${a}`:t;super(n?`API error ${e} [${n}]: ${o}`:`API error ${e}: ${o}`),this.name=`ApiError`,this.status=e,this.code=n,this.details=r,this.fields=i}},ms=class extends Error{timeoutMs;constructor(e){super(`Request timed out after ${e}ms. The server may still have processed a state-changing request; follow that operation's documented recovery procedure before retrying.`),this.name=`TimeoutError`,this.timeoutMs=e}};const hs=d.object({error:d.nullish(d.string()),message:d.nullish(d.string()),code:d.nullish(d.string()),details:d.nullish(d.record(d.string(),d.unknown())),fields:d.fallback(d.nullish(d.pipe(d.unknown(),d.check(e=>!Array.isArray(e)),d.record(d.string(),d.string()))),void 0)});async function gs(e){let t=d.safeParse(hs,await e.json().catch(()=>void 0)),n=t.success?t.output:{};return n.error!=null&&n.message!=null?new ps(e.status,n.message,n.code??n.error,n.details??void 0,n.fields??void 0):new ps(e.status,n.error??n.message??e.statusText,n.code??void 0,n.details??void 0,n.fields??void 0)}async function _s(e,t){if(!e.ok)throw await gs(e);return d.parse(t,await e.json())}var vs=class extends Error{intentId;outcome;constructor(e){let t=e.cause instanceof Error?e.cause.message:String(e.cause);super(e.outcome===`not-submitted`?`Intent ${e.intentId} was created but never submitted; no money moved: ${t}`:`Intent ${e.intentId} submission could not be confirmed: ${t}; poll getIntent("${e.intentId}") to a terminal status and resubmit only after blocked or failed`,{cause:e.cause}),this.name=`IntentSubmitError`,this.intentId=e.intentId,this.outcome=e.outcome}};const ys=2147483647,bs=d.looseObject({parameters:d.looseObject({payloads:d.pipe(d.array(d.unknown()),d.minLength(1))})});let xs,Ss;function Cs(){return xs??=import(`./movements-BPWh6hg3.mjs`).then(e=>e,e=>{Ss=e}),xs}async function ws(){return await Cs()===void 0?`crossChain`:`crossChain, movement`}const Ts=d.looseObject({type:d.literal(`ACTIVITY_TYPE_SIGN_RAW_PAYLOADS`)});function Es(e){try{let t=JSON.parse(e);return d.safeParse(bs,t).success||d.safeParse(Ts,t).success}catch{return!1}}var Ds=class{#e;#t;#n;#r;#i;#a;#o;constructor(e){let t=e.timeout===void 0?8e4:e.timeout;if(!Number.isInteger(t)||t<=0||t>ys)throw TypeError(`timeout must be a positive integer no greater than ${ys}`);this.#e=e.baseUrl??`https://api.catena.com`,this.#t=Ra(e.appInfo),this.#n=e.defaultHeaders??{},this.#r=va(e.privateKeyHex),this.#a=(e.fetch??globalThis.fetch).bind(globalThis),this.#o=t,this.#i=Ta({keypair:this.#r,baseUrl:this.#e,identityUrl:e.identityUrl})}#s(e){let t=new Headers({"Content-Type":`application/json`});for(let[e,n]of Object.entries(this.#n))t.set(e,n);for(let[n,r]of Object.entries(e??{}))t.set(n,r);return t.set(`User-Agent`,this.#t),t.delete(`Authorization`),t}async#c(e){let t=new URL(`${this.#e}/v1/agent-api${e.path}`);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,r);let n=new Request(t,{method:e.method,headers:this.#s(e.headers),body:e.body===void 0?null:JSON.stringify(e.body)});return this.#i.sign(n)}async#l(e,t){return this.#u(await this.#c(e),t)}async#u(e,t){let n=new AbortController,r=new Request(e,{signal:n.signal}),i;try{let e=new Promise((e,t)=>{i=setTimeout(()=>{let e=new ms(this.#o);t(e),n.abort(e)},this.#o)}),a=this.#a(r).then(e=>_s(e,t));return await Promise.race([a,e])}finally{i!==void 0&&clearTimeout(i)}}async whoami(){return(await this.#l({method:`GET`,path:`/me`},uo)).agent}async submitFeedback(e){await this.#l({method:`POST`,path:`/feedback`,body:{body:e}},co)}async getPolicy(){return(await this.#l({method:`GET`,path:`/policy`},bo)).policy}async listAccounts(){return this.#l({method:`GET`,path:`/accounts`},xo)}async getAccountBalance(e){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/balance`},So)}async listAccountTransactions(e,t={}){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/transactions`,query:{start:t.start,end:t.end,limit:t.limit?.toString(),offset:t.offset?.toString()}},Oo)}async getAccountDepositAddress(e,t){return this.#l({method:`GET`,path:`/accounts/${encodeURIComponent(e)}/deposit-address`,query:{network:t.network,asset:t.asset}},ko)}async listCounterparties(e={}){return this.#l({method:`GET`,path:`/counterparties`,query:{address:e.address,network:e.network}},Mo)}async submitIntent(e){let t=await this.#d({...e,idempotencyKey:e.idempotencyKey??crypto.randomUUID()}),n=t.nextAction;if(!n)return Vo(t);let r;try{let i=await this.#f(n,e.action);r=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(t.id)}/submit-stamp`,body:{preparedBody:n.preparedBody,stamp:i}})}catch(e){throw new vs({intentId:t.id,outcome:`not-submitted`,cause:e})}try{return await this.#m(r,t.replayed)}catch(e){throw new vs({intentId:t.id,outcome:`unknown`,cause:e})}}async#d(e){return this.#l({method:`POST`,path:`/intents`,body:{action:ds(e.action)},headers:{"Idempotency-Key":e.idempotencyKey}},Bo)}async#f(e,t){if(e.signer.publicKeyHex.toLowerCase()!==this.#r.publicKeyHex.toLowerCase())throw Error(`Local signer public key does not match requested signer ${e.signer.publicKeyHex}; linked credential has ${this.#r.publicKeyHex}`);await this.#p(e,t);let n=await new ma({apiPublicKey:this.#r.publicKeyHex,apiPrivateKey:this.#r.privateKeyHex}).stamp(e.preparedBody.body);return{publicKeyHex:this.#r.publicKeyHex,stampHeaderName:n.stampHeaderName,stampHeaderValue:n.stampHeaderValue}}async#p(e,t){let n=e.movement;if(n===void 0){if(Es(e.preparedBody.body))throw Error(`Refusing to approve this payment: it would sign pre-hashed digests with nothing describing what they commit to. Nothing was signed.`);return}let r=await Cs();if(r===void 0)throw Error("Refusing to approve this payment: its digests cannot be checked without the optional `viem` peer dependency (>=2.24.0). Nothing was signed.",{cause:Ss});let{verifyPreparedMovement:i}=r,a=i({signerAddress:n.signerAddress,digests:n.digests,instructions:n.instructions,body:e.preparedBody.body},t!==void 0&&`amount`in t?{amount:t.amount}:void 0);if(!a.ok)throw Error(`Refusing to approve this payment: ${a.reason} Nothing was signed.`)}async#m(e,t){let n=Vo((await this.#u(e,fs)).intent);return t?{...n,replayed:!0}:n}async getIntent(e){return Vo(await this.#l({method:`GET`,path:`/intents/${encodeURIComponent(e)}`},Bo))}async continueIntent(e){let t=await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/continue`,headers:{"Idempotency-Key":e.idempotencyKey??crypto.randomUUID(),"Catena-Continuation-Kinds":await ws()}},zo),n;try{let r=await this.#f(t.nextAction,e.action);n=await this.#c({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/submit-stamp`,body:{preparedBody:t.nextAction.preparedBody,stamp:r}})}catch(t){throw new vs({intentId:e.intentId,outcome:`not-submitted`,cause:t})}try{return await this.#m(n,!1)}catch(t){throw new vs({intentId:e.intentId,outcome:`unknown`,cause:t})}}async unlinkAgent(){await this.#l({method:`POST`,path:`/unlink`},co)}async reportSettlement(e){await this.#l({method:`POST`,path:`/intents/${encodeURIComponent(e.intentId)}/settlement-report`,body:{txHash:e.txHash,...e.receipt!==void 0&&{receipt:e.receipt}}},co)}};function Os(e={}){let t=e.privateKeyHex===void 0?process.env.CATENA_SECRET_KEY:e.privateKeyHex;if(t===void 0)throw new ha(`privateKeyHex is required; pass it explicitly or set CATENA_SECRET_KEY`);return new Ds({...e,privateKeyHex:t})}function ks(e){let t=se(e);return e instanceof ps&&e.details!==void 0?`${t}\nDetails:\n${JSON.stringify(e.details,null,2)}`:t}function X(e){console.error(ks(e)),process.exit(1)}const As=d.string(),js=d.boolean();function Ms(e){return e===void 0}function Ns(e){return e.issues?.[0]?.message??`Invalid value`}function Ps(e,t,n,r){return X(`${e}: ${t}${r?` (got: ${String(n)})`:``}`)}function Fs(e,t,n,r){let i=d.safeParse(e,t);return i.success?i.output:Ps(n,Ns(i),t,r)}function Is(e,t){let n=t.schema??As;return{type:e,description:t.description,negativeDescription:t.negativeDescription,required:t.required,default:t.default,parseValue(e,r){let i=Ms(e)?t.default:e;if(Ms(i)){t.required===!0&&X(`${r} is required`);return}return Fs(n,i,r,t.showValueInError===!0)}}}function Z(e){return Is(`string`,e)}function Ls(e){return Is(`positional`,e)}function Rs(e){let t=e.schema??As;return{type:`string`,description:e.description,repeatable:!0,parseValue(n,r){return(Array.isArray(n)?n:[]).map(n=>Fs(t,n,r,e.showValueInError===!0))}}}function zs(e){return{type:`boolean`,description:e.description,negativeDescription:e.negativeDescription,required:e.required,default:e.default,parseValue(t,n){let r=Ms(t)?e.default:t;if(Ms(r)){e.required===!0&&X(`${n} is required`);return}return Fs(js,r,n,!1)}}}function Bs(e){return Vs(`string`,e)}function Vs(e,t){return Is(e,{description:t.description,required:t.required,default:t.default,schema:d.picklist(t.choices,`must be one of ${t.choices.join(`|`)}`),showValueInError:!0})}function Hs(e,t){return t.type===`positional`?`<${e}>`:`--${e}`}function Us(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z0-9])([A-Z][a-z])/g,`$1 $2`).split(/[ _-]/).filter(e=>e.length>0)}function Ws(e){return Us(e).join(`-`).toLowerCase()}function Gs(e){return Us(e).map((e,t)=>t===0?e.charAt(0).toLowerCase()+e.slice(1):e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function Ks(e){return[`--${e}`,`--${Ws(e)}`,`--${Gs(e)}`]}function qs(e){let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Js(e,t,n){let r=e.indexOf(`--`),i=r===-1?e.length:r,a=[...e.slice(0,i).filter(e=>!e.startsWith(`--no-`)),...e.slice(i)],o=new Set(Ks(t)),s=new Set(Object.entries(n).filter(([e,n])=>e!==t&&n.type===`string`).flatMap(([e])=>Ks(e))),c=[];for(let e=0;e<a.length;e++){let t=a[e];if(t===`--`)break;let[n,r]=qs(t);if(o.has(n)){r===void 0?(c.push(a[e+1]??``),e++):c.push(r);continue}s.has(n)&&r===void 0&&e++}return c}function Ys(e){let t=e.required??(e.type!==`positional`&&void 0);return e.type===`boolean`?{type:e.type,description:e.description,negativeDescription:e.negativeDescription,required:t,default:typeof e.default==`boolean`?e.default:void 0}:{type:e.type,description:e.description,required:t,default:typeof e.default==`string`?e.default:void 0}}function Q(e){return{args:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ys(t)])),label(t){return Hs(t,e[t])},parse(t,n){let r=(r,i)=>{if(i.repeatable!==!0)return t[r];if(n===void 0)throw Error(`parse() needs the command's raw argv to collect the repeatable --${r} flag`);return Js(n,r,e)};return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.parseValue(r(e,t),Hs(e,t))]))}}}const Xs=Z({description:`Credential profile name`}),Zs=zs({description:`Print compact single-line JSON (for piping)`,default:!1}),Qs=/^[a-zA-Z0-9_-]+$/,$s=d.pipe(d.string(`ID must be a string`),d.minLength(1,`ID must not be empty`),d.maxLength(256,`ID is too long (max 256 characters)`),d.regex(Qs,`ID may only contain letters, digits, hyphens, and underscores`));d.picklist([`base`,`base-sepolia`,`arc`,`solana`]),d.picklist([`usdc`]),d.picklist([`evm`,`svm`]);const ec=/^0x[0-9a-fA-F]{40}$/;d.pipe(d.string(),d.trim(),d.regex(ec,`Must be a 0x-prefixed hex wallet address`),d.brand(`EvmAddress`)),d.picklist([`always`,`testnet`,`preview`]),d.picklist([`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`]);const tc=[`bridge-internal-transfer`,`bridge-wallet-transfer`,`wallet-bridge-transfer`,`wallet-wallet-transfer`],nc=[`wallet-wallet-transfer`],rc=[{network:`base`,networkLabel:`Base`,addressFamily:`evm`,blockExplorerUrl:`https://basescan.org`,blockExplorerName:`Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,caip2:`eip155:8453`,caip19:`eip155:8453/erc20:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`always`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:tc,provider:{alchemyNetwork:`base`,alchemyDeposit:{transferEmitterAddress:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,transferDecimals:6,webhook:`enabled`},bridgePaymentRail:`base`}},{network:`base-sepolia`,networkLabel:`Base Sepolia`,addressFamily:`evm`,isTestnet:!0,blockExplorerUrl:`https://sepolia.basescan.org`,blockExplorerName:`Sepolia Basescan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,caip2:`eip155:84532`,caip19:`eip155:84532/erc20:0x036CbD53842c5426634e7929541eC2318f3dCF7e`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`testnet`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:nc,provider:{alchemyNetwork:`base-sepolia`,alchemyDeposit:{transferEmitterAddress:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,transferDecimals:6,webhook:`enabled`}}},{network:`arc`,networkLabel:`Arc`,addressFamily:`evm`,blockExplorerUrl:`https://explorer.arc.io`,blockExplorerName:`Arc Explorer`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`0x3600000000000000000000000000000000000000`,caip2:`eip155:5042`,caip19:`eip155:5042/erc20:0x3600000000000000000000000000000000000000`,finality:`block-inclusion`,gasTokenIsTrackedAsset:!0,availabilityGate:`always`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:nc,provider:{alchemyNetwork:`arc`,alchemyDeposit:{transferEmitterAddress:`0xfffffffffffffffffffffffffffffffffffffffe`,transferDecimals:18,webhook:`enabled`},sendMode:`self-broadcast`}},{network:`solana`,networkLabel:`Solana`,addressFamily:`svm`,blockExplorerUrl:`https://solscan.io`,blockExplorerName:`Solscan`,asset:`usdc`,assetLabel:`USDC`,assetDecimals:6,contractAddress:`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,caip2:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`,caip19:`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,finality:`finalized`,gasTokenIsTrackedAsset:!1,availabilityGate:`preview`,customerAccess:`enabled`,chainFeeUsd:`0`,walletTransferFeeUsd:`0`,transferRoutes:tc,provider:{alchemyNotify:{webhook:`enabled`},bridgePaymentRail:`solana`}}];function ic(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){for(let t of Object.values(e))ic(t);Object.freeze(e)}}ic(rc);const ac=rc;function oc(e){return{id:e.network,label:e.networkLabel,addressFamily:e.addressFamily,blockExplorerUrl:e.blockExplorerUrl,blockExplorerName:e.blockExplorerName,...e.isTestnet?{isTestnet:!0}:{}}}function sc(e){return{id:e.asset,label:e.assetLabel,decimals:e.assetDecimals}}function cc(e){return{network:e.network,asset:e.asset,contractAddress:e.contractAddress}}function lc(e){return{id:`${e.network}-usdc`,label:`${e.networkLabel} USDC`,network:e.network,asset:`usdc`}}function uc(e){let t=[];for(let n of e)t.some(e=>e.id===n.network)||t.push(oc(n));return t}function dc(e){let t=[],n=new Set;for(let r of e)n.has(r.asset)||(n.add(r.asset),t.push(sc(r)));return t}function fc(e){return e.asset===`usdc`}const pc=uc(ac);dc(ac),ac.map(cc),ac.filter(fc).map(lc);function mc(e,t){return`${e}:${t}`}new Map(ac.map(e=>[mc(e.network,e.asset),e])),new Map(pc.map(e=>[e.id,e]));const hc=[`usdc`],gc=`base`,_c=d.pipe(d.string(),d.trim(),d.guard(e=>ec.test(e),`Must be a 0x-prefixed hex wallet address`));function vc(e){return Z({description:e.description,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),...e.default===void 0?{}:{default:e.default}})}const yc=[`registered`,`already_registered`,`not_applicable`,`registration_failed`],bc=d.pipe(d.string(),d.regex(/^0[23][0-9a-f]{64}$/)),xc=d.pipe(d.string(),d.regex(/^[0-9a-f]{64}$/)),Sc=d.object({status:d.picklist(yc),publicKeyHex:d.optional(bc),reason:d.optional(d.string())}),Cc=d.object({algorithm:d.literal(`p256`),privateKeyHex:xc,publicKeyHex:bc,registration:Sc}),wc=d.object({version:d.literal(`signer-1`),signer:Cc}),Tc=d.object({version:d.literal(1),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp())}),Ec=d.object({version:d.literal(2),refreshToken:d.pipe(d.string(),d.minLength(1)),sessionToken:d.pipe(d.string(),d.minLength(1)),expiresAt:d.pipe(d.string(),d.isoTimestamp()),signer:Cc}),Dc=d.object({version:d.literal(3),signer:Cc}),Oc=d.variant(`version`,[Tc,Ec,Dc]),kc=d.variant(`version`,[wc,Tc,Ec,Dc]);function Ac(e){return d.parse(Oc,e)}function jc(e){return d.parse(kc,e)}function Mc(e){let t=d.safeParse(kc,e);return t.success?t.output:null}function Nc(e){return{version:`signer-1`,signer:{algorithm:e.algorithm,privateKeyHex:e.privateKeyHex,publicKeyHex:e.publicKeyHex,registration:{status:`not_applicable`,reason:`pending_claim`}}}}function Pc(e,t){try{return jc(JSON.parse(e))}catch(e){throw Error(`${t} credential has an unsupported format`,{cause:e})}}function Fc(e){return Ac({version:3,signer:e})}function Ic(e){return JSON.stringify(e)}function Lc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Rc(e){return(t,n)=>zc(e,t,n)}function zc(e,t,n){return new Promise((r,i)=>{let a=y(e,[...t],{stdio:[`pipe`,`pipe`,`pipe`]}),o=[],s=[],c=!1,l=!1,u=null,d=null,f=null,p=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),r(e))},m=e=>{c||(c=!0,d!==null&&clearTimeout(d),f!==null&&clearTimeout(f),i(e))};d=setTimeout(()=>{l=!0,a.kill(`SIGTERM`),f=setTimeout(()=>{a.kill(`SIGKILL`),p({stdout:o.join(``),stderr:s.join(``),status:124})},1e3)},3e4),a.stdout.setEncoding(`utf8`),a.stderr.setEncoding(`utf8`),a.stdout.on(`data`,e=>o.push(e)),a.stderr.on(`data`,e=>s.push(e)),a.on(`error`,t=>{m(Error(`Unable to run ${e}: ${t.message}`))}),a.on(`close`,t=>{if(u!==null&&t===0){m(Error(`Unable to write to ${e} stdin: ${u.message}`));return}p({stdout:o.join(``),stderr:s.join(``),status:l?124:t})}),a.stdin.on(`error`,e=>{u=e});try{a.stdin.end(n)}catch(t){m(t instanceof Error?Error(`Unable to write to ${e} stdin: ${t.message}`):Error(`Unable to write to ${e} stdin`))}})}const Bc=`catena-agent`;function Vc(e){if(!Qs.test(e))throw Error(`Invalid credential location for credential storage: "${e}"`);return e}const Hc=Rc(`/usr/bin/secret-tool`);function Uc(e){return e.status===1&&e.stdout===``&&e.stderr.trim()===``}function Wc(e,t){if(t.status===0)return;let n=Gc(t);throw Error(`Linux Secret Service credential ${e} failed (secret-tool exited ${t.status??`without status`}): ${n}`)}function Gc(e){let t=e.stderr.toLowerCase();return e.status===124?`secret service operation timed out`:t.includes(`cannot autolaunch`)||t.includes(`dbus`)||t.includes(`d-bus`)||t.includes(`org.freedesktop.secrets`)?`secret service session is unavailable`:/\blocked\b/.test(t)?`secret service keyring appears to be locked`:t.includes(`authorization`)||t.includes(`denied`)||t.includes(`not authorized`)?`secret service authorization was denied`:`secret service operation failed; ensure the Secret Service session is available and unlocked`}function Kc(e){return e instanceof Error?e.message.includes(`ENOENT`)?Error(`Linux Secret Service credential operation failed: /usr/bin/secret-tool was not found. Install libsecret-tools and ensure a Secret Service keyring is available.`,{cause:e}):e:Error(String(e))}var qc=class{runSecretTool;constructor(e={}){if((e.platform??process.platform)!==`linux`)throw Error(`Linux Secret Service credential storage is only supported on Linux`);this.runSecretTool=e.runSecretTool??Hc}async save(e,t){let n=jc(t),r=Vc(e);if(await this.savePassword(r,Ic(n)),!Lc(await this.resolveDirectPassword(r),n))throw Error(`Linux Secret Service credential save verification failed`)}async resolve(e){return this.resolveDirectPassword(Vc(e))}async delete(e){await this.deletePassword(Vc(e))}async savePassword(e,t){Wc(`save`,await this.runSecretToolCommand([`store`,`--label`,`${Bc} ${e}`,`app`,Bc,`account`,e],t))}async resolvePassword(e){let t=await this.runSecretToolCommand([`lookup`,`app`,Bc,`account`,e]);return Uc(t)?null:(Wc(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveDirectPassword(e){let t=await this.resolvePassword(e);return t===null?null:Pc(t,`Linux Secret Service`)}async deletePassword(e){let t=await this.runSecretToolCommand([`clear`,`app`,Bc,`account`,e]);Uc(t)||Wc(`delete`,t)}async runSecretToolCommand(e,t){try{return await this.runSecretTool(e,t)}catch(e){throw Kc(e)}}};const Jc=Rc(`/usr/bin/security`),Yc=d.object({version:d.literal(1),encoding:d.literal(`base64-json`),chunks:d.pipe(d.number(),d.integer(),d.minValue(1),d.maxValue(64)),sha256:d.pipe(d.string(),d.regex(/^[a-f0-9]{64}$/))});function Xc(e){return e.status===44}function Zc(e,t){return`${e}:chunk:${t}`}function Qc(e){let t=JSON.parse(e),n=Mc(t);if(n!==null)return{kind:`direct`,payload:n};let r=d.safeParse(Yc,t);if(r.success)return{kind:`legacy`,manifest:r.output};throw Error(`macOS Keychain credential has an unsupported format`)}function $c(e,t){if(t.status===0)return;let n=el(t);throw Error(`macOS Keychain credential ${e} failed (security exited ${t.status??`without status`})${n===null?``:`: ${n}`}`)}function el(e){let t=e.stderr.toLowerCase();return e.status===124?`keychain operation timed out`:t.includes(`stdin isn't a terminal`)?`parent process has no terminal`:t.includes(`user interaction is not allowed`)?`keychain user interaction is not allowed`:t.includes(`authorization`)||t.includes(`denied`)?`keychain authorization was denied`:t.includes(`locked`)?`keychain appears to be locked`:null}function tl(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)throw Error(`macOS Keychain credential values cannot contain control characters`)}return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function nl(e,t){return[`add-generic-password`,`-s`,tl(Bc),`-a`,tl(e),`-w`,tl(t),`-U`].join(` `)+`
137
+ `}var rl=class{runSecurity;constructor(e={}){if((e.platform??process.platform)!==`darwin`)throw Error(`macOS Keychain credential storage is only supported on macOS`);this.runSecurity=e.runSecurity??Jc}async save(e,t){let n=jc(t),r=Vc(e),i=await this.resolveLegacyChunkCount(r,64);if(await this.savePassword(r,Ic(n)),!Lc(await this.resolveDirectPassword(r),n))throw Error(`macOS Keychain credential save verification failed`);await this.deleteChunks(r,i)}async resolve(e){let t=Vc(e),n=await this.resolveKeychainItem(t);return n===null?null:n.kind===`direct`?n.payload:this.resolveLegacyPayload(t,n.manifest)}async delete(e){let t=Vc(e),n=await this.resolveLegacyChunkCount(t,64);await this.deleteChunks(t,n),await this.deletePassword(t)}async savePassword(e,t){$c(`save`,await this.runSecurity([`-i`],nl(e,t)))}async resolvePassword(e){let t=await this.runSecurity([`find-generic-password`,`-a`,e,`-s`,Bc,`-w`]);return Xc(t)?null:($c(`resolve`,t),t.stdout.replace(/\r?\n$/,``))}async resolveKeychainItem(e){let t=await this.resolvePassword(e);return t===null?null:Qc(t)}async resolveDirectPassword(e){let t=await this.resolveKeychainItem(e);if(t===null)return null;if(t.kind!==`direct`)throw Error(`macOS Keychain credential direct verification failed`);return t.payload}async resolveLegacyPayload(e,t){let n=[];for(let r=0;r<t.chunks;r++){let t=await this.resolvePassword(Zc(e,r));if(t===null)throw Error(`macOS Keychain credential chunk is missing`);n.push(t)}let r=n.join(``);if(m(`sha256`).update(r).digest(`hex`)!==t.sha256)throw Error(`macOS Keychain credential checksum mismatch`);return jc(JSON.parse(Buffer.from(r,`base64`).toString(`utf8`)))}async resolveLegacyChunkCount(e,t){let n=await this.resolvePassword(e);if(n===null)return 0;try{let e=Qc(n);return e.kind===`legacy`?e.manifest.chunks:0}catch{return t}}async deleteChunks(e,t){for(let n=0;n<t;n++)await this.deletePassword(Zc(e,n))}async deletePassword(e){let t=await this.runSecurity([`delete-generic-password`,`-a`,e,`-s`,Bc]);Xc(t)||$c(`delete`,t)}};function il(e={}){let t=e.platform??process.platform;if(t===`darwin`)return new rl({platform:t});if(t===`linux`)return new qc({platform:t});throw Error(`Catena credential storage is only supported on macOS and Linux`)}const al=/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function ol(e){let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`::1`||al.test(t)}function sl(e){let t;try{t=new URL(e)}catch{return!1}return t.protocol===`https:`||t.protocol===`http:`&&ol(t.hostname)}function cl(e,t){if(!sl(e))throw Error(`${t} must be an https:// URL (http:// is allowed only for a loopback host): "${e}"`)}const ll=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,ul=d.object({status:d.optional(d.literal(`linked`),`linked`),api_url:d.pipe(d.string(),d.minLength(1)),agent_id:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Qs))}),dl=d.object({status:d.literal(`pending_connection`),api_url:d.pipe(d.string(),d.minLength(1)),client_instance_id:d.pipe(d.string(),d.regex(Qs)),created_at:d.pipe(d.string(),d.isoTimestamp())}),fl=d.variant(`status`,[ul,dl]),pl=d.union([fl,d.pipe(d.looseObject({api_url:d.optional(d.undefined()),bank_url:d.pipe(d.string(),d.minLength(1))}),d.transform(({bank_url:e,...t})=>({...t,api_url:e})),fl)]);d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),fl),directories:d.optional(d.record(d.string(),d.string()))});const ml=d.object({version:d.literal(1),default_profile:d.optional(d.string()),profiles:d.record(d.string(),d.unknown()),directories:d.optional(d.record(d.string(),d.unknown()))});function hl(){return te(process.env.HOME??ee(),`.catena`)}function gl(){return te(hl(),`profiles.json`)}function _l(e){return ll.test(e)}function vl(e){if(!_l(e))throw Error(`invalid profile name "${e}" (expected [a-zA-Z0-9][a-zA-Z0-9._-]{0,63})`)}function yl(e){return typeof e!=`object`||!e||!(`code`in e)?!1:typeof e.code==`string`}function bl(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`profiles.json is not valid JSON: ${ks(e)}`,{cause:e})}if(typeof n==`object`&&n&&`version`in n){let e=n;if(e.version!==1)throw Error(`profiles.json version ${String(e.version)} is not supported (expected 1)`)}let r=d.parse(ml,n),i={};for(let[e,n]of Object.entries(r.profiles)){if(!_l(e)){t?.(`profiles: dropping invalid profile name "${e}"`);continue}let r=d.safeParse(pl,n);if(!r.success){t?.(`profiles: dropping malformed profile "${e}"`);continue}i[e]=r.output}if(r.default_profile!==void 0&&(vl(r.default_profile),!Object.hasOwn(i,r.default_profile)))throw Error(`profiles.json default_profile "${r.default_profile}" is not linked`);let a={};for(let[e,n]of Object.entries(r.directories??{})){if(!M(e)){t?.(`profiles: dropping directory binding with relative path "${e}"`);continue}if(typeof n!=`string`||!_l(n)){t?.(`profiles: dropping malformed directory binding "${e}"`);continue}a[e]=n}return{version:1,...r.default_profile===void 0?{}:{default_profile:r.default_profile},profiles:i,...Object.keys(a).length===0?{}:{directories:a}}}function xl(e){try{return bl(T(gl(),`utf-8`),e)}catch(e){if(e instanceof Error&&yl(e)&&e.code===`ENOENT`)return{version:1,profiles:{}};throw e}}function Sl(){w(hl(),{recursive:!0,mode:448}),x(hl(),448)}function Cl(e){Sl();let t=gl(),n=`${t}.${g(6).toString(`hex`)}.tmp`;A(n,JSON.stringify(e,null,2)+`
138
+ `,{encoding:`utf-8`,mode:384}),D(n,t)}function wl(e,t){vl(e);let n=d.parse(fl,t);cl(n.api_url,`profile "${e}" api_url`);let r=xl();Cl({...r,profiles:{...r.profiles,[e]:n}})}function Tl(e){return e.status===`linked`}function El(e,t){return e.replace(/\/+$/,``)===t.replace(/\/+$/,``)}function Dl(e,t){let n=Object.entries(xl().profiles).toSorted(([e],[t])=>e.localeCompare(t)).find(([,n])=>Tl(n)&&n.agent_id===e&&El(n.api_url,t));return n===void 0?null:n[0]}function Ol(e,t){let n=Object.fromEntries(Object.entries(e??{}).filter(([,e])=>t(e)));return Object.keys(n).length===0?{}:{directories:n}}function kl(e){vl(e);let t=xl(),{[e]:n,...r}=t.profiles;Cl({version:1,...t.default_profile===e||t.default_profile===void 0?{}:{default_profile:t.default_profile},profiles:r,...Ol(t.directories,t=>t!==e)})}function Al(e){try{return E(ne(e))}catch{return ne(e)}}function jl(e){return xl().directories?.[Al(e)]??null}function Ml(e,t){vl(t);let n=xl();if(!Object.hasOwn(n.profiles,t))throw Error(`Profile "${t}" is not linked. Run catena link --profile ${t} <agent-id>.`);let r=Al(e);return Cl({...n,directories:{...n.directories,[r]:t}}),r}function Nl(e){let t=xl(),n=Al(e);if(t.directories===void 0||!Object.hasOwn(t.directories,n))return{directory:n,removed:!1};let{[n]:r,...i}=t.directories,{directories:a,...o}=t;return Cl({...o,...Object.keys(i).length===0?{}:{directories:i}}),{directory:n,removed:!0}}function Pl(e){return vl(e),xl().profiles[e]??null}function Fl(){return`client_${g(16).toString(`hex`)}`}function Il(e,t){let n=Pl(e);return t.agent_id===void 0?Ll(e,t.api_url,n):Rl(e,t.api_url,t.agent_id,n)}function Ll(e,t,n){if(n?.status===`linked`)throw Error(`Profile "${e}" is already linked. Choose a different profile name to start agent connection.`);let r=(n?.status===`pending_connection`&&El(n.api_url,t)?n.client_instance_id:null)??Fl();return wl(e,{status:`pending_connection`,api_url:t,client_instance_id:r,created_at:n?.status===`pending_connection`?n.created_at:new Date().toISOString()}),r}function Rl(e,t,n,r){if(r?.status===`linked`){if(r.agent_id!==n)throw Error(`Profile "${e}" is already linked to a different agent (${r.agent_id}). Link ${n} under a different --profile, or run 'catena unlink --profile ${e}' first to repoint it (add --force if that agent's credential is missing or revoked).`);if(!El(r.api_url,t))throw Error(`Profile "${e}" is already linked to this agent on a different Catena API (${r.api_url}). Link under a different --profile, or run 'catena unlink --profile ${e}' first (add --force if that credential is missing or revoked).`);return r.client_instance_id}let i=(r?.status===`pending_connection`&&El(r.api_url,t)?r.client_instance_id:null)??Fl();return wl(e,{status:`linked`,api_url:t,agent_id:n,client_instance_id:i}),i}function zl(e){vl(e);let t=xl();if(!Object.hasOwn(t.profiles,e))throw Error(`Profile "${e}" is not linked. Run catena link --profile ${e} <agent-id>.`);Cl({...t,default_profile:e})}function Bl(e){let t=e.toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/^[^a-z0-9]+/,``).slice(0,64);return _l(t)?t:`agent`}function Vl(e,t){if(!t(e))return e;for(let n=2;;n++){let r=`${e.slice(0,64-String(n).length-1)}-${n}`;if(!t(r))return r}}function Hl(e){vl(e.reservationName),vl(e.profileName);let t=d.parse(fl,e.profile);cl(t.api_url,`profile "${e.profileName}" api_url`);let n=xl(),{[e.reservationName]:r,...i}=n.profiles;if(!Object.hasOwn(n.profiles,e.reservationName)||r.client_instance_id!==t.client_instance_id)throw Error(`Link reservation "${e.reservationName}" changed during setup (a concurrent link from this directory?). Re-run 'catena link'.`);if(e.profileName!==e.reservationName&&Object.hasOwn(i,e.profileName))throw Error(`Profile "${e.profileName}" already exists; cannot finalize link under that name.`);let a=Object.fromEntries(Object.entries(n.directories??{}).map(([t,n])=>[t,n===e.reservationName?e.profileName:n]));Cl({version:1,...n.default_profile===void 0?{}:{default_profile:n.default_profile===e.reservationName?e.profileName:n.default_profile},profiles:{...i,[e.profileName]:t},...Object.keys(a).length===0?{}:{directories:a}})}function Ul(e){return e??il()}async function Wl(e,t){let n;try{n=Pl(e.profileName)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:ks(t)}}if(n===null)return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:`Profile "${e.profileName}" is not linked. Run 'catena link --profile ${e.profileName}' to authenticate.`};try{cl(n.api_url,`profile "${e.profileName}" api_url`)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:e.fallbackApiUrl,message:ks(t)}}if(n.status===`pending_connection`)return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" is waiting for agent connection approval. Run 'catena link --profile ${e.profileName}' to finish setup.`};let r;try{r=await Ul(t).resolve(n.client_instance_id)}catch(t){return{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}: ${ks(t)}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}}return r===null||r.version===`signer-1`?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential unavailable for ${n.agent_id}. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:r.version===1?{ok:!1,profileName:e.profileName,apiUrl:n.api_url,message:`Profile "${e.profileName}" credential for ${n.agent_id} has no signing key. Run 'catena link --profile ${e.profileName} ${n.agent_id}' to authenticate.`}:{ok:!0,profileName:e.profileName,apiUrl:n.api_url,agentId:n.agent_id,clientInstanceId:n.client_instance_id,signer:r.signer}}const Gl=`https://api.catena.com`,Kl=`CATENA_SECRET_KEY`;function ql(e,t){let n=e[t]?.trim();return n===void 0||n.length===0?void 0:n}function Jl(e=process.env){return ql(e,Kl)!==void 0}function Yl(e=process.env){let t=ql(e,Kl);if(t===void 0)return null;let n=ql(e,`CATENA_API_URL`)??`https://api.catena.com`;return cl(n,`CATENA_API_URL`),{apiUrl:n,privateKeyHex:t}}const Xl=`CATENA_PROFILE`;function Zl(e,t,n,r){if(e.directories===void 0)return null;let i;try{i=E(t)}catch{return null}let a=Object.entries(e.directories).map(([e,t])=>[e.replace(/\/+$/,``)||`/`,t]).filter(([e])=>i===e||i.startsWith(e===`/`?`/`:`${e}/`)).toSorted(([e],[t])=>t.length-e.length),o=null;for(let[t,n]of a){if(Object.hasOwn(e.profiles,n))return n;o??=`${t} -> "${n}"`}if(o===null)return null;if(n===`error`)throw Error(`This directory is bound to a profile that no longer exists (${o}). Run 'catena profiles unbind' here, bind it with 'catena profiles bind <name>', or run 'catena link' to re-establish it.`);return r?.(`profiles: ignoring stale directory binding ${o}`),null}function Ql(e,t,n){if(e.flag!==void 0&&e.flag.length>0)return vl(e.flag),{name:e.flag,source:`flag`};if(e.env!==void 0&&e.env.length>0){if(!_l(e.env))throw Error(`${Xl} is set to an invalid profile name "${e.env}"`);return{name:e.env,source:`env`}}if(e.cwd!==void 0){let r=Zl(t,e.cwd,n,e.log);if(r!==null)return{name:r,source:`directory`}}return t.default_profile===void 0?null:{name:t.default_profile,source:`default`}}function $l(e){return Ql(e,xl(e.log),`ignore`)}function eu(e){let t=xl(e.log),n=Ql(e,t,`error`);if(n!==null)return n;let r=Object.keys(t.profiles),i=Object.entries(t.profiles).filter(([,e])=>Tl(e)).map(([e])=>e);if(i.length===1){let[e]=i;return{name:e,source:`single`}}if(i.length===0){if(r.length===1){let[e]=r;return{name:e,source:`single`}}return r.length>1&&e.log?.(`profiles: ignoring ${r.length} pending profiles (${r.toSorted().join(`, `)}); none is linked`),{name:`default`,source:`fallback`}}throw Error(`Multiple profiles exist and none is selected (${i.toSorted().join(`, `)}). Pass --profile <name>, set ${Xl}, run 'catena profiles use <name>', or run 'catena link' from an agent directory to bind it.`)}function tu(){try{return Object.entries(xl().profiles).filter(([,e])=>Tl(e)).map(([e])=>e).toSorted()}catch{return[]}}function nu(e=process.env){let t=e[Xl]?.trim();if(t!==void 0&&t.length>0)return`profiles: signing with ${Kl}; ${Xl}=${t} is ignored. Pass --profile ${t} to use that profile.`;let n=tu();if(n.length===0)return null;let r=n.length===1?`profile`:`profiles`;return`profiles: signing with ${Kl}; ${n.length} linked ${r} ignored (${n.join(`, `)}). Pass --profile <name> to use one.`}const ru={name:`catena-cli`,version:oe},iu=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function au(e,t){if(!iu.test(e))throw Error(`${t} must be a valid HTTP token`)}function ou(e,t){let n=!1;for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<32||r===127||r>255){n=!0;break}}if(n||/[()\\]/.test(e))throw Error(`${t} must not contain parentheses, backslashes, control characters, or characters outside Latin-1`)}function su(e){au(e.name,`appInfo.name`),e.version!==void 0&&au(e.version,`appInfo.version`),e.url!==void 0&&ou(e.url,`appInfo.url`);let t=e.version===void 0?e.name:`${e.name}/${e.version}`;return{"User-Agent":e.url===void 0?t:`${t} (${e.url})`}}function cu(e){return Os({baseUrl:e.apiUrl,privateKeyHex:e.signer.privateKeyHex,appInfo:ru})}function lu(){return il()}function uu(e){try{return Os({baseUrl:e.apiUrl,privateKeyHex:e.privateKeyHex,appInfo:ru})}catch(e){return X(`${Kl} is not usable: ${ks(e)}`)}}async function du(e){if(e===void 0){let e;try{e=Yl()}catch(e){return X(e)}if(e!==null){let t=nu();return t!==null&&console.error(t),uu(e)}}let t;try{t=eu({flag:e,env:process.env[Xl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){return X(e)}let n=await Wl({profileName:t,fallbackApiUrl:Gl},void 0);return n.ok||X(n.message),cu(n)}const fu=new Set([`unknown_key`,`key_revoked`,`client_unlinked`]),pu=new Set([`signature_auth_disabled`,`missing_auth`]);function mu(e,t,n=process.env){if(!(e instanceof ps)||e.code===void 0)return e;let r=t===void 0?`catena link`:`catena link --profile ${t}`;return fu.has(e.code)?t===void 0&&Jl(n)?Error(`Catena rejected the ${Kl} signing key (${e.code}). Create a secret key in the Catena console under the agent's Secret keys tab, then update ${Kl}.`):Error(`Catena rejected this machine's signing key (${e.code}). Run '${r}' to re-authenticate.`):e.code===`client_upgrade_required`?Error(`This CLI version (${ru.version}) is no longer supported by the Catena API. Run 'npm i -g @catena/cli' and retry.`):pu.has(e.code)?Error(`This Catena API does not support key-based authentication (${e.code}). Upgrade it, or use an older CLI release that authenticates with session tokens.`):e.code===`invalid_signature`&&e.message.includes(`created_out_of_window`)?Error(`Catena rejected this request's timestamp (created_out_of_window). Check this machine's system clock and retry.`):e}function hu(e,t){console.log(t?.compact?JSON.stringify(e):JSON.stringify(e,null,2))}function gu(e){return e.profile===void 0||e.profile.length===0?void 0:e.profile}async function _u(e,t){try{return await t(await du(e))}catch(t){return X(mu(t,e))}}function vu(e,t){return async(n,r)=>{let i=await _u(e,n);return hu(i,t),await new Promise(e=>{process.stdout.write(``,()=>e())}),process.exit(r?.exitCode?r.exitCode(i):0)}}function $(e){return vu(gu(e),{compact:e.json===!0})}const yu=d.pipe(d.string(),d.regex(/^\d+$/,`must be a non-negative integer`),d.transform(Number),d.maxValue(2**53-1,`must be at most ${2**53-1}`)),bu=d.pipe(yu,d.maxValue(200,`must be at most 200`)),xu={profile:Xs,json:Zs},Su=Q(xu),Cu=Q({account:Ls({description:`Account id`,required:!0,schema:$s}),...xu}),wu=Q({account:Ls({description:`Account id`,required:!0,schema:$s}),start:Z({description:`Only include transactions at or after this ISO 8601 time`}),end:Z({description:`Only include transactions at or before this ISO 8601 time`}),limit:Z({description:`Maximum transactions to return (default 50, max 200)`,schema:bu}),offset:Z({description:`Number of transactions to skip for pagination`,schema:yu}),...xu}),Tu=Q({account:Ls({description:`Account id`,required:!0,schema:$s}),network:vc({description:`Deposit network; defaults to ${gc}. Availability depends on the connected environment.`,default:gc}),asset:Z({description:`Deposit asset; known value: ${hc.join(`|`)}`,schema:d.pipe(d.string(),d.trim(),d.minLength(1)),default:`usdc`}),...xu}),Eu=c({meta:{name:`list`,description:`List accounts accessible under the agent's policy`},args:Su.args,async run({args:e}){await $(Su.parse(e))(e=>e.listAccounts())}}),Du=c({meta:{name:`balance`,description:`Request an account balance through the policy engine`},args:Cu.args,async run({args:e}){let t=Cu.parse(e);await $(t)(e=>e.getAccountBalance(t.account))}}),Ou=c({meta:{name:`transactions`,description:`Read an account's transaction history through the policy engine`},args:wu.args,async run({args:e}){let t=wu.parse(e);await $(t)(e=>e.listAccountTransactions(t.account,{start:t.start,end:t.end,limit:t.limit,offset:t.offset}))}}),ku=c({meta:{name:`deposit-address`,description:`Read an account deposit address through the policy engine`},args:Tu.args,async run({args:e}){let t=Tu.parse(e);await $(t)(e=>e.getAccountDepositAddress(t.account,{network:t.network,asset:t.asset}))}}),Au=c({meta:{name:`accounts`,description:`Inspect bank accounts`},subCommands:{list:Eu,balance:Du,transactions:Ou,"deposit-address":ku}}),ju=d.pipe(d.string(`Idempotency key must be a string`),d.minLength(1,`Idempotency key must not be empty`),d.maxLength(255,`Idempotency key is too long (max 255 characters)`)),Mu=d.pipe(d.string(),d.minLength(1,`must not be empty`)),Nu=d.pipe(d.string(),d.trim(),d.email(`must be a valid email address`)),Pu={profile:Xs,json:Zs},Fu=Q({address:Z({description:`Only counterparties with a wallet rail matching this address (0x…)`,schema:_c}),network:vc({description:`Only counterparties owning a wallet address in this network class (e.g. base); not a settlement promise`}),...Pu}),Iu=Z({description:`Counterparty name`,required:!0,schema:Mu}),Lu=Z({description:`Optional contact email`,schema:Nu}),Ru=Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:ju}),zu=Q({name:Iu,email:Z({description:`Contact email; creating the counterparty sends no email`,required:!0,schema:Nu}),"idempotency-key":Ru,...Pu}),Bu=Q({name:Z({description:`Counterparty name; required without a subcommand`,schema:Mu}),email:Z({description:`Contact email; required without a subcommand; creating the counterparty sends no email`,schema:Nu}),"idempotency-key":Ru,...Pu}),Vu=Q({name:Iu,"bank-name":Z({description:`Receiving bank name`,required:!0,schema:Mu}),"routing-number":Z({description:`9-digit ABA routing number`,required:!0,schema:Mu}),"account-number":Z({description:`Receiving bank account number`,required:!0,schema:Mu}),"account-type":Bs({description:`checking | savings (default checking)`,choices:[`checking`,`savings`]}),"address-street":Z({description:`Street address of the receiving bank account holder`,required:!0,schema:Mu}),"address-city":Z({description:`City`,required:!0,schema:Mu}),"address-state":Z({description:`State (e.g. NY)`,required:!0,schema:Mu}),"address-postal-code":Z({description:`Postal code`,required:!0,schema:Mu}),"address-country":Z({description:`Default USA`}),email:Lu,"idempotency-key":Ru,...Pu}),Hu=Q({name:Iu,address:Z({description:`Wallet address (0x… or ENS name on EVM networks)`,required:!0,schema:Mu}),network:vc({description:`Wallet network; defaults to ${gc}. Availability depends on the connected environment.`,default:gc}),email:Lu,"idempotency-key":Ru,...Pu}),Uu=Q({counterparty:Ls({description:`Counterparty id`,required:!0,schema:$s}),bank:zs({description:`Request bank account details`,default:!1}),wallet:zs({description:`Request wallet details`,default:!1}),"idempotency-key":Ru,...Pu}),Wu=c({meta:{name:`list`,description:`List counterparties available under the agent's policy`},args:Fu.args,async run({args:e}){let t=Fu.parse(e);await $(t)(e=>e.listCounterparties({address:t.address,network:t.network}))}});function Gu(e){return e&&e.length>0?e:void 0}function Ku(e){let t=Gu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`bank`,bankName:e[`bank-name`],routingNumber:e[`routing-number`],accountNumber:e[`account-number`],addressStreet:e[`address-street`],addressCity:e[`address-city`],addressState:e[`address-state`],addressPostalCode:e[`address-postal-code`],...e[`account-type`]?{accountType:e[`account-type`]}:{},...e[`address-country`]?{addressCountry:e[`address-country`]}:{}}}}function qu(e){let t=Gu(e.email);return{type:`create_counterparty`,name:e.name,email:t,rail:{type:`wallet`,walletAddress:e.address,network:e.network}}}function Ju(e){return{type:`create_counterparty`,name:e.name,email:e.email}}const Yu=c({meta:{name:`email`,description:`Create a counterparty with an email and no payment details. Sends no email.`},args:zu.args,async run({args:e}){let t=zu.parse(e);await $(t)(e=>e.submitIntent({action:Ju(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Xu=c({meta:{name:`bank`,description:`Request bank counterparty creation through the policy engine. Prints an intent envelope.`},args:Vu.args,async run({args:e}){let t=Vu.parse(e),n=Ku(t);await $(t)(e=>e.submitIntent({action:n,...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Zu=c({meta:{name:`wallet`,description:`Request wallet counterparty creation through the policy engine. Prints an intent envelope.`},args:Hu.args,async run({args:e}){let t=Hu.parse(e);await $(t)(e=>e.submitIntent({action:qu(t),...t[`idempotency-key`]!==void 0&&{idempotencyKey:t[`idempotency-key`]}}))}}),Qu=c({meta:{name:`create`,description:`Request counterparty creation through the policy engine. Without a subcommand, --name and --email create a record without payment details and send no email.`},args:Bu.args,default:`email`,subCommands:{email:Yu,bank:Xu,wallet:Zu}}),$u=c({meta:{name:`request-details`,description:`Ask a counterparty to provide bank details, wallet details, or both through the policy engine.`},args:Uu.args,async run({args:e}){let t=Uu.parse(e);!t.bank&&!t.wallet&&X(`Select at least one of --bank or --wallet`),await $(t)(e=>e.submitIntent({action:{type:`request_counterparty_details`,counterpartyId:t.counterparty,methods:{bank:t.bank,wallet:t.wallet}},...t[`idempotency-key`]?{idempotencyKey:t[`idempotency-key`]}:{}}))}}),ed=c({meta:{name:`counterparties`,description:`Inspect, create, and request details from counterparties`},subCommands:{list:Wu,create:Qu,"request-details":$u}}),td=4e3;async function nd(){process.stdin.setEncoding(`utf8`);let e=``;for await(let t of process.stdin)e+=t;return e}async function rd(e){return e===void 0?(process.stdin.isTTY&&X(`<message>: pass a quoted message or pipe it on stdin; a message starting with "-" needs -- before it (catena feedback -- "<message>") or stdin`),nd()):e}const id=Q({message:Ls({description:`Plain-text feedback (1-4000 chars); omit to pipe on stdin`}),profile:Xs,json:Zs}),ad=c({meta:{name:`feedback`,description:`Send free-form feedback about Catena to the Catena team`},args:id.args,async run({args:e}){(Array.isArray(e._)?e._:[]).length>1&&X(`<message>: pass the message as a single quoted argument`);let t=id.parse(e),n=(await rd(t.message)).trim();n.length===0&&X(`<message>: must not be empty`),n.length>td&&X(`<message>: must be at most ${td} characters (got: ${n.length})`),await $(t)(async e=>(await e.submitFeedback(n),{ok:!0}))}});function od(e){return`# Catena CLI Agent Guide
139
139
 
140
140
  CLI version: ${e}
141
141
 
@@ -301,7 +301,7 @@ convenience for interactive use.
301
301
  Run \`accounts list\` before you choose an explicit send source, and before a
302
302
  transfer. Account ids (\`acct_...\`) go into \`--account\`, \`--from\`, or
303
303
  \`--to\`. Run \`counterparties list\` before a send. \`--rail\` takes a rail id
304
- (\`cprl_...\`), not a counterparty id.
304
+ (\`cpr_...\`), not a counterparty id.
305
305
 
306
306
  Direct per-account reads are plain reads, not intents:
307
307
 
@@ -309,6 +309,18 @@ Direct per-account reads are plain reads, not intents:
309
309
  catena accounts transactions acct_...
310
310
  catena accounts deposit-address acct_...
311
311
 
312
+ \`accounts balance\` returns \`.balances.total\` and \`.balances.available\`.
313
+ Size a payment against \`.available\`, which is what one payment can move. It
314
+ reads zero while the account is not active, and so does every
315
+ \`.balances.byNetwork[]\` \`available\`. It reads the largest row while the
316
+ network of the account holds nothing yet.
317
+ \`.balances.byNetwork[]\` gives the \`network\`, \`total\`, and \`available\`
318
+ for each network that the account holds and agents may use. The rows can add
319
+ up to less than \`.balances.total\` when the account also holds money on a
320
+ network that agents may not use. Their \`available\` can add up to more than
321
+ \`.balances.available\`, because one payment binds one network. This field is
322
+ absent until Catena splits the money of the account by network.
323
+
312
324
  \`accounts transactions\` returns \`.transactions[]\` with the newest first, and
313
325
  a \`.total\` count. Use \`--limit\` and \`--offset\` to read more pages. The
314
326
  \`status\` of a transaction is not the status of an intent. Read it to confirm
@@ -319,9 +331,11 @@ what the agent can do.
319
331
  \`--network\` must match the network of the account. Catena does not always
320
332
  enable every network. A network that Catena does not enable fails with a
321
333
  server error that lists the enabled networks. A network that the account is not
322
- on fails with a configured-network error. No command returns the network of an
323
- account. Use \`base\` by default. After either error, run the command again with
324
- a network that the error names. Do not invent a network.
334
+ on fails with a configured-network error. When \`.balances.byNetwork[]\` is
335
+ present, use a \`network\` it names. An empty list means no network of the
336
+ account is open to agents, so every network fails until that changes. When the
337
+ field is absent, use \`base\` by default. After either error, run the command
338
+ again with a network that the error names. Do not invent a network.
325
339
 
326
340
  ## Counterparties
327
341
 
@@ -331,10 +345,15 @@ saved:
331
345
  catena counterparties list \\
332
346
  --address 0x... --network base
333
347
 
334
- Both filters must agree on the same rail. An address saved on a different
335
- network is not a match. A match returns the full counterparty. Use the
336
- \`rails[].id\` (\`cprl_...\`) of the rail whose \`walletAddress\` and \`network\`
337
- both match. Do not make a duplicate.
348
+ Both filters must agree on the same rail and network class. The network filter
349
+ is an ownership check, not a promise that the payment will settle on that
350
+ network. A match returns the full counterparty. Use the \`rails[].id\`
351
+ (\`cpr_...\`) of the rail whose \`walletAddress\` matches. A wallet rail can
352
+ omit \`network\` when its configured destination is unavailable to the agent;
353
+ do not substitute the query network or create a duplicate. That rail cannot
354
+ receive an agent send until the counterparty's network configuration or the
355
+ organization's capability changes. A rail that does report a network can also
356
+ receive across chains when an admitted route is available.
338
357
 
339
358
  An empty \`counterparties\` array means that no counterparty you can see holds
340
359
  that rail. A counterparty outside the allow-list of the agent stays hidden. Bad
@@ -430,14 +449,16 @@ Do these three things before either command:
430
449
 
431
450
  Examples:
432
451
 
433
- catena send --rail cprl_... \\
452
+ catena send --rail cpr_... \\
434
453
  --amount 125.00 --method ach
435
454
  catena transfer --from acct_... --to acct_... \\
436
455
  --amount 125.00
437
456
 
438
457
  \`--method\` must match the rail type. \`ach\` and \`wire\` need a bank rail.
439
458
  \`on-chain\` needs a wallet rail. A wrong pair fails with
440
- \`rail_method_mismatch\`. See \`--help\` for the memo and description flags.
459
+ \`rail_method_mismatch\`. \`--memo\` is sent with ACH and wire payments. It is
460
+ accepted for on-chain sends only for compatibility, is deprecated, and is not
461
+ sent to the blockchain. Use \`--description\` for an internal Catena note.
441
462
 
442
463
  An intent's source account stays fixed through approval.
443
464
 
@@ -454,9 +475,12 @@ is an ordinary \`send\`. When the account cannot pay it from its balance on the
454
475
  rail's network, the send crosses chains under the same intent: the first
455
476
  signature burns the amount toward the account's own address on the other
456
477
  chain, and a second signature pays the counterparty once the funds land. Gas
457
- on both legs is paid by Catena; there is no fee flag.
478
+ on both legs is paid by Catena; there is no fee flag. You do not select the
479
+ network of a send. When a send is refused for the amount,
480
+ \`.balances.byNetwork[]\` from \`accounts balance\` shows where the money
481
+ sits, which explains the refusal.
458
482
 
459
- catena send --rail cprl_... --amount 250.00 --method on-chain
483
+ catena send --rail cpr_... --amount 250.00 --method on-chain
460
484
  catena intents get int_...
461
485
  catena intents continue int_...
462
486
 
@@ -480,6 +504,50 @@ A network the provider does not sponsor yet answers
480
504
  chain; tell the user and do not retry. On \`intents continue\` that means the
481
505
  destination chain; the intent stays at \`continue\`, so try again later.
482
506
 
507
+ ## Payments A Person Has To Approve
508
+
509
+ Over the organization's approval threshold, a \`send\` is not refused: it is
510
+ parked for a person, and \`status\` reads \`pending\` with \`reasons\` saying
511
+ why. Nothing is held and no money has moved.
512
+
513
+ catena send --rail cprl_... --amount 5000.00 --method on-chain
514
+ catena intents get int_...
515
+
516
+ A link with no registered signing key cannot sign at all, so every wallet
517
+ payment it asks for parks this way, whatever the amount. \`reasons\` then
518
+ carries \`agent_signer_not_registered\` when the payment has a \`.movement\`,
519
+ or \`operator_signature_required\` when it does not. Running \`link\` again
520
+ registers a key once the organization can sign, and payments under the
521
+ threshold are then yours to sign.
522
+
523
+ Read \`.movement\` on the envelope. When it is present, the payment is carried
524
+ by a movement plan, and \`.movement.nextStep\` is the contract:
525
+
526
+ - \`wait\`: it is not your turn. Poll \`intents get\`. Do not start a second
527
+ payment. If you restarted before signing a payment nobody had to approve,
528
+ send the original request again on the same idempotency key. Within about
529
+ five minutes of the first send it answers
530
+ \`movement_authorization_in_progress\`; after that it hands the payment back
531
+ for you to sign.
532
+ - \`done\`: the counterparty was paid.
533
+ - \`blocked\`: it ended without paying; read \`reasons\`. It is empty when an
534
+ approval lapsed with nobody finishing the payment.
535
+
536
+ **You do not finish this payment.** A person approves it and an admin signs it
537
+ in the Catena console, so \`nextStep\` never becomes \`continue\` for a
538
+ payment a person had to approve. \`intents continue\` refuses it with
539
+ \`movement_admin_completes_payment\`, and sending the same request again on the
540
+ same idempotency key hands back the payment's intent, or tells you to read it —
541
+ never a signature. All of these are answers, not failures: report the refusal
542
+ and keep polling.
543
+
544
+ Note that \`status\` alone cannot tell you where the payment is: a payment
545
+ waiting on a person and one an admin is finishing both read \`processing\`.
546
+ Use \`.movement.nextStep\`.
547
+
548
+ An approval does not wait forever. If nobody finishes the payment before it
549
+ lapses, it expires unpaid and has to be asked for again.
550
+
483
551
  ## Paying x402 (HTTP 402) Endpoints
484
552
 
485
553
  \`x402\` fetches a URL. If the server answers 402 with an x402 v2 challenge, the
@@ -599,8 +667,8 @@ a larger challenge before it makes an intent.
599
667
 
600
668
  An MPP payment uses the same send capability, counterparty allowlist, spend
601
669
  limits, and operator approval flow as every other agent payment. The recipient
602
- of the challenge must be a saved counterparty wallet rail on the network that
603
- the challenge asks for.
670
+ of the challenge must be a saved counterparty wallet rail in the challenge
671
+ network's class; the challenge itself determines the settlement network.
604
672
 
605
673
  Three fields tell you what to do next:
606
674
 
@@ -720,6 +788,10 @@ the result carries \`.error\`, and they still print their JSON on stdout. That
720
788
  outcome needs an action from you. Read \`.error\`. Do not treat the exit code as
721
789
  a simple failure.
722
790
 
791
+ Request validation errors identify the affected fields and explain the rules in
792
+ the message on stderr, so you can correct the inputs without inspecting the HTTP
793
+ response.
794
+
723
795
  ## Persisting Across Sessions
724
796
 
725
797
  Only an agent that already knows about the CLI finds this guide. The Catena
@@ -740,14 +812,14 @@ need, or if it cannot express your operation:
740
812
 
741
813
  The message must have 1 to 4000 characters. You cannot read it again after you
742
814
  send it. Give a longer message on stdin instead of as an argument.
743
- `}const Qu=c({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(Zu(oe))}}),$u=Q({id:Os({description:`Intent id (e.g. int_…)`,required:!0,schema:Ws}),profile:Vs,json:Hs}),ed=c({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:$u.args,async run({args:e}){let t=$u.parse(e);await $(t)(e=>e.getIntent(t.id))}}),td=Q({id:Os({description:`Intent id of a send that crossed chains (e.g. int_…)`,required:!0,schema:Ws}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same continuation; omitted generates a fresh key for this invocation.`,schema:Su}),profile:Vs,json:Hs}),nd=c({meta:{name:`continue`,description:"Sign the second leg of a send that crossed chains, once `intents get` shows crossChain.nextStep = continue"},args:td.args,async run({args:e}){let t=td.parse(e);await $(t)(e=>e.continueIntent({intentId:t.id,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),rd=c({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:ed,continue:nd}});function id(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function ad(e){let t;try{t=E(ne(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??ee());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function od(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function sd(e){process.platform===`darwin`?v(`open`,[e],od):process.platform===`win32`?v(`cmd`,[`/c`,`start`,``,e],od):v(`xdg-open`,[e],od)}function cd(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.message==`string`?t.message:typeof t.error==`string`?t.error:void 0}function ld(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function ud(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.sessionToken==`string`&&(t.activated===void 0||typeof t.activated==`boolean`)}function dd(e){if(typeof e!=`object`||!e)return!1;let t=e;return uc.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function fd(e){let{apiUrl:t,authCode:n,verifier:r,redirectUri:i,agentId:a,clientInstanceId:o,clientId:s,clientLabel:c,log:l=()=>{},appInfo:u,existingSigner:d,generateSignerKeypair:f=ga}=e,p=Ql(u);l(`Exchanging authorization code...`);let m=await fetch(`${t}/v1/auth/oauth2/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,...p},body:new URLSearchParams({grant_type:`authorization_code`,code:n,code_verifier:r,client_id:s,redirect_uri:i}).toString()});if(!m.ok)return{ok:!1,message:cd(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!ld(h))return{ok:!1,message:`Token exchange response missing access_token`};l(`Claiming agent...`);let g=d?{algorithm:d.algorithm,privateKeyHex:d.privateKeyHex,publicKeyHex:d.publicKeyHex}:f(),_=await fetch(`${t}/v1/agent-api/claim`,{method:`POST`,headers:{"Content-Type":`application/json`,...p,Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({agentId:a,clientInstanceId:o,...c===void 0?{}:{clientLabel:c}})});if(!_.ok)return{ok:!1,message:cd(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return ud(v)?pd({apiUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function pd(e){let{apiUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await hd({apiUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await gd({apiUrl:t,sessionToken:n.sessionToken,identityHeaders:a}),o.reason===`public_key_conflict`?{ok:!1,message:`This device's signing key conflicts with the one Catena already holds for this agent, or that key is already registered to another agent. Re-running link will not fix this; this agent's signing key cannot be reset automatically, so ask an operator or support to reset it before linking again.`}:{ok:!1,message:`Signer registration failed (${o.reason??`unknown`}). Run link again to retry.`}):{ok:!0,result:{agentId:n.agentId,clientInstanceId:r,agentName:n.name,signer:{...i,registration:o}}}}function md(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:dd(e.signer)}async function hd(e){let t;try{t=await fetch(`${e.apiUrl}/v1/agent-api/signer/register`,{method:`POST`,headers:{"Content-Type":`application/json`,...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({signer:{algorithm:e.keypair.algorithm,publicKeyHex:e.keypair.publicKeyHex}})})}catch{return{status:`registration_failed`,reason:`registration_request_failed`}}if(t.status===409)return{status:`registration_failed`,reason:`public_key_conflict`};if(!t.ok)return{status:`registration_failed`,reason:`provider_registration_failed`};let n=await t.json().catch(()=>null);return md(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function gd(e){try{await fetch(`${e.apiUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function _d(e){return`${e}-signer`}async function vd(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(_d(t));if(r!==null&&`signer`in r)return r.signer}async function yd(e,t,n=ga){let r=await vd(e,t);if(r!==void 0)return r;let i=wc(n());return await e.save(_d(t),i),i.signer}const bd=[53682,53683,53684,53685,53686,53687];function xd(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=bd.length){n(Error(`No registered loopback callback ports are available`));return}let a=bd[r],o=t=>{if(e.off(`error`,o),t.code===`EADDRINUSE`){r++,i();return}n(t)};e.once(`error`,o),e.listen(a,`127.0.0.1`,()=>{e.off(`error`,o),t(a)})};i()})}async function Sd(e){let{apiUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;$c(t,`apiUrl`);let u=g(32).toString(`base64url`),d=m(`sha256`).update(u).digest(`base64url`),f=g(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},h=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,m)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),m(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=re((e,t)=>{C(e,t).catch(e=>{let n=cd(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:h(n)}),t.end()),s(`Link failed: ${n}`),y(null)})});async function C(e,o){let d=new URL(e.url??`/`,`http://localhost`);if(d.pathname!==`/callback`){o.writeHead(404),o.end(`Not found`);return}let m=d.searchParams.get(`error`);if(m){let e=d.searchParams.get(`error_description`)??m;o.writeHead(302,{Location:h(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:h(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:h(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await fd({apiUrl:t,authCode:_,verifier:u,redirectUri:v,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,log:s,appInfo:c,existingSigner:l});if(!b.ok){o.writeHead(302,{Location:h(b.message)}),o.end(),s(`Link failed: ${b.message}`),y(null);return}o.writeHead(302,{Location:p(b.result.agentId)}),o.end(),y(b.result)}xd(S).then(e=>{g=e;let n=`http://127.0.0.1:${g}/callback`,r=`${t}/v1/auth/oauth2/authorize?`+new URLSearchParams({response_type:`code`,client_id:i,redirect_uri:n,scope:`openid email profile offline_access`,code_challenge:d,code_challenge_method:`S256`,state:f}).toString();s(`Opening browser for authentication...`),sd(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function Cd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.deviceCode==`string`&&typeof t.userCode==`string`&&typeof t.verificationUri==`string`&&typeof t.verificationUriComplete==`string`&&typeof t.expiresIn==`number`&&typeof t.interval==`number`}function wd(e){if(typeof e!=`object`||!e)return{};let t=e;return{code:typeof t.code==`string`?t.code:void 0,message:typeof t.error==`string`?t.error:void 0}}function Td(e){return new Promise(t=>{setTimeout(t,e)})}function Ed(e){let t={clientInstanceId:e.clientInstanceId,...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}};return e.scope===`agent:connect`?{scope:`agent:connect`,...t,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:e.scope===`agent:link`?{scope:`agent:link`,agentId:e.agentId,...t}:{agentId:e.agentId,...t}}async function Dd(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ga,sleep:c=Td}=e;$c(t,`apiUrl`);let l=Ql(a),u=e=>(i(`Link failed: ${e}`),null),d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...l},body:JSON.stringify(Ed(e))})}catch{return u(`Could not reach the Catena API to start the device flow`)}if(!d.ok)return u(wd(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!Cd(f))return u(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Od({apiUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!ud(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await pd({apiUrl:t,claim:m,clientInstanceId:n,signerKeypair:o?{algorithm:o.algorithm,privateKeyHex:o.privateKeyHex,publicKeyHex:o.publicKeyHex}:s(),identityHeaders:l,log:i});return h.ok?h.result:u(h.message)}async function Od(e){let{apiUrl:t,grant:n,identityHeaders:r,sleep:i}=e,a=Date.now()+n.expiresIn*1e3,o=Math.max(n.interval,1)*1e3,s=o;for(;Date.now()+o<=a;){await i(o);let e;try{e=await fetch(`${t}/v1/agent-link/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`,...r},body:JSON.stringify({deviceCode:n.deviceCode})})}catch{s=Math.min(s*2,6e4),o=Math.max(o,s);continue}if(s=o,e.ok){let t=await e.json().catch(()=>null);return t===null?{ok:!1,message:`The Catena API returned an unreadable token response`}:{ok:!0,body:t}}let a=wd(await e.json().catch(()=>null));if(a.code!==`authorization_pending`){if(a.code===`slow_down`){o+=5e3;continue}return a.code===`expired_token`?{ok:!1,message:`The device code expired before approval. Run link again`}:{ok:!1,message:a.message??`The request was denied`}}}return{ok:!1,message:`Timed out waiting for approval`}}function kd(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.signer;return t.credential===`signing_key`&&typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.keyThumbprint==`string`&&typeof t.activated==`boolean`&&typeof n==`object`&&!!n&&typeof n.status==`string`}async function Ad(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=Td}=e;$c(t,`apiUrl`);let s=Ql(a),c=e=>(i(`Link failed: ${e}`),null),l={clientInstanceId:n,signer:{algorithm:`p256`,publicKeyHex:e.publicKeyHex},...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}},u=e.agentId===void 0?{scope:`agent:connect:service`,...l,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:{scope:`agent:link:service`,agentId:e.agentId,...l},d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...s},body:JSON.stringify(u)})}catch{return c(`Could not reach the Catena API to start the device flow`)}if(!d.ok){let e=wd(await d.json().catch(()=>null));return e.code===`validation_failed`?c(`The Catena API rejected the request, which usually means it does not support --service yet. Nothing was created. Upgrade it and retry`):c(e.message??d.statusText)}let f=await d.json();if(!Cd(f))return c(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Od({apiUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?ud(p.body)?c(`This Catena API does not support --service yet: it created a session link for agent ${p.body.agentId}. Unlink it in the console before retrying`):kd(p.body)?(i(`Approved. Signing key registered.`),{agentId:p.body.agentId,agentName:p.body.name,keyThumbprint:p.body.keyThumbprint,activated:p.body.activated,signerStatus:p.body.signer.status,...p.body.signer.reason===void 0?{}:{signerReason:p.body.signer.reason}}):c(`Device token response missing required fields`):c(p.message)}const jd=Q({"agent-id":Os({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:Ws}),"api-url":Z({description:`Catena API URL (defaults to $CATENA_API_URL)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:As({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:As({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the secret key) instead of generating a keypair`}),profile:Vs}),Md=/^0[23][0-9a-f]{64}$/;function Nd(e){let t=Math.round(e.expiresInSeconds/60);console.log(`\n To approve this link, visit: ${e.verificationUri}`),console.log(` and enter the code: ${e.userCode}`),console.log(`\n Or open: ${e.verificationUriComplete}`),console.log(`\n Waiting for approval (expires in ${t} minutes)...`)}function Pd(e){console.log(`
744
- This machine generated a key that the approval may already have registered.`),console.log(`Save both values before you run link again:`),console.log(`\n ${Ll}=${e.privateKeyHex}`),console.log(` Public key: ${e.publicKeyHex}`)}function Fd(e){let t=e.apiUrl===`https://api.catena.com`?``:` --api-url ${e.apiUrl}`;return` catena link --service ${e.agentId} --public-key ${e.publicKeyHex}${t}`}function Id(e){let t=t=>[...t,``,e.retryCommand];switch(e.signerStatus){case`registered`:case`already_registered`:return[];case`not_applicable`:return t([`Wallet sends are not ready yet. Your organization cannot sign`,`transfers until an admin finishes signing setup. Reads and payment`,`requests work now. Run this once that is done:`]);case`registration_failed`:return e.signerReason===`signer_key_conflict`?[`Wallet sends are not ready yet. Another link already uses this`,`signing key. Unlink that service in the Catena console, then run`,`link again.`]:t([`Wallet sends are not ready yet. The signing provider did not`,`register the key. Reads and payment requests work now. Run this`,`once it recovers:`]);default:return t([`Wallet sends are not ready yet. Catena reported "${e.signerReason??e.signerStatus}".`,`Reads and payment requests work now. Check the link in the Catena`,`console, then run this:`])}}function Ld({agentId:e,suggestedAgentName:t,browserRequested:n,isHeadless:r}){return e===void 0?{kind:`device-connect`,deviceTarget:{scope:`agent:connect`,...t===void 0?{}:{suggestedAgentName:t}}}:n?r()?{kind:`device-link`,deviceTarget:{agentId:e},notice:`No browser available — using device code flow.`}:{kind:`pkce-link`,agentId:e}:{kind:`device-link`,deviceTarget:{agentId:e}}}function Rd(e){let t=m(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${jl(e??`agent`).slice(0,47)}-${t}`}function zd(e){try{let t=process.cwd();if(ad(t))return null;let n=Sl(t);return{directory:Cl(t,e),reboundFrom:n!==null&&n!==e?n:null}}catch{return console.error(`Warning: could not bind the current directory to profile "${e}".`),null}}const Bd=c({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:jd.args,async run({args:e}){let t=jd.parse(e),n=t[`api-url`],r=t[`agent-id`],i=t.name;if(t.service){await Vd({apiUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if($c(n,`--api-url`),t[`public-key`]!==void 0)throw Error(`--public-key requires --service`);if(r!==void 0&&i!==void 0)throw Error(`--name can only be used when agent-id is omitted`);let e=Wl({flag:su(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:vl(r,n)),o=a??(r===void 0?Rd(i):jl(r)),s=Dl(o,{api_url:n,agent_id:r})}catch(e){X(e)}console.log(`
745
- Catena — Agent Setup`),console.log(`─`.repeat(25));let c=Yc(),l=await yd(c,s),u={apiUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:Jl,existingSigner:l},d=Ld({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:id});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await Sd({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await Dd({...u,...d.deviceTarget,onUserCode:Nd});f||X(`
746
- Failed to link agent. Run the command again to try again.`),await c.save(s,Ec(f.signer));let p=a??Ml(jl(f.agentName),e=>e!==o&&Tl(e)!==null);try{p===o?hl(p,{api_url:n,agent_id:f.agentId,client_instance_id:s}):Nl({reservationName:o,profileName:p,profile:{api_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){X(e)}console.log(`\n Wrote profile "${p}"`);let m=zd(p);m!==null&&console.log(m.reboundFrom===null?` Bound ${m.directory} to profile "${p}"`:` Rebound ${m.directory} from profile "${m.reboundFrom}" to "${p}"`),console.log(` To pin this identity for an agent host, set ${Vl}=${p}`),zl()&&console.log(` ${Ll} is set and outranks ${Vl}; unset it, or pass --profile ${p}, to use this profile`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Vd(e){try{if($c(e.apiUrl,`--api-url`),e.agentId!==void 0&&e.suggestedAgentName!==void 0)throw Error(`--name can only be used when agent-id is omitted`);if(e.publicKeyHex!==void 0&&!Md.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){X(e)}console.log(`
747
- Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ga():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=ba(n)}catch(e){e instanceof ha||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key: ${r}`),console.log(` Check this matches the key on the approval screen.`);let i=`service-${m(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&Pd({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await Ad({apiUrl:e.apiUrl,clientInstanceId:i,publicKeyHex:n,...e.agentId===void 0?{}:{agentId:e.agentId},...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName},onUserCode:e=>{a=!0,Nd(e)},log:e=>console.log(` ${e}`),appInfo:Jl})}catch(e){o(),X(e)}s||(o(),X(`
748
- Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`Catena registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`));let c=Id({signerStatus:s.signerStatus,signerReason:s.signerReason,retryCommand:Fd({agentId:s.agentId,publicKeyHex:n,apiUrl:e.apiUrl})});console.log(`\nDone. Agent "${s.agentName}" is linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(c.length===0?` Wallet sends: ready`:` Wallet sends: not ready yet`),console.log(`
749
- Set this in the deployment environment:`),console.log(t?`\n ${Ll}=${t.privateKeyHex}`:`\n ${Ll}=<the secret key this deployment already holds>`),e.apiUrl!==`https://api.catena.com`&&console.log(` CATENA_API_URL=${e.apiUrl}`),t&&console.log(`
815
+ `}const sd=c({meta:{name:`guide`,description:`Print the Catena CLI agent operating guide`},run(){console.log(od(oe))}}),cd=Q({id:Ls({description:`Intent id (e.g. int_…)`,required:!0,schema:$s}),profile:Xs,json:Zs}),ld=c({meta:{name:`get`,description:`Look up the current state of an intent created by this agent`},args:cd.args,async run({args:e}){let t=cd.parse(e);await $(t)(e=>e.getIntent(t.id))}}),ud=Q({id:Ls({description:`Intent id of a cross-chain send or approved payment (e.g. int_…)`,required:!0,schema:$s}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same continuation; omitted generates a fresh key for this invocation.`,schema:ju}),profile:Xs,json:Zs}),dd=c({meta:{name:`continue`,description:"Finish the second leg of a send that crossed chains, once `intents get` shows crossChain.nextStep = continue"},args:ud.args,async run({args:e}){let t=ud.parse(e);await $(t)(e=>e.continueIntent({intentId:t.id,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),fd=c({meta:{name:`intents`,description:`Inspect intent receipts returned by governed operations`},subCommands:{get:ld,continue:dd}});function pd(e=process.env,t=process.platform){return!!(e.SSH_CONNECTION||e.SSH_TTY||t===`linux`&&!e.DISPLAY&&!e.WAYLAND_DISPLAY)}function md(e){let t;try{t=E(ne(e))}catch{return!1}if(t===`/`)return!0;try{let e=E(process.env.HOME??ee());return t===e||e.startsWith(`${t}/`)}catch{return!0}}function hd(e){e&&process.stderr.write(`Failed to open browser: ${e.message}\n`)}function gd(e){process.platform===`darwin`?v(`open`,[e],hd):process.platform===`win32`?v(`cmd`,[`/c`,`start`,``,e],hd):v(`xdg-open`,[e],hd)}function _d(e){if(typeof e!=`object`||!e)return;let t=e;return typeof t.message==`string`?t.message:typeof t.error==`string`?t.error:void 0}function vd(e){return typeof e!=`object`||!e||!(`access_token`in e)?!1:typeof e.access_token==`string`}function yd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.sessionToken==`string`&&(t.activated===void 0||typeof t.activated==`boolean`)}function bd(e){if(typeof e!=`object`||!e)return!1;let t=e;return yc.some(e=>e===t.status)&&(t.publicKeyHex===void 0||typeof t.publicKeyHex==`string`)&&(t.reason===void 0||typeof t.reason==`string`)}async function xd(e){let{apiUrl:t,authCode:n,verifier:r,redirectUri:i,agentId:a,clientInstanceId:o,clientId:s,clientLabel:c,log:l=()=>{},appInfo:u,existingSigner:d,generateSignerKeypair:f=ga}=e,p=su(u);l(`Exchanging authorization code...`);let m=await fetch(`${t}/v1/auth/oauth2/token`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,...p},body:new URLSearchParams({grant_type:`authorization_code`,code:n,code_verifier:r,client_id:s,redirect_uri:i}).toString()});if(!m.ok)return{ok:!1,message:_d(await m.json().catch(()=>({message:`Token exchange failed`})))??m.statusText};let h=await m.json();if(!vd(h))return{ok:!1,message:`Token exchange response missing access_token`};l(`Claiming agent...`);let g=d?{algorithm:d.algorithm,privateKeyHex:d.privateKeyHex,publicKeyHex:d.publicKeyHex}:f(),_=await fetch(`${t}/v1/agent-api/claim`,{method:`POST`,headers:{"Content-Type":`application/json`,...p,Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({agentId:a,clientInstanceId:o,...c===void 0?{}:{clientLabel:c}})});if(!_.ok)return{ok:!1,message:_d(await _.json().catch(()=>({message:`Claim failed`})))??_.statusText};let v=await _.json();return yd(v)?Sd({apiUrl:t,claim:v,clientInstanceId:o,signerKeypair:g,identityHeaders:p,log:l}):{ok:!1,message:`Claim response missing required fields`}}async function Sd(e){let{apiUrl:t,claim:n,clientInstanceId:r,signerKeypair:i,identityHeaders:a}=e;(e.log??(()=>{}))(`Registering signer...`);let o=await wd({apiUrl:t,sessionToken:n.sessionToken,keypair:i,identityHeaders:a});return o.status===`registration_failed`?(n.activated!==!1&&await Td({apiUrl:t,sessionToken:n.sessionToken,identityHeaders:a}),o.reason===`public_key_conflict`?{ok:!1,message:`This device's signing key conflicts with the one Catena already holds for this agent, or that key is already registered to another agent. Re-running link will not fix this; this agent's signing key cannot be reset automatically, so ask an operator or support to reset it before linking again.`}:{ok:!1,message:`Signer registration failed (${o.reason??`unknown`}). Run link again to retry.`}):{ok:!0,result:{agentId:n.agentId,clientInstanceId:r,agentName:n.name,signer:{...i,registration:o}}}}function Cd(e){return typeof e!=`object`||!e||!(`signer`in e)?!1:bd(e.signer)}async function wd(e){let t;try{t=await fetch(`${e.apiUrl}/v1/agent-api/signer/register`,{method:`POST`,headers:{"Content-Type":`application/json`,...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`},body:JSON.stringify({signer:{algorithm:e.keypair.algorithm,publicKeyHex:e.keypair.publicKeyHex}})})}catch{return{status:`registration_failed`,reason:`registration_request_failed`}}if(t.status===409)return{status:`registration_failed`,reason:`public_key_conflict`};if(!t.ok)return{status:`registration_failed`,reason:`provider_registration_failed`};let n=await t.json().catch(()=>null);return Cd(n)?n.signer:{status:`registration_failed`,reason:`registration_response_malformed`}}async function Td(e){try{await fetch(`${e.apiUrl}/v1/agent-api/unlink`,{method:`POST`,headers:{...e.identityHeaders,Authorization:`Bearer ${e.sessionToken}`}})}catch{}}function Ed(e){return`${e}-signer`}async function Dd(e,t){let n=await e.resolve(t);if(n!==null&&`signer`in n)return n.signer;let r=await e.resolve(Ed(t));if(r!==null&&`signer`in r)return r.signer}async function Od(e,t,n=ga){let r=await Dd(e,t);if(r!==void 0)return r;let i=Nc(n());return await e.save(Ed(t),i),i.signer}const kd=[53682,53683,53684,53685,53686,53687];function Ad(e){return new Promise((t,n)=>{let r=0,i=()=>{if(r>=kd.length){n(Error(`No registered loopback callback ports are available`));return}let a=kd[r],o=t=>{if(e.off(`error`,o),t.code===`EADDRINUSE`){r++,i();return}n(t)};e.once(`error`,o),e.listen(a,`127.0.0.1`,()=>{e.off(`error`,o),t(a)})};i()})}async function jd(e){let{apiUrl:t,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,timeoutMs:o=3e5,log:s=()=>{},appInfo:c,existingSigner:l}=e;cl(t,`apiUrl`);let u=g(32).toString(`base64url`),d=m(`sha256`).update(u).digest(`base64url`),f=g(16).toString(`hex`),p=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`linked`,e),n.toString()},h=e=>{let n=new URL(`${t}/link-complete`);return n.searchParams.set(`error`,e),n.toString()};return new Promise((e,m)=>{let g=0,_=!1,v=null,y=t=>{_||(_=!0,v&&clearTimeout(v),S.close(),e(t))},b=e=>{_||(_=!0,v&&clearTimeout(v),S.close(),m(e))},x=e=>{s(`Link failed: ${e}`),y(null)},S=re((e,t)=>{C(e,t).catch(e=>{let n=_d(e)??`Unexpected error`;t.headersSent||(t.writeHead(302,{Location:h(n)}),t.end()),s(`Link failed: ${n}`),y(null)})});async function C(e,o){let d=new URL(e.url??`/`,`http://localhost`);if(d.pathname!==`/callback`){o.writeHead(404),o.end(`Not found`);return}let m=d.searchParams.get(`error`);if(m){let e=d.searchParams.get(`error_description`)??m;o.writeHead(302,{Location:h(e)}),o.end(),x(`OAuth error: ${e}`);return}if(d.searchParams.get(`state`)!==f){o.writeHead(302,{Location:h(`State mismatch during OAuth callback`)}),o.end(),x(`State mismatch during OAuth callback`);return}let _=d.searchParams.get(`code`);if(!_){o.writeHead(302,{Location:h(`Missing authorization code`)}),o.end(),x(`Missing authorization code`);return}let v=`http://127.0.0.1:${g}/callback`,b=await xd({apiUrl:t,authCode:_,verifier:u,redirectUri:v,agentId:n,clientInstanceId:r,clientId:i,clientLabel:a,log:s,appInfo:c,existingSigner:l});if(!b.ok){o.writeHead(302,{Location:h(b.message)}),o.end(),s(`Link failed: ${b.message}`),y(null);return}o.writeHead(302,{Location:p(b.result.agentId)}),o.end(),y(b.result)}Ad(S).then(e=>{g=e;let n=`http://127.0.0.1:${g}/callback`,r=`${t}/v1/auth/oauth2/authorize?`+new URLSearchParams({response_type:`code`,client_id:i,redirect_uri:n,scope:`openid email profile offline_access`,code_challenge:d,code_challenge_method:`S256`,state:f}).toString();s(`Opening browser for authentication...`),gd(r),s(`If browser didn't open, visit: ${r}`)}).catch(b),v=setTimeout(()=>{x(`Timed out waiting for authentication`)},o),v.unref()})}function Md(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.deviceCode==`string`&&typeof t.userCode==`string`&&typeof t.verificationUri==`string`&&typeof t.verificationUriComplete==`string`&&typeof t.expiresIn==`number`&&typeof t.interval==`number`}function Nd(e){if(typeof e!=`object`||!e)return{};let t=e;return{code:typeof t.code==`string`?t.code:void 0,message:typeof t.error==`string`?t.error:void 0}}function Pd(e){return new Promise(t=>{setTimeout(t,e)})}function Fd(e){let t={clientInstanceId:e.clientInstanceId,...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}};return e.scope===`agent:connect`?{scope:`agent:connect`,...t,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:e.scope===`agent:link`?{scope:`agent:link`,agentId:e.agentId,...t}:{agentId:e.agentId,...t}}async function Id(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,existingSigner:o,generateSignerKeypair:s=ga,sleep:c=Pd}=e;cl(t,`apiUrl`);let l=su(a),u=e=>(i(`Link failed: ${e}`),null),d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...l},body:JSON.stringify(Fd(e))})}catch{return u(`Could not reach the Catena API to start the device flow`)}if(!d.ok)return u(Nd(await d.json().catch(()=>null)).message??d.statusText);let f=await d.json();if(!Md(f))return u(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Ld({apiUrl:t,grant:f,identityHeaders:l,sleep:c});if(!p.ok)return u(p.message);let m=p.body;if(!yd(m))return u(`Device token response missing required fields`);i(`Approved. Claiming agent...`);let h=await Sd({apiUrl:t,claim:m,clientInstanceId:n,signerKeypair:o?{algorithm:o.algorithm,privateKeyHex:o.privateKeyHex,publicKeyHex:o.publicKeyHex}:s(),identityHeaders:l,log:i});return h.ok?h.result:u(h.message)}async function Ld(e){let{apiUrl:t,grant:n,identityHeaders:r,sleep:i}=e,a=Date.now()+n.expiresIn*1e3,o=Math.max(n.interval,1)*1e3,s=o;for(;Date.now()+o<=a;){await i(o);let e;try{e=await fetch(`${t}/v1/agent-link/device/token`,{method:`POST`,headers:{"Content-Type":`application/json`,...r},body:JSON.stringify({deviceCode:n.deviceCode})})}catch{s=Math.min(s*2,6e4),o=Math.max(o,s);continue}if(s=o,e.ok){let t=await e.json().catch(()=>null);return t===null?{ok:!1,message:`The Catena API returned an unreadable token response`}:{ok:!0,body:t}}let a=Nd(await e.json().catch(()=>null));if(a.code!==`authorization_pending`){if(a.code===`slow_down`){o+=5e3;continue}return a.code===`expired_token`?{ok:!1,message:`The device code expired before approval. Run link again`}:{ok:!1,message:a.message??`The request was denied`}}}return{ok:!1,message:`Timed out waiting for approval`}}function Rd(e){if(typeof e!=`object`||!e)return!1;let t=e,n=t.signer;return t.credential===`signing_key`&&typeof t.agentId==`string`&&typeof t.name==`string`&&typeof t.keyThumbprint==`string`&&typeof t.activated==`boolean`&&typeof n==`object`&&!!n&&typeof n.status==`string`}async function zd(e){let{apiUrl:t,clientInstanceId:n,onUserCode:r,log:i=()=>{},appInfo:a,sleep:o=Pd}=e;cl(t,`apiUrl`);let s=su(a),c=e=>(i(`Link failed: ${e}`),null),l={clientInstanceId:n,signer:{algorithm:`p256`,publicKeyHex:e.publicKeyHex},...e.clientLabel===void 0?{}:{clientLabel:e.clientLabel}},u=e.agentId===void 0?{scope:`agent:connect:service`,...l,...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName}}:{scope:`agent:link:service`,agentId:e.agentId,...l},d;try{d=await fetch(`${t}/v1/agent-link/device/code`,{method:`POST`,headers:{"Content-Type":`application/json`,...s},body:JSON.stringify(u)})}catch{return c(`Could not reach the Catena API to start the device flow`)}if(!d.ok){let e=Nd(await d.json().catch(()=>null));return e.code===`validation_failed`?c(`The Catena API rejected the request, which usually means it does not support --service yet. Nothing was created. Upgrade it and retry`):c(e.message??d.statusText)}let f=await d.json();if(!Md(f))return c(`Device authorization response missing required fields`);r({userCode:f.userCode,verificationUri:f.verificationUri,verificationUriComplete:f.verificationUriComplete,expiresInSeconds:f.expiresIn});let p=await Ld({apiUrl:t,grant:f,identityHeaders:s,sleep:o});return p.ok?yd(p.body)?c(`This Catena API does not support --service yet: it created a session link for agent ${p.body.agentId}. Unlink it in the console before retrying`):Rd(p.body)?(i(`Approved. Signing key registered.`),{agentId:p.body.agentId,agentName:p.body.name,keyThumbprint:p.body.keyThumbprint,activated:p.body.activated,signerStatus:p.body.signer.status,...p.body.signer.reason===void 0?{}:{signerReason:p.body.signer.reason}}):c(`Device token response missing required fields`):c(p.message)}const Bd=Q({"agent-id":Ls({description:`Optional agent ID shown in the Catena console; omit to create and link a new agent`,schema:$s}),"api-url":Z({description:`Catena API URL (defaults to $CATENA_API_URL)`,default:process.env.CATENA_API_URL??`https://api.catena.com`}),browser:zs({description:`Open the browser PKCE flow (default)`,negativeDescription:`Skip the browser and link with a device code you approve from another machine`,default:!0}),name:Z({description:`Suggested name for an agent created from this link; only used when agent-id is omitted`}),service:zs({description:`Provision a deployed-service signing credential instead of linking this machine: approval registers a P-256 key, no session tokens are minted, and nothing is stored locally. Interactive agent hosts must NOT use this`,default:!1}),"public-key":Z({description:`With --service: register this existing compressed P-256 public key (the deployment already holds the secret key) instead of generating a keypair`}),profile:Xs}),Vd=/^0[23][0-9a-f]{64}$/;function Hd(e){let t=Math.round(e.expiresInSeconds/60);console.log(`\n To approve this link, visit: ${e.verificationUri}`),console.log(` and enter the code: ${e.userCode}`),console.log(`\n Or open: ${e.verificationUriComplete}`),console.log(`\n Waiting for approval (expires in ${t} minutes)...`)}function Ud(e){console.log(`
816
+ This machine generated a key that the approval may already have registered.`),console.log(`Save both values before you run link again:`),console.log(`\n ${Kl}=${e.privateKeyHex}`),console.log(` Public key: ${e.publicKeyHex}`)}function Wd(e){let t=e.apiUrl===`https://api.catena.com`?``:` --api-url ${e.apiUrl}`;return` catena link --service ${e.agentId} --public-key ${e.publicKeyHex}${t}`}function Gd(e){let t=t=>[...t,``,e.retryCommand];switch(e.signerStatus){case`registered`:case`already_registered`:return[];case`not_applicable`:return t([`Wallet sends are not ready yet. Your organization cannot sign`,`transfers until an admin finishes signing setup. Reads and payment`,`requests work now. Run this once that is done:`]);case`registration_failed`:return e.signerReason===`signer_key_conflict`?[`Wallet sends are not ready yet. Another link already uses this`,`signing key. Unlink that service in the Catena console, then run`,`link again.`]:t([`Wallet sends are not ready yet. The signing provider did not`,`register the key. Reads and payment requests work now. Run this`,`once it recovers:`]);default:return t([`Wallet sends are not ready yet. Catena reported "${e.signerReason??e.signerStatus}".`,`Reads and payment requests work now. Check the link in the Catena`,`console, then run this:`])}}function Kd({agentId:e,suggestedAgentName:t,browserRequested:n,isHeadless:r}){return e===void 0?{kind:`device-connect`,deviceTarget:{scope:`agent:connect`,...t===void 0?{}:{suggestedAgentName:t}}}:n?r()?{kind:`device-link`,deviceTarget:{agentId:e},notice:`No browser available — using device code flow.`}:{kind:`pkce-link`,agentId:e}:{kind:`device-link`,deviceTarget:{agentId:e}}}function qd(e){let t=m(`sha256`).update(E(process.cwd())).digest(`hex`).slice(0,16);return`${Bl(e??`agent`).slice(0,47)}-${t}`}function Jd(e){try{let t=process.cwd();if(md(t))return null;let n=jl(t);return{directory:Ml(t,e),reboundFrom:n!==null&&n!==e?n:null}}catch{return console.error(`Warning: could not bind the current directory to profile "${e}".`),null}}const Yd=c({meta:{name:`link`,description:`Link an existing agent, or create and link a new agent when agent-id is omitted`},args:Bd.args,async run({args:e}){let t=Bd.parse(e),n=t[`api-url`],r=t[`agent-id`],i=t.name;if(t.service){await Xd({apiUrl:n,agentId:r,suggestedAgentName:i,publicKeyHex:t[`public-key`]});return}let a,o,s;try{if(cl(n,`--api-url`),t[`public-key`]!==void 0)throw Error(`--public-key requires --service`);if(r!==void 0&&i!==void 0)throw Error(`--name can only be used when agent-id is omitted`);let e=$l({flag:gu(t),cwd:process.cwd(),log:e=>console.error(e)});a=(e!==null&&e.source!=="default"?e.name:null)??(r===void 0?null:Dl(r,n)),o=a??(r===void 0?qd(i):Bl(r)),s=Il(o,{api_url:n,agent_id:r})}catch(e){X(e)}console.log(`
817
+ Catena — Agent Setup`),console.log(`─`.repeat(25));let c=il(),l=await Od(c,s),u={apiUrl:n,clientInstanceId:s,log:e=>console.log(` ${e}`),appInfo:ru,existingSigner:l},d=Kd({agentId:r,suggestedAgentName:i,browserRequested:t.browser,isHeadless:pd});d.kind===`device-link`&&d.notice!==void 0&&console.log(` ${d.notice}`);let f=d.kind===`pkce-link`?await jd({...u,agentId:d.agentId,clientId:`catena-cli`,timeoutMs:3e5}):await Id({...u,...d.deviceTarget,onUserCode:Hd});f||X(`
818
+ Failed to link agent. Run the command again to try again.`),await c.save(s,Fc(f.signer));let p=a??Vl(Bl(f.agentName),e=>e!==o&&Pl(e)!==null);try{p===o?wl(p,{api_url:n,agent_id:f.agentId,client_instance_id:s}):Hl({reservationName:o,profileName:p,profile:{api_url:n,agent_id:f.agentId,client_instance_id:s}})}catch(e){X(e)}console.log(`\n Wrote profile "${p}"`);let m=Jd(p);m!==null&&console.log(m.reboundFrom===null?` Bound ${m.directory} to profile "${p}"`:` Rebound ${m.directory} from profile "${m.reboundFrom}" to "${p}"`),console.log(` To pin this identity for an agent host, set ${Xl}=${p}`),Jl()&&console.log(` ${Kl} is set and outranks ${Xl}; unset it, or pass --profile ${p}, to use this profile`),console.log(`\nDone. Agent "${f.agentName}" linked.`),process.exit(0)}});async function Xd(e){try{if(cl(e.apiUrl,`--api-url`),e.agentId!==void 0&&e.suggestedAgentName!==void 0)throw Error(`--name can only be used when agent-id is omitted`);if(e.publicKeyHex!==void 0&&!Vd.test(e.publicKeyHex.toLowerCase()))throw Error(`--public-key must be compressed P-256 public key hex (66 chars)`)}catch(e){X(e)}console.log(`
819
+ Catena — Deployed Service Setup`),console.log(`─`.repeat(31));let t=e.publicKeyHex===void 0?ga():null,n=t?.publicKeyHex??e.publicKeyHex?.toLowerCase()??``,r;try{r=ba(n)}catch(e){e instanceof ha||X(e),X(`Signing key public key is not a valid P-256 point`)}console.log(` Signing key: ${r}`),console.log(` Check this matches the key on the approval screen.`);let i=`service-${m(`sha256`).update(n).digest(`hex`).slice(0,32)}`,a=!1,o=()=>{t&&a&&Ud({publicKeyHex:n,privateKeyHex:t.privateKeyHex})},s;try{s=await zd({apiUrl:e.apiUrl,clientInstanceId:i,publicKeyHex:n,...e.agentId===void 0?{}:{agentId:e.agentId},...e.suggestedAgentName===void 0?{}:{suggestedAgentName:e.suggestedAgentName},onUserCode:e=>{a=!0,Hd(e)},log:e=>console.log(` ${e}`),appInfo:ru})}catch(e){o(),X(e)}s||(o(),X(`
820
+ Failed to link the service. Run the command again to try again.`)),s.keyThumbprint!==r&&(o(),X(`Catena registered signing key thumbprint ${s.keyThumbprint}, which does not match the local key (${r}). Do not deploy this credential. Unlink the agent in the console and run link again`));let c=Gd({signerStatus:s.signerStatus,signerReason:s.signerReason,retryCommand:Wd({agentId:s.agentId,publicKeyHex:n,apiUrl:e.apiUrl})});console.log(`\nDone. Agent "${s.agentName}" is linked as a deployed service.`),console.log(` Agent ID: ${s.agentId}`),console.log(c.length===0?` Wallet sends: ready`:` Wallet sends: not ready yet`),console.log(`
821
+ Set this in the deployment environment:`),console.log(t?`\n ${Kl}=${t.privateKeyHex}`:`\n ${Kl}=<the secret key this deployment already holds>`),e.apiUrl!==`https://api.catena.com`&&console.log(` CATENA_API_URL=${e.apiUrl}`),t&&console.log(`
750
822
  Save the secret key now. It is shown once and is not stored on this machine.`),c.length>0&&console.log(`\n${c.join(`
751
823
  `)}`),process.exit(0)}
752
824
  /*! decimal.js-light v2.5.1 https://github.com/MikeMcl/decimal.js-light/LICENCE */
753
- const Hd=e(i(((e,t)=>{(function(e){var n=1e9,r={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:`2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286`},i=!0,a=`[DecimalError] `,o=a+`Invalid argument: `,s=a+`Exponent out of range: `,c=Math.floor,l=Math.pow,u=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d,f=1e7,p=7,m=9007199254740991,h=c(m/p),g={};g.absoluteValue=g.abs=function(){var e=new this.constructor(this);return e.s&&=1,e},g.comparedTo=g.cmp=function(e){var t,n,r,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(r=a.d.length,i=e.d.length,t=0,n=r<i?r:i;t<n;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return r===i?0:r>i^a.s<0?1:-1},g.decimalPlaces=g.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*p;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n},g.dividedBy=g.div=function(e){return b(this,new this.constructor(e))},g.dividedToIntegerBy=g.idiv=function(e){var t=this,n=t.constructor;return D(b(t,new n(e),0,1),n.precision)},g.equals=g.eq=function(e){return!this.cmp(e)},g.exponent=function(){return S(this)},g.greaterThan=g.gt=function(e){return this.cmp(e)>0},g.greaterThanOrEqualTo=g.gte=function(e){return this.cmp(e)>=0},g.isInteger=g.isint=function(){return this.e>this.d.length-2},g.isNegative=g.isneg=function(){return this.s<0},g.isPositive=g.ispos=function(){return this.s>0},g.isZero=function(){return this.s===0},g.lessThan=g.lt=function(e){return this.cmp(e)<0},g.lessThanOrEqualTo=g.lte=function(e){return this.cmp(e)<1},g.logarithm=g.log=function(e){var t,n=this,r=n.constructor,o=r.precision,s=o+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(d))throw Error(a+`NaN`);if(n.s<1)throw Error(a+(n.s?`NaN`:`-Infinity`));return n.eq(d)?new r(0):(i=!1,t=b(T(n,s),T(e,s),s),i=!0,D(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?O(t,e):_(t,(e.s=-e.s,e))},g.modulo=g.mod=function(e){var t,n=this,r=n.constructor,o=r.precision;if(e=new r(e),!e.s)throw Error(a+`NaN`);return n.s?(i=!1,t=b(n,e,0,1).times(e),i=!0,n.minus(t)):D(new r(n),o)},g.naturalExponential=g.exp=function(){return x(this)},g.naturalLogarithm=g.ln=function(){return T(this)},g.negated=g.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e},g.plus=g.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?_(t,e):O(t,(e.s=-e.s,e))},g.precision=g.sd=function(e){var t,n,r,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(o+e);if(t=S(i)+1,r=i.d.length-1,n=r*p+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return e&&t>n?t:n},g.squareRoot=g.sqrt=function(){var e,t,n,r,o,s,l,u=this,d=u.constructor;if(u.s<1){if(!u.s)return new d(0);throw Error(a+`NaN`)}for(e=S(u),i=!1,o=Math.sqrt(+u),o==0||o==1/0?(t=y(u.d),(t.length+e)%2==0&&(t+=`0`),o=Math.sqrt(t),e=c((e+1)/2)-(e<0||e%2),o==1/0?t=`5e`+e:(t=o.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+e),r=new d(t)):r=new d(o.toString()),n=d.precision,o=l=n+3;;)if(s=r,r=s.plus(b(u,s,l+2)).times(.5),y(s.d).slice(0,l)===(t=y(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),o==l&&t==`4999`){if(D(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,D(r,n)},g.times=g.mul=function(e){var t,n,r,a,o,s,c,l,u,d=this,p=d.constructor,m=d.d,h=(e=new p(e)).d;if(!d.s||!e.s)return new p(0);for(e.s*=d.s,n=d.e+e.e,l=m.length,u=h.length,l<u&&(o=m,m=h,h=o,s=l,l=u,u=s),o=[],s=l+u,r=s;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)c=o[a]+h[r]*m[a-r-1]+t,o[a--]=c%f|0,t=c/f|0;o[a]=(o[a]+t)%f|0}for(;!o[--s];)o.pop();return t?++n:o.shift(),e.d=o,e.e=n,i?D(e,p.precision):e},g.toDecimalPlaces=g.todp=function(e,t){var r=this,i=r.constructor;return r=new i(r),e===void 0?r:(v(e,0,n),t===void 0?t=i.rounding:v(t,0,8),D(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=k(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=D(new a(i),e+1,t),r=k(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?k(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=D(new o(a),e+S(a)+1,t),r=k(i.abs(),!1,e+S(i)+1),a.isneg()&&!a.isZero()?`-`+r:r)},g.toInteger=g.toint=function(){var e=this,t=e.constructor;return D(new t(e),S(e)+1,t.rounding)},g.toNumber=function(){return+this},g.toPower=g.pow=function(e){var t,n,r,o,s,l,u=this,f=u.constructor,h=12,g=+(e=new f(e));if(!e.s)return new f(d);if(u=new f(u),!u.s){if(e.s<1)throw Error(a+`Infinity`);return u}if(u.eq(d))return u;if(r=f.precision,e.eq(d))return D(u,r);if(t=e.e,n=e.d.length-1,l=t>=n,s=u.s,!l){if(s<0)throw Error(a+`NaN`)}else if((n=g<0?-g:g)<=m){for(o=new f(d),t=Math.ceil(r/p+4),i=!1;n%2&&(o=o.times(u),A(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),A(u.d,t);return i=!0,e.s<0?new f(d).div(o):D(o,r)}return s=s<0&&e.d[Math.max(t,n)]&1?-1:1,u.s=1,i=!1,o=e.times(T(u,r+h)),i=!0,o=x(o),o.s=s,o},g.toPrecision=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?(r=S(a),i=k(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=D(new o(a),e,t),r=S(a),i=k(a,e<=r||r<=o.toExpNeg,e)),i},g.toSignificantDigits=g.tosd=function(e,t){var r=this,i=r.constructor;return e===void 0?(e=i.precision,t=i.rounding):(v(e,1,n),t===void 0?t=i.rounding:v(t,0,8)),D(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return k(e,t<=n.toExpNeg||t>=n.toExpPos)};function _(e,t){var n,r,a,o,s,c,l,u,d=e.constructor,m=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),i?D(t,m):t;if(l=e.d,u=t.d,s=e.e,a=t.e,l=l.slice(),o=s-a,o){for(o<0?(r=l,o=-o,c=u.length):(r=u,a=s,c=l.length),s=Math.ceil(m/p),c=s>c?s+1:c+1,o>c&&(o=c,r.length=1),r.reverse();o--;)r.push(0);r.reverse()}for(c=l.length,o=u.length,c-o<0&&(o=c,r=u,u=l,l=r),n=0;o;)n=(l[--o]=l[o]+u[o]+n)/f|0,l[o]%=f;for(n&&(l.unshift(n),++a),c=l.length;l[--c]==0;)l.pop();return t.d=l,t.e=a,i?D(t,m):t}function v(e,t,n){if(e!==~~e||e<t||e>n)throw Error(o+e)}function y(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=p-r.length,n&&(a+=w(n)),a+=r;o=e[t],r=o+``,n=p-r.length,n&&(a+=w(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}var b=(function(){function e(e,t){var n,r=0,i=e.length;for(e=e.slice();i--;)n=e[i]*t+r,e[i]=n%f|0,r=n/f|0;return r&&e.unshift(r),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n){for(var r=0;n--;)e[n]-=r,r=+(e[n]<t[n]),e[n]=r*f+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,o,s){var c,l,u,d,m,h,g,_,v,y,b,x,C,w,T,E,O,k,A=r.constructor,ee=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new A(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,O=M.length,T=j.length,g=new A(ee),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=A.precision:s?o+(S(r)-S(i))+1:o,x<0)return new A(0);if(x=x/p+2|0,u=0,O==1)for(d=0,M=M[0],x++;(u<T||d)&&x--;u++)C=d*f+(j[u]||0),_[u]=C/M|0,d=C%M|0;else{for(d=f/(M[0]+1)|0,d>1&&(M=e(M,d),j=e(j,d),O=M.length,T=j.length),w=O,v=j.slice(0,O),y=v.length;y<O;)v[y++]=0;k=M.slice(),k.unshift(0),E=M[0],M[1]>=f/2&&++E;do d=0,c=t(M,v,O,y),c<0?(b=v[0],O!=y&&(b=b*f+(v[1]||0)),d=b/E|0,d>1?(d>=f&&(d=f-1),m=e(M,d),h=m.length,y=v.length,c=t(m,v,h,y),c==1&&(d--,n(m,O<h?k:M,h))):(d==0&&(c=d=1),m=M.slice()),h=m.length,h<y&&m.unshift(0),n(v,m,y),c==-1&&(y=v.length,c=t(M,v,O,y),c<1&&(d++,n(v,O<y?k:M,y))),y=v.length):c===0&&(d++,v=[0]),_[u++]=d,c&&v[0]?v[y++]=j[w]||0:(v=[j[w]],y=1);while((w++<T||v[0]!==void 0)&&x--)}return _[0]||_.shift(),g.e=l,D(g,s?o+S(g)+1:o)}})();function x(e,t){var n,r,a,o,c,u,f=0,p=0,m=e.constructor,h=m.precision;if(S(e)>16)throw Error(s+S(e));if(!e.s)return new m(d);for(t==null?(i=!1,u=h):u=t,c=new m(.03125);e.abs().gte(.1);)e=e.times(c),p+=5;for(r=Math.log(l(2,p))/Math.LN10*2+5|0,u+=r,n=a=o=new m(d),m.precision=u;;){if(a=D(a.times(e),u),n=n.times(++f),c=o.plus(b(a,n,u)),y(c.d).slice(0,u)===y(o.d).slice(0,u)){for(;p--;)o=D(o.times(o),u);return m.precision=h,t==null?(i=!0,D(o,h)):o}o=c}}function S(e){for(var t=e.e*p,n=e.d[0];n>=10;n/=10)t++;return t}function C(e,t,n){if(t>e.LN10.sd())throw i=!0,n&&(e.precision=n),Error(a+`LN10 precision limit exceeded`);return D(new e(e.LN10),t)}function w(e){for(var t=``;e--;)t+=`0`;return t}function T(e,t){var n,r,o,s,c,l,u,f,p,m=1,h=10,g=e,_=g.d,v=g.constructor,x=v.precision;if(g.s<1)throw Error(a+(g.s?`NaN`:`-Infinity`));if(g.eq(d))return new v(0);if(t==null?(i=!1,f=x):f=t,g.eq(10))return t??(i=!0),C(v,f);if(f+=h,v.precision=f,n=y(_),r=n.charAt(0),s=S(g),Math.abs(s)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=y(g.d),r=n.charAt(0),m++;s=S(g),r>1?(g=new v(`0.`+n),s++):g=new v(r+`.`+n.slice(1))}else return u=C(v,f+2,x).times(s+``),g=T(new v(r+`.`+n.slice(1)),f-h).plus(u),v.precision=x,t==null?(i=!0,D(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=D(g.times(g),f),o=3;;){if(c=D(c.times(p),f),u=l.plus(b(c,new v(o),f)),y(u.d).slice(0,f)===y(l.d).slice(0,f))return l=l.times(2),s!==0&&(l=l.plus(C(v,f+2,x).times(s+``))),l=b(l,new v(m),f),v.precision=x,t==null?(i=!0,D(l,x)):l;l=u,o+=2}}function E(e,t){var n,r,a;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=c(n/p),e.d=[],r=(n+1)%p,n<0&&(r+=p),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=p;r<a;)e.d.push(+t.slice(r,r+=p));t=t.slice(r),r=p-t.length}else r-=a;for(;r--;)t+=`0`;if(e.d.push(+t),i&&(e.e>h||e.e<-h))throw Error(s+n)}else e.s=0,e.e=0,e.d=[0];return e}function D(e,t,n){var r,a,o,u,d,m,g,_,v=e.d;for(u=1,o=v[0];o>=10;o/=10)u++;if(r=t-u,r<0)r+=p,a=t,g=v[_=0];else{if(_=Math.ceil((r+1)/p),o=v.length,_>=o)return e;for(g=o=v[_],u=1;o>=10;o/=10)u++;r%=p,a=r-p+u}if(n!==void 0&&(o=l(10,u-a-1),d=g/o%10|0,m=t<0||v[_+1]!==void 0||g%o,m=n<4?(d||m)&&(n==0||n==(e.s<0?3:2)):d>5||d==5&&(n==4||m||n==6&&(r>0?a>0?g/l(10,u-a):0:v[_-1])%10&1||n==(e.s<0?8:7))),t<1||!v[0])return m?(o=S(e),v.length=1,t=t-o-1,v[0]=l(10,(p-t%p)%p),e.e=c(-t/p)||0):(v.length=1,v[0]=e.e=e.s=0),e;if(r==0?(v.length=_,o=1,_--):(v.length=_+1,o=l(10,p-r),v[_]=a>0?(g/l(10,u-a)%l(10,a)|0)*o:0),m)for(;;)if(_==0){(v[0]+=o)==f&&(v[0]=1,++e.e);break}else{if(v[_]+=o,v[_]!=f)break;v[_--]=0,o=1}for(r=v.length;v[--r]===0;)v.pop();if(i&&(e.e>h||e.e<-h))throw Error(s+S(e));return e}function O(e,t){var n,r,a,o,s,c,l,u,d,m,h=e.constructor,g=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),i?D(t,g):t;if(l=e.d,m=t.d,r=t.e,u=e.e,l=l.slice(),s=u-r,s){for(d=s<0,d?(n=l,s=-s,c=m.length):(n=m,r=u,c=l.length),a=Math.max(Math.ceil(g/p),c)+2,s>a&&(s=a,n.length=1),n.reverse(),a=s;a--;)n.push(0);n.reverse()}else{for(a=l.length,c=m.length,d=a<c,d&&(c=a),a=0;a<c;a++)if(l[a]!=m[a]){d=l[a]<m[a];break}s=0}for(d&&(n=l,l=m,m=n,t.s=-t.s),c=l.length,a=m.length-c;a>0;--a)l[c++]=0;for(a=m.length;a>s;){if(l[--a]<m[a]){for(o=a;o&&l[--o]===0;)l[o]=f-1;--l[o],l[a]+=f}l[a]-=m[a]}for(;l[--c]===0;)l.pop();for(;l[0]===0;l.shift())--r;return l[0]?(t.d=l,t.e=r,i?D(t,g):t):new h(0)}function k(e,t,n){var r,i=S(e),a=y(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+w(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(i<0?`e`:`e+`)+i):i<0?(a=`0.`+w(-i-1)+a,n&&(r=n-o)>0&&(a+=w(r))):i>=o?(a+=w(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+w(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=w(r))),e.s<0?`-`+a:a}function A(e,t){if(e.length>t)return e.length=t,!0}function ee(e){var t,n,r;function i(e){var t=this;if(!(t instanceof i))return new i(e);if(t.constructor=i,e instanceof i){t.s=e.s,t.e=e.e,t.d=(e=e.d)?e.slice():e;return}if(typeof e==`number`){if(e*0!=0)throw Error(o+e);if(e>0)t.s=1;else if(e<0)e=-e,t.s=-1;else{t.s=0,t.e=0,t.d=[0];return}if(e===~~e&&e<1e7){t.e=0,t.d=[e];return}return E(t,e.toString())}if(typeof e!=`string`)throw Error(o+e);if(e.charCodeAt(0)===45?(e=e.slice(1),t.s=-1):t.s=1,u.test(e))E(t,e);else throw Error(o+e)}if(i.prototype=g,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=ee,i.config=i.set=j,e===void 0&&(e={}),e)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`LN10`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function j(e){if(!e||typeof e!=`object`)throw Error(a+`Object expected`);var t,r,i,s=[`precision`,1,n,`rounding`,0,8,`toExpNeg`,-1/0,0,`toExpPos`,0,1/0];for(t=0;t<s.length;t+=3)if((i=e[r=s[t]])!==void 0){if(c(i)===i&&i>=s[t+1]&&i<=s[t+2])this[r]=i;else throw Error(o+r+`: `+i)}if((i=e[r=`LN10`])!==void 0){if(i==Math.LN10)this[r]=new this(i);else throw Error(o+r+`: `+i)}return this}r=ee(r),r.default=r.Decimal=r,d=new r(1),typeof define==`function`&&define.amd?define(function(){return r}):t!==void 0&&t.exports?t.exports=r:(e||=typeof self<`u`&&self&&self.self==self?self:Function(`return this`)(),e.Decimal=r)})(e)}))(),1).default;Hd.set({rounding:Hd.ROUND_HALF_EVEN});const Ud=new Map,Wd=/^[A-Z]{3}$/,Gd=/^[A-Z0-9]{2,6}$/;function Kd(e,t,n,r){if(Ud.has(e))throw Error(`duplicate asset id ${e}`);let i=new Hd(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function qd(e,t,n,r,i){if(!Wd.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);Kd(e,n,r,i.dustThreshold);let a=e;return Ud.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function Jd(e,t,n,r,i){if(!Gd.test(e)||Wd.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Ud.get(i.denomination);if(!a||a.kind!==`fiat`)throw Error(`stablecoin denomination must be a registered fiat asset, got ${i.denomination}`);if(n>a.decimals)throw Error(`par stablecoin decimals (${n}) must not exceed its denomination fiat's (${a.decimals})`);Kd(e,n,r,i.dustThreshold);let o=e;return Ud.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}Jd(`USDC`,`USD Coin`,6,2,{denomination:qd(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Hd(1e6),new Hd(1e3);const Yd=d.pipe(d.string(`Amount must be a string`),d.nonEmpty(`Amount must not be empty`),d.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),d.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),d.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),d.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),d.check(e=>{try{return new Hd(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),Xd=d.pipe(d.string(`Count must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),d.transform(Number),d.check(e=>Number.isSafeInteger(e),`Count is too large`),d.check(e=>e>=1,`Count must be at least 1`)),Zd={s:1,m:60,h:3600,d:86400},Qd=d.pipe(d.string(`Duration must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),d.transform(e=>{let t=e.at(-1)??``;return t in Zd?Number(e.slice(0,-1))*Zd[t]:Number(e)}),d.check(e=>e>=60,`Duration must be at least 1 minute`),d.check(e=>e<=604800,`Duration must be at most 7 days`)),$d=Q({profile:Vs,json:Hs}),ef=c({meta:{name:`show`,description:`Show the agent's assigned policy`},args:$d.args,async run({args:e}){await $($d.parse(e))(e=>e.getPolicy())}}),tf=Q({account:Z({description:`Account whose existing hard limit should increase. For a transfer limit, the source account funds move out of.`,required:!0}),capability:js({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:rs,default:`send`}),rule:js({description:`Which limit to adjust`,choices:fo,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:Yd,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:Xd,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:Qd,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Su}),profile:Vs,json:Hs}),nf=c({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:tf.args,async run({args:e}){let t=tf.parse(e),n=$(t),r={type:`policy_override`,operations:[rf(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r,...t.idempotencyKey!==void 0&&{idempotencyKey:t.idempotencyKey}}))}});function rf(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const af=c({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:ef,"request-override":nf}}),of=Q({profile:Os({description:`Profile name`,required:!0})});function sf(){try{return Gl({env:process.env[Vl],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const cf=c({meta:{name:`use`,description:`Set the default credential profile`},args:of.args,async run({args:e}){let t=of.parse(e);try{Al(t.profile),ou({defaultProfile:t.profile})}catch(e){X(e)}}}),lf=c({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e;try{e=Bl()}catch(e){return X(e)}if(e!==null){ou({source:`secret-key`,credential:Ll,apiUrl:e.apiUrl});return}let t=sf(),n;try{n=Tl(t.name)}catch(e){X(e)}n===null&&X(`Profile "${t.name}" is not linked.\nRun 'catena link --profile ${t.name} <agent-id>' to authenticate.`),ou({profile:t.name,source:t.source,apiUrl:n.api_url,agentId:gl(n)?n.agent_id:void 0})}}),uf=c({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=fl()}catch(e){X(e)}let t=zl(),n;try{n=t?null:Gl({env:process.env[Vl],cwd:process.cwd()}).name}catch{n=null}let r=Object.entries(e.directories??{});ou({defaultProfile:e.default_profile,...t?{shadowedBy:Ll}:{},profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({name:e,apiUrl:t.api_url,agentId:gl(t)?t.agent_id:void 0,directories:r.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===n}))})}}),df=Q({profile:Os({description:`Profile name to bind`,required:!0}),path:Os({description:`Directory to bind (defaults to the current directory)`})}),ff=c({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:df.args,async run({args:e}){let t=df.parse(e);try{let e=t.path??process.cwd();if(ad(e))throw Error(`Refusing to bind the home directory or an ancestor of it — that would shadow the default profile for every directory beneath it. Bind a specific agent directory instead.`);let n=Cl(e,t.profile);ou({profile:t.profile,directory:n})}catch(e){X(e)}}}),pf=Q({path:Os({description:`Directory to unbind (defaults to the current directory)`})}),mf=c({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:pf.args,async run({args:e}){let t=pf.parse(e);try{ou(wl(t.path??process.cwd()))}catch(e){X(e)}}}),hf=c({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:cf,current:lf,list:uf,bind:ff,unbind:mf}}),gf=Q({account:Z({description:`Source account id; omit when the policy allows sends from exactly one account`,schema:Ws}),rail:Z({description:`Destination counterparty rail id (cprl_...)`,required:!0,schema:Ws}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Yd,showValueInError:!0}),method:js({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:Eo}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Su}),profile:Vs,json:Hs}),_f=c({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:gf.args,async run({args:e}){let t=gf.parse(e),n=$(t),r={type:`send`,...t.account!==void 0&&{accountId:t.account},counterpartyRailId:t.rail,amount:t.amount,method:t.method,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),vf=Q({from:Z({description:`Source account id`,required:!0,schema:Ws}),to:Z({description:`Destination account id`,required:!0,schema:Ws}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:Yd,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:Su}),profile:Vs,json:Hs}),yf=c({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:vf.args,async run({args:e}){let t=vf.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}});function bf(){return`${Ll} is set, and this command removes only a linked profile. Revoke the key in the Catena console under the agent's Secret keys tab, or pass --profile <name> to target a profile on this machine.`}const xf=Q({profile:Vs,force:As({description:`Remove the profile and its local credentials without contacting the server; use when the credential is missing, revoked, or a link was interrupted`,default:!1}),json:Hs}),Sf=c({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:xf.args,async run({args:e}){let t=xf.parse(e),n=eu();!t.force&&su(t)===void 0&&zl()&&X(bf());let r;try{r=Gl({flag:su(t),env:process.env[Vl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=Tl(r),e===null)throw Error(zl()?`Profile "${r}" not found, and this machine holds no profile to clear. Revoke the key in the Catena console under the agent's Secret keys tab.`:`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(_d(e.client_instance_id)),bl(r)}catch(e){X(e)}ou({success:!0,profile:r,...gl(e)?{agentId:e.agent_id}:{},local:!0},{compact:t.json});return}let i=`To remove only this machine's copy, run 'catena unlink --profile ${r} --force'.`,a=await Fl({profileName:r,fallbackApiUrl:Il},n);a.ok||X(`${a.message} ${i}`);let o=$l(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(_d(a.clientInstanceId)),bl(r)}catch(e){X(`${bs(au(e,r))} ${i}`)}ou({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),Cf=Q({profile:Vs,json:Hs}),wf=c({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:Cf.args,async run({args:e}){await $(Cf.parse(e))(e=>e.whoami())}});function Tf(e){throw Error(`Unhandled case: ${String(e)}`)}const Ef=d.object({requiredRail:Ao});function Df(e,t){let n=d.safeParse(Ef,e);if(n.success&&n.output.requiredRail.walletAddress.toLowerCase()===t.toLowerCase())return n.output.requiredRail}function Of(e,t){return t?.body!==void 0&&t.body!==null&&typeof t.body!=`string`&&!(t.body instanceof URLSearchParams)&&!(t.body instanceof Blob)&&!(t.body instanceof ArrayBuffer)&&!ArrayBuffer.isView(t.body)?!1:typeof Request<`u`&&e instanceof Request?e.body===null&&!e.bodyUsed:!0}function kf(e,t){let n=new Headers(typeof Request<`u`&&e instanceof Request?e.headers:void 0);return new Headers(t?.headers).forEach((e,t)=>{n.set(t,e)}),n}const Af={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`,"eip155:5042":`Arc`};function jf(e){let t=Object.hasOwn(Af,e)?Af[e]:void 0;return t?`${t} (${e})`:e}const Mf=/^0x[0-9a-fA-F]{64}$/;async function Nf(e,t,n,r){try{await e.reportSettlement({intentId:t,txHash:n,...r!==void 0&&{receipt:r}})}catch{return}}const Pf=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Ff=/^0x[0-9a-fA-F]{40}$/,If=d.looseObject({success:d.boolean(),transaction:d.string(),extensions:d.optional(d.unknown())}),Lf=d.looseObject({x402Version:d.literal(2),accepts:d.array(Jo),resource:d.optional(Yo),extensions:d.optional(d.unknown())}),Rf=`x402_network_mismatch`,zf=`x402_counterparty_rail_not_found`,Bf=new Set([`x402_requirement_not_payable`,Rf,zf]);function Vf(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Hf(e){let t=Pf.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=d.safeParse(Lf,Vf(t));return e.success?e.output:void 0}catch{return}}async function Uf(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=d.safeParse(If,Vf(r));if(!i.success||!i.output.success||!Mf.test(i.output.transaction))return;let a=ro(i.output.extensions);await Nf(e,t,i.output.transaction,a)}catch{}}var Wf=class extends Error{reasons;constructor(e,t=[],n={}){super(t.length>0&&(n.appendReasonsToMessage??!0)?`${e}: ${t.join(`; `)}`:e),this.name=`X402PaymentError`,this.reasons=t}},Gf=class extends Wf{accountId;requiredNetworks;constructor(e,t,n=[]){super(`Account ${e} cannot fund this 402 challenge: it must be paid from a wallet account on ${t.map(jf).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},Kf=class extends Wf{payTo;network;requiredRail;serviceName;constructor(e,t,n,r=[],i){super(`This 402 pays ${e} on ${jf(t)}, which is not a saved counterparty wallet rail; add it as a counterparty before paying`,r,{appendReasonsToMessage:!1}),this.name=`X402CounterpartyNotFoundError`,this.payTo=e,this.network=t,this.serviceName=n,this.requiredRail=i}},qf=class extends Wf{intentId;expiresAt;constructor(e,t,n){super(`The payment is awaiting a human approval (intent ${e}); once an operator approves it, retry the request to complete the payment`,t),this.name=`X402ApprovalPendingError`,this.intentId=e,this.expiresAt=n}},Jf=class extends Wf{receipt;constructor(e,t){super(`The payment settled (intent ${e.intentId}) but the post-payment continuation failed; retry the request with the PAYMENT-SIGNATURE header from the receipt (or getIntent("${e.intentId}") data.paymentCredential.value) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function Yf(e,t){try{return await t()}catch(t){throw new Jf(e,t)}}var Xf=class extends Wf{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.paymentCredential.value as the PAYMENT-SIGNATURE header; processing: poll until terminal; pay again only after blocked or failed`),this.name=`X402SubmitInterruptedError`,this.intentId=e,this.requirements=t,this.cause=n}};async function Zf(e,t){let n=t.paymentRequired.accepts.filter(e=>e.scheme===`exact`),r=n.filter(e=>t.maxAtomicAmount===void 0||/^\d+$/.test(e.amount)&&BigInt(e.amount)<=t.maxAtomicAmount).slice(0,5);if(r.length===0)throw new Wf(n.length>0&&t.maxAtomicAmount!==void 0?`Every requirement in the 402 challenge costs more than the caller's maximum amount`:`The 402 challenge offers no exact-scheme requirement Catena can pay`);let i=t.resource??t.paymentRequired.resource,a=[];for(let n of r){let r=await Qf(e,{accountId:t.accountId,requirements:n,resource:i,signedOffer:no(t.paymentRequired.extensions,n)}).catch(e=>{if(e instanceof ds&&e.code!==void 0&&Bf.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===zf),s=a.filter(e=>e.error.code===Rf),c=a.filter(e=>e.error.code!==zf&&e.error.code!==Rf),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Ff.test(e.requirement.payTo));throw u?new Kf(u.requirement.payTo,u.requirement.network,i?.serviceName,l,Df(u.error.details,u.requirement.payTo)):s.length>0&&o.length===0?new Gf(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new Wf(`No requirement in the 402 challenge is payable from this account`,l)}async function Qf(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource},...t.signedOffer!==void 0&&{signedOffer:t.signedOffer}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof gs&&e.outcome===`unknown`?new Xf(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=Vo(n.data);if(e!==void 0)return{intentId:n.id,paymentSignature:e,requirements:t.requirements};throw new Wf(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new qf(n.id,n.reasons,n.expiresAt);case`processing`:throw new Wf(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new Wf(`Catena declined the payment`,n.reasons)}return Tf(n.status)}function $f(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis);return async(r,i)=>{let a=await n(r,i);if(a.status!==402)return a;let o=Hf(a);if(!o)return a;if(!Of(r,i))throw new Wf(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await Zf(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await Yf(s,()=>t.onPayment?.(s));let c=kf(r,i);c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await Yf(s,()=>n(r,{...i,headers:c}));return Uf(e,s.intentId,l),l}}function ep(e){if(e===`@-`)return tp(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):tp(t,`@${t}`)}return e}function tp(e,t){try{return T(e,`utf8`)}catch(e){return X(`--data ${t}: ${bs(e)}`)}}function np(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}const rp=d.pipe(d.string(),d.check(e=>Yl.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),d.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),d.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function ip(e,t){return e.some(e=>e.name.toLowerCase()===t)}function ap(e,t){ip(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function op(e,t,n){let r=[...n!==void 0&&!ip(e,`content-type`)?[[`content-type`,t??`application/json`]]:[],...e.map(e=>[e.name,e.value])];return r.length>0?new Headers(r):void 0}const sp={"eip155:8453":`base`,"eip155:84532":`base-sepolia`,"eip155:5042":`arc`};function cp(e){return Object.hasOwn(sp,e)?sp[e]:void 0}function lp(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function up(e){return e===void 0?``:` --profile ${lp(e)}`}function dp(e,t){return`Payment submission could not be confirmed (intent ${e}). It may have succeeded. Before paying again, run \`catena intents get ${e}${up(t)}\`.`}function fp(e,t,n,r){let i=/^[a-z0-9][a-z0-9-]*$/.test(t)?t:lp(t);return`catena counterparties create wallet --name ${lp(n??`<name>`)} --address ${lp(e)} --network ${i}${up(r)}`}function pp(e,t){try{w(e,{recursive:!0,mode:448}),x(e,448);let n=te(e,t);return w(n,{recursive:!0,mode:448}),x(n,448),n}catch{return}}const mp=4e3;function hp(e){try{return k(e)}catch{return}}function gp(e,t,n){try{b(e,t)}catch{X(n)}}function _p(e){let t=ne(e),n=j(t),r=hp(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=hp(t);return i===void 0?(gp(n,S.W_OK|S.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),gp(t,S.W_OK,`--output ${e}: destination is not writable`),t)}const vp=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function yp(e){if(e!==void 0&&Us.test(e)&&!vp.test(e))return`${e}.body`;let t=`${Date.now()}-${g(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function bp(e,t){let n=pp(ol(),`responses`);if(n===void 0)return;let r=te(n,yp(t));try{return A(r,e,{mode:384}),r}catch{return}}function xp(e){let t=e.subarray(0,mp*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=mp&&ie(e)}}function Sp({decoded:e,complete:t}){let n=e.slice(0,mp),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function Cp(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...Sp(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ie(e)){let t=e.toString(`utf8`);if(6*t.length+2<=N.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function wp(e){return e.error===void 0?e.bodyEncoding===void 0?`the full body is inlined in the result's .body field`:`the full body is inlined base64-encoded in the result's .body field`:e.error}function Tp(e,t,n){let r=bp(e,t);return r===void 0?Cp(e,n):{...Sp(n),bodyPath:r}}function Ep(e,t,n){let r=xp(e);if(n===void 0)return r.complete?{body:r.decoded}:Tp(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Tp(e,t,r),o=`--output ${n}: ${bs(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${wp(a)}`}}return{...Sp(r),bodyPath:n}}function Dp(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}function Op(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function kp(e,t){ip(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),ap(e,t)}const Ap=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:d.pipe(d.string(),d.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:Ws}),maxAmount:Z({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/))}),method:js({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:ks({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:rp}),profile:Vs,json:Hs}),jp=c({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:Ap.args,async run({args:e,rawArgs:t}){let n=Ap.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),kp(n.header,n.contentType);let i=n.output===void 0?void 0:_p(n.output),a=n.data===void 0?void 0:ep(n.data),o=op(n.header,n.contentType,a);await $(n)(async e=>{let t,s=$f(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:np(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof Xf)throw Error(dp(e.intentId,n.profile),{cause:e});if(e instanceof Jf)return{status:null,paid:!0,retryFailed:!0,payment:Dp(e.receipt),error:e.message};if(e instanceof Gf){let t=e.requiredNetworks.map(e=>cp(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${up(n.profile)}\`).`}}if(e instanceof Kf){let t=Op(e.serviceName),r=e.requiredRail?.network??cp(e.network)??e.network,i=t!==void 0&&t.length<=40?t:void 0,a=fp(e.payTo,r,i,n.profile),o=t===void 0?``:` The endpoint calls itself "${t.length>40?`${t.slice(0,40)}…`:t}" (unverified) — rename it if that is not a service you recognize.`;return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{payTo:e.payTo,network:r,networkId:e.network,...e.requiredRail!==void 0&&{requiredRail:e.requiredRail},createCommand:a,nameIsPlaceholder:i===void 0,...t!==void 0&&{serviceName:t}},error:`${e.message}. Add it, then re-run:\n ${a}\n(counterparty creation may require approval per your policy)${o}`}}if(e instanceof qf)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:Dp(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment settled — re-read the PAYMENT-SIGNATURE with \`catena intents get ${t.intentId}${up(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${bs(e)}${r}`}}return{...l,...Ep(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Mp=d.object({version:d.literal(1),result:d.literal(`latest-version`),latestVersion:d.string(),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Np=d.object({version:d.literal(1),result:d.literal(`fetch-failure`),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Pp=d.variant(`result`,[Mp,Np]),Fp=d.object({"dist-tags":d.object({latest:d.string()})}),Ip=`cache`;function Lp(){return te(ol(),Ip,`cli-version.json`)}function Rp(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function zp(e){try{let t=JSON.parse(T(e,`utf8`)),n=d.safeParse(Pp,t);return n.success?n.output:void 0}catch{return}}function Bp(e){let t=zp(e);if(!t)return;let n=Date.parse(t.checkedAt);if(!Number.isFinite(n))return;let r=Date.now()-n,i=t.result===`fetch-failure`?36e5:864e5;if(!(r<0||r>=i))return t}function Vp(e){try{return!C(e)||k(e).isFile()}catch{return!1}}function Hp(e){let t=pp(ol(),Ip);if(t===void 0||!Vp(e))return!1;let n=te(t,`.cli-version-check-${g(6).toString(`hex`)}.tmp`);try{return A(n,``,{encoding:`utf8`,mode:384}),O(n,{force:!0}),!0}catch{try{O(n,{force:!0})}catch{}return!1}}function Up(e,t){if(pp(ol(),Ip)===void 0)return!1;try{let n=`${e}.${g(6).toString(`hex`)}.tmp`;return A(n,`${JSON.stringify({version:1,...t,checkedAt:new Date().toISOString()},null,2)}\n`,{encoding:`utf8`,mode:384}),D(n,e),!0}catch{return!1}}async function Wp(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(Rp(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=d.safeParse(Fp,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function Gp(e){let t=ae.valid(e.currentVersion),n=ae.valid(e.latestVersion);t!==null&&n!==null&&ae.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function Kp({packageName:e,currentVersion:t}){let n=Lp(),r=Bp(n);if(r?.result===`latest-version`){Gp({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!Hp(n))return;let i=await Wp({packageName:e});if(i===void 0){Up(n,{result:`fetch-failure`});return}Up(n,{result:`latest-version`,latestVersion:i}),Gp({packageName:e,currentVersion:t,latestVersion:i})}const qp=[{command:`link`,from:`--bank-url`,to:`--api-url`},{command:`link`,from:`--bankUrl`,to:`--api-url`}];function Jp(e){return e.find(e=>!e.startsWith(`-`))??null}function Yp(e,t){let n=qp.find(({command:n,from:r})=>n===t&&(e===r||e.startsWith(`${r}=`)));return n===void 0?null:{to:n.to+e.slice(n.from.length),notice:`${n.from} is deprecated; use ${n.to}`}}function Xp(e){let t=e.indexOf(`--`),n=t===-1?e.length:t,r=e.slice(0,n),i=Jp(r),a=r.map(e=>({token:e,rename:Yp(e,i)}));return{rawArgs:[...a.map(({token:e,rename:t})=>t?.to??e),...e.slice(n)],notices:a.flatMap(({rename:e})=>e===null?[]:[e.notice])}}async function Zp(e){return typeof e==`function`?await e():await e}async function Qp(e){return typeof e==`function`?await e():await e}async function $p(e){return typeof e==`function`?await e():await e}async function em(e,t,n=[]){if(e===t)return n;let r=await $p(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>em(await Zp(r),t,[...n,e])))).find(e=>e!==void 0)}async function tm(e,t){if(!e||!t||t.length<2)return e;let n=await Qp(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function nm(e){return async(t,n)=>{let r=await l(t,await tm(n,await em(e,t)));console.log(`${r}\n`)}}function rm({shouldCheckCliVersionFreshness:e}){return c({meta:{name:`catena`,version:oe,description:`Catena CLI`},async setup({rawArgs:t}){e&&t.length!==0&&await Kp({packageName:P,currentVersion:oe})},subCommands:{link:Bd,unlink:Sf,profiles:hf,whoami:wf,policy:af,accounts:xu,intents:rd,send:_f,transfer:yf,mpp:()=>import(`./mpp-Dwn6_pas.mjs`).then(e=>e.mppCommand),x402:jp,counterparties:Gu,feedback:Xu,guide:Qu}})}const im=rm({shouldCheckCliVersionFreshness:!0});rm({shouldCheckCliVersionFreshness:!1});function am(e){let t=Xp(e);for(let e of t.notices)console.error(e);return[...t.rawArgs]}function om(){u(im,{rawArgs:am(process.argv.slice(2)),showUsage:nm(im)})}om();export{ds as A,ks as C,Vs as D,Hs as E,Ba as M,ge as N,X as O,js as S,Q as T,Of as _,fp as a,$ as b,rp as c,ep as d,np as f,kf as g,jf as h,op as i,gs as j,bs as k,up as l,Nf as m,_p as n,ip as o,Mf as p,ap as r,cp as s,Ep as t,dp as u,Df as v,Z as w,Ws as x,Tf as y};
825
+ const Zd=e(i(((e,t)=>{(function(e){var n=1e9,r={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:`2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286`},i=!0,a=`[DecimalError] `,o=a+`Invalid argument: `,s=a+`Exponent out of range: `,c=Math.floor,l=Math.pow,u=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,d,f=1e7,p=7,m=9007199254740991,h=c(m/p),g={};g.absoluteValue=g.abs=function(){var e=new this.constructor(this);return e.s&&=1,e},g.comparedTo=g.cmp=function(e){var t,n,r,i,a=this;if(e=new a.constructor(e),a.s!==e.s)return a.s||-e.s;if(a.e!==e.e)return a.e>e.e^a.s<0?1:-1;for(r=a.d.length,i=e.d.length,t=0,n=r<i?r:i;t<n;++t)if(a.d[t]!==e.d[t])return a.d[t]>e.d[t]^a.s<0?1:-1;return r===i?0:r>i^a.s<0?1:-1},g.decimalPlaces=g.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*p;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n},g.dividedBy=g.div=function(e){return b(this,new this.constructor(e))},g.dividedToIntegerBy=g.idiv=function(e){var t=this,n=t.constructor;return D(b(t,new n(e),0,1),n.precision)},g.equals=g.eq=function(e){return!this.cmp(e)},g.exponent=function(){return S(this)},g.greaterThan=g.gt=function(e){return this.cmp(e)>0},g.greaterThanOrEqualTo=g.gte=function(e){return this.cmp(e)>=0},g.isInteger=g.isint=function(){return this.e>this.d.length-2},g.isNegative=g.isneg=function(){return this.s<0},g.isPositive=g.ispos=function(){return this.s>0},g.isZero=function(){return this.s===0},g.lessThan=g.lt=function(e){return this.cmp(e)<0},g.lessThanOrEqualTo=g.lte=function(e){return this.cmp(e)<1},g.logarithm=g.log=function(e){var t,n=this,r=n.constructor,o=r.precision,s=o+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(d))throw Error(a+`NaN`);if(n.s<1)throw Error(a+(n.s?`NaN`:`-Infinity`));return n.eq(d)?new r(0):(i=!1,t=b(T(n,s),T(e,s),s),i=!0,D(t,o))},g.minus=g.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?O(t,e):_(t,(e.s=-e.s,e))},g.modulo=g.mod=function(e){var t,n=this,r=n.constructor,o=r.precision;if(e=new r(e),!e.s)throw Error(a+`NaN`);return n.s?(i=!1,t=b(n,e,0,1).times(e),i=!0,n.minus(t)):D(new r(n),o)},g.naturalExponential=g.exp=function(){return x(this)},g.naturalLogarithm=g.ln=function(){return T(this)},g.negated=g.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e},g.plus=g.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?_(t,e):O(t,(e.s=-e.s,e))},g.precision=g.sd=function(e){var t,n,r,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(o+e);if(t=S(i)+1,r=i.d.length-1,n=r*p+1,r=i.d[r],r){for(;r%10==0;r/=10)n--;for(r=i.d[0];r>=10;r/=10)n++}return e&&t>n?t:n},g.squareRoot=g.sqrt=function(){var e,t,n,r,o,s,l,u=this,d=u.constructor;if(u.s<1){if(!u.s)return new d(0);throw Error(a+`NaN`)}for(e=S(u),i=!1,o=Math.sqrt(+u),o==0||o==1/0?(t=y(u.d),(t.length+e)%2==0&&(t+=`0`),o=Math.sqrt(t),e=c((e+1)/2)-(e<0||e%2),o==1/0?t=`5e`+e:(t=o.toExponential(),t=t.slice(0,t.indexOf(`e`)+1)+e),r=new d(t)):r=new d(o.toString()),n=d.precision,o=l=n+3;;)if(s=r,r=s.plus(b(u,s,l+2)).times(.5),y(s.d).slice(0,l)===(t=y(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),o==l&&t==`4999`){if(D(s,n+1,0),s.times(s).eq(u)){r=s;break}}else if(t!=`9999`)break;l+=4}return i=!0,D(r,n)},g.times=g.mul=function(e){var t,n,r,a,o,s,c,l,u,d=this,p=d.constructor,m=d.d,h=(e=new p(e)).d;if(!d.s||!e.s)return new p(0);for(e.s*=d.s,n=d.e+e.e,l=m.length,u=h.length,l<u&&(o=m,m=h,h=o,s=l,l=u,u=s),o=[],s=l+u,r=s;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,a=l+r;a>r;)c=o[a]+h[r]*m[a-r-1]+t,o[a--]=c%f|0,t=c/f|0;o[a]=(o[a]+t)%f|0}for(;!o[--s];)o.pop();return t?++n:o.shift(),e.d=o,e.e=n,i?D(e,p.precision):e},g.toDecimalPlaces=g.todp=function(e,t){var r=this,i=r.constructor;return r=new i(r),e===void 0?r:(v(e,0,n),t===void 0?t=i.rounding:v(t,0,8),D(r,e+S(r)+1,t))},g.toExponential=function(e,t){var r,i=this,a=i.constructor;return e===void 0?r=k(i,!0):(v(e,0,n),t===void 0?t=a.rounding:v(t,0,8),i=D(new a(i),e+1,t),r=k(i,!0,e+1)),r},g.toFixed=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?k(a):(v(e,0,n),t===void 0?t=o.rounding:v(t,0,8),i=D(new o(a),e+S(a)+1,t),r=k(i.abs(),!1,e+S(i)+1),a.isneg()&&!a.isZero()?`-`+r:r)},g.toInteger=g.toint=function(){var e=this,t=e.constructor;return D(new t(e),S(e)+1,t.rounding)},g.toNumber=function(){return+this},g.toPower=g.pow=function(e){var t,n,r,o,s,l,u=this,f=u.constructor,h=12,g=+(e=new f(e));if(!e.s)return new f(d);if(u=new f(u),!u.s){if(e.s<1)throw Error(a+`Infinity`);return u}if(u.eq(d))return u;if(r=f.precision,e.eq(d))return D(u,r);if(t=e.e,n=e.d.length-1,l=t>=n,s=u.s,!l){if(s<0)throw Error(a+`NaN`)}else if((n=g<0?-g:g)<=m){for(o=new f(d),t=Math.ceil(r/p+4),i=!1;n%2&&(o=o.times(u),A(o.d,t)),n=c(n/2),n!==0;)u=u.times(u),A(u.d,t);return i=!0,e.s<0?new f(d).div(o):D(o,r)}return s=s<0&&e.d[Math.max(t,n)]&1?-1:1,u.s=1,i=!1,o=e.times(T(u,r+h)),i=!0,o=x(o),o.s=s,o},g.toPrecision=function(e,t){var r,i,a=this,o=a.constructor;return e===void 0?(r=S(a),i=k(a,r<=o.toExpNeg||r>=o.toExpPos)):(v(e,1,n),t===void 0?t=o.rounding:v(t,0,8),a=D(new o(a),e,t),r=S(a),i=k(a,e<=r||r<=o.toExpNeg,e)),i},g.toSignificantDigits=g.tosd=function(e,t){var r=this,i=r.constructor;return e===void 0?(e=i.precision,t=i.rounding):(v(e,1,n),t===void 0?t=i.rounding:v(t,0,8)),D(new i(r),e,t)},g.toString=g.valueOf=g.val=g.toJSON=function(){var e=this,t=S(e),n=e.constructor;return k(e,t<=n.toExpNeg||t>=n.toExpPos)};function _(e,t){var n,r,a,o,s,c,l,u,d=e.constructor,m=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),i?D(t,m):t;if(l=e.d,u=t.d,s=e.e,a=t.e,l=l.slice(),o=s-a,o){for(o<0?(r=l,o=-o,c=u.length):(r=u,a=s,c=l.length),s=Math.ceil(m/p),c=s>c?s+1:c+1,o>c&&(o=c,r.length=1),r.reverse();o--;)r.push(0);r.reverse()}for(c=l.length,o=u.length,c-o<0&&(o=c,r=u,u=l,l=r),n=0;o;)n=(l[--o]=l[o]+u[o]+n)/f|0,l[o]%=f;for(n&&(l.unshift(n),++a),c=l.length;l[--c]==0;)l.pop();return t.d=l,t.e=a,i?D(t,m):t}function v(e,t,n){if(e!==~~e||e<t||e>n)throw Error(o+e)}function y(e){var t,n,r,i=e.length-1,a=``,o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+``,n=p-r.length,n&&(a+=w(n)),a+=r;o=e[t],r=o+``,n=p-r.length,n&&(a+=w(n))}else if(o===0)return`0`;for(;o%10==0;)o/=10;return a+o}var b=(function(){function e(e,t){var n,r=0,i=e.length;for(e=e.slice();i--;)n=e[i]*t+r,e[i]=n%f|0,r=n/f|0;return r&&e.unshift(r),e}function t(e,t,n,r){var i,a;if(n!=r)a=n>r?1:-1;else for(i=a=0;i<n;i++)if(e[i]!=t[i]){a=e[i]>t[i]?1:-1;break}return a}function n(e,t,n){for(var r=0;n--;)e[n]-=r,r=+(e[n]<t[n]),e[n]=r*f+e[n]-t[n];for(;!e[0]&&e.length>1;)e.shift()}return function(r,i,o,s){var c,l,u,d,m,h,g,_,v,y,b,x,C,w,T,E,O,k,A=r.constructor,ee=r.s==i.s?1:-1,j=r.d,M=i.d;if(!r.s)return new A(r);if(!i.s)throw Error(a+`Division by zero`);for(l=r.e-i.e,O=M.length,T=j.length,g=new A(ee),_=g.d=[],u=0;M[u]==(j[u]||0);)++u;if(M[u]>(j[u]||0)&&--l,x=o==null?o=A.precision:s?o+(S(r)-S(i))+1:o,x<0)return new A(0);if(x=x/p+2|0,u=0,O==1)for(d=0,M=M[0],x++;(u<T||d)&&x--;u++)C=d*f+(j[u]||0),_[u]=C/M|0,d=C%M|0;else{for(d=f/(M[0]+1)|0,d>1&&(M=e(M,d),j=e(j,d),O=M.length,T=j.length),w=O,v=j.slice(0,O),y=v.length;y<O;)v[y++]=0;k=M.slice(),k.unshift(0),E=M[0],M[1]>=f/2&&++E;do d=0,c=t(M,v,O,y),c<0?(b=v[0],O!=y&&(b=b*f+(v[1]||0)),d=b/E|0,d>1?(d>=f&&(d=f-1),m=e(M,d),h=m.length,y=v.length,c=t(m,v,h,y),c==1&&(d--,n(m,O<h?k:M,h))):(d==0&&(c=d=1),m=M.slice()),h=m.length,h<y&&m.unshift(0),n(v,m,y),c==-1&&(y=v.length,c=t(M,v,O,y),c<1&&(d++,n(v,O<y?k:M,y))),y=v.length):c===0&&(d++,v=[0]),_[u++]=d,c&&v[0]?v[y++]=j[w]||0:(v=[j[w]],y=1);while((w++<T||v[0]!==void 0)&&x--)}return _[0]||_.shift(),g.e=l,D(g,s?o+S(g)+1:o)}})();function x(e,t){var n,r,a,o,c,u,f=0,p=0,m=e.constructor,h=m.precision;if(S(e)>16)throw Error(s+S(e));if(!e.s)return new m(d);for(t==null?(i=!1,u=h):u=t,c=new m(.03125);e.abs().gte(.1);)e=e.times(c),p+=5;for(r=Math.log(l(2,p))/Math.LN10*2+5|0,u+=r,n=a=o=new m(d),m.precision=u;;){if(a=D(a.times(e),u),n=n.times(++f),c=o.plus(b(a,n,u)),y(c.d).slice(0,u)===y(o.d).slice(0,u)){for(;p--;)o=D(o.times(o),u);return m.precision=h,t==null?(i=!0,D(o,h)):o}o=c}}function S(e){for(var t=e.e*p,n=e.d[0];n>=10;n/=10)t++;return t}function C(e,t,n){if(t>e.LN10.sd())throw i=!0,n&&(e.precision=n),Error(a+`LN10 precision limit exceeded`);return D(new e(e.LN10),t)}function w(e){for(var t=``;e--;)t+=`0`;return t}function T(e,t){var n,r,o,s,c,l,u,f,p,m=1,h=10,g=e,_=g.d,v=g.constructor,x=v.precision;if(g.s<1)throw Error(a+(g.s?`NaN`:`-Infinity`));if(g.eq(d))return new v(0);if(t==null?(i=!1,f=x):f=t,g.eq(10))return t??(i=!0),C(v,f);if(f+=h,v.precision=f,n=y(_),r=n.charAt(0),s=S(g),Math.abs(s)<0x5543df729c000){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)g=g.times(e),n=y(g.d),r=n.charAt(0),m++;s=S(g),r>1?(g=new v(`0.`+n),s++):g=new v(r+`.`+n.slice(1))}else return u=C(v,f+2,x).times(s+``),g=T(new v(r+`.`+n.slice(1)),f-h).plus(u),v.precision=x,t==null?(i=!0,D(g,x)):g;for(l=c=g=b(g.minus(d),g.plus(d),f),p=D(g.times(g),f),o=3;;){if(c=D(c.times(p),f),u=l.plus(b(c,new v(o),f)),y(u.d).slice(0,f)===y(l.d).slice(0,f))return l=l.times(2),s!==0&&(l=l.plus(C(v,f+2,x).times(s+``))),l=b(l,new v(m),f),v.precision=x,t==null?(i=!0,D(l,x)):l;l=u,o+=2}}function E(e,t){var n,r,a;for((n=t.indexOf(`.`))>-1&&(t=t.replace(`.`,``)),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=c(n/p),e.d=[],r=(n+1)%p,n<0&&(r+=p),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=p;r<a;)e.d.push(+t.slice(r,r+=p));t=t.slice(r),r=p-t.length}else r-=a;for(;r--;)t+=`0`;if(e.d.push(+t),i&&(e.e>h||e.e<-h))throw Error(s+n)}else e.s=0,e.e=0,e.d=[0];return e}function D(e,t,n){var r,a,o,u,d,m,g,_,v=e.d;for(u=1,o=v[0];o>=10;o/=10)u++;if(r=t-u,r<0)r+=p,a=t,g=v[_=0];else{if(_=Math.ceil((r+1)/p),o=v.length,_>=o)return e;for(g=o=v[_],u=1;o>=10;o/=10)u++;r%=p,a=r-p+u}if(n!==void 0&&(o=l(10,u-a-1),d=g/o%10|0,m=t<0||v[_+1]!==void 0||g%o,m=n<4?(d||m)&&(n==0||n==(e.s<0?3:2)):d>5||d==5&&(n==4||m||n==6&&(r>0?a>0?g/l(10,u-a):0:v[_-1])%10&1||n==(e.s<0?8:7))),t<1||!v[0])return m?(o=S(e),v.length=1,t=t-o-1,v[0]=l(10,(p-t%p)%p),e.e=c(-t/p)||0):(v.length=1,v[0]=e.e=e.s=0),e;if(r==0?(v.length=_,o=1,_--):(v.length=_+1,o=l(10,p-r),v[_]=a>0?(g/l(10,u-a)%l(10,a)|0)*o:0),m)for(;;)if(_==0){(v[0]+=o)==f&&(v[0]=1,++e.e);break}else{if(v[_]+=o,v[_]!=f)break;v[_--]=0,o=1}for(r=v.length;v[--r]===0;)v.pop();if(i&&(e.e>h||e.e<-h))throw Error(s+S(e));return e}function O(e,t){var n,r,a,o,s,c,l,u,d,m,h=e.constructor,g=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),i?D(t,g):t;if(l=e.d,m=t.d,r=t.e,u=e.e,l=l.slice(),s=u-r,s){for(d=s<0,d?(n=l,s=-s,c=m.length):(n=m,r=u,c=l.length),a=Math.max(Math.ceil(g/p),c)+2,s>a&&(s=a,n.length=1),n.reverse(),a=s;a--;)n.push(0);n.reverse()}else{for(a=l.length,c=m.length,d=a<c,d&&(c=a),a=0;a<c;a++)if(l[a]!=m[a]){d=l[a]<m[a];break}s=0}for(d&&(n=l,l=m,m=n,t.s=-t.s),c=l.length,a=m.length-c;a>0;--a)l[c++]=0;for(a=m.length;a>s;){if(l[--a]<m[a]){for(o=a;o&&l[--o]===0;)l[o]=f-1;--l[o],l[a]+=f}l[a]-=m[a]}for(;l[--c]===0;)l.pop();for(;l[0]===0;l.shift())--r;return l[0]?(t.d=l,t.e=r,i?D(t,g):t):new h(0)}function k(e,t,n){var r,i=S(e),a=y(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+`.`+a.slice(1)+w(r):o>1&&(a=a.charAt(0)+`.`+a.slice(1)),a=a+(i<0?`e`:`e+`)+i):i<0?(a=`0.`+w(-i-1)+a,n&&(r=n-o)>0&&(a+=w(r))):i>=o?(a+=w(i+1-o),n&&(r=n-i-1)>0&&(a=a+`.`+w(r))):((r=i+1)<o&&(a=a.slice(0,r)+`.`+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+=`.`),a+=w(r))),e.s<0?`-`+a:a}function A(e,t){if(e.length>t)return e.length=t,!0}function ee(e){var t,n,r;function i(e){var t=this;if(!(t instanceof i))return new i(e);if(t.constructor=i,e instanceof i){t.s=e.s,t.e=e.e,t.d=(e=e.d)?e.slice():e;return}if(typeof e==`number`){if(e*0!=0)throw Error(o+e);if(e>0)t.s=1;else if(e<0)e=-e,t.s=-1;else{t.s=0,t.e=0,t.d=[0];return}if(e===~~e&&e<1e7){t.e=0,t.d=[e];return}return E(t,e.toString())}if(typeof e!=`string`)throw Error(o+e);if(e.charCodeAt(0)===45?(e=e.slice(1),t.s=-1):t.s=1,u.test(e))E(t,e);else throw Error(o+e)}if(i.prototype=g,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=ee,i.config=i.set=j,e===void 0&&(e={}),e)for(r=[`precision`,`rounding`,`toExpNeg`,`toExpPos`,`LN10`],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function j(e){if(!e||typeof e!=`object`)throw Error(a+`Object expected`);var t,r,i,s=[`precision`,1,n,`rounding`,0,8,`toExpNeg`,-1/0,0,`toExpPos`,0,1/0];for(t=0;t<s.length;t+=3)if((i=e[r=s[t]])!==void 0){if(c(i)===i&&i>=s[t+1]&&i<=s[t+2])this[r]=i;else throw Error(o+r+`: `+i)}if((i=e[r=`LN10`])!==void 0){if(i==Math.LN10)this[r]=new this(i);else throw Error(o+r+`: `+i)}return this}r=ee(r),r.default=r.Decimal=r,d=new r(1),typeof define==`function`&&define.amd?define(function(){return r}):t!==void 0&&t.exports?t.exports=r:(e||=typeof self<`u`&&self&&self.self==self?self:Function(`return this`)(),e.Decimal=r)})(e)}))(),1).default;Zd.set({rounding:Zd.ROUND_HALF_EVEN});const Qd=new Map,$d=/^[A-Z]{3}$/,ef=/^[A-Z0-9]{2,6}$/;function tf(e,t,n,r){if(Qd.has(e))throw Error(`duplicate asset id ${e}`);let i=new Zd(r);if(i.isNegative())throw Error(`dustThreshold must be a non-negative decimal`);if(i.decimalPlaces()>t)throw Error(`dustThreshold (${r}) must not be finer than the asset's ${t} decimals`);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)throw Error(`decimals and presentmentDecimals must be non-negative integers`);if(n>t)throw Error(`presentment decimals should be less than or equal to decimals`)}function nf(e,t,n,r,i){if(!$d.test(e))throw Error(`fiat asset ids must be 3-letter ISO-4217 codes`);tf(e,n,r,i.dustThreshold);let a=e;return Qd.set(e,{id:a,symbol:e,name:t,kind:`fiat`,decimals:n,presentmentDecimals:r,denomination:e,valuation:{type:`par`},dustThreshold:i.dustThreshold}),a}function rf(e,t,n,r,i){if(!ef.test(e)||$d.test(e))throw Error(`stablecoin tickers must be 2-6 uppercase alphanumerics and not a 3-letter ISO-4217 shape`);let a=Qd.get(i.denomination);if(!a||a.kind!==`fiat`)throw Error(`stablecoin denomination must be a registered fiat asset, got ${i.denomination}`);if(n>a.decimals)throw Error(`par stablecoin decimals (${n}) must not exceed its denomination fiat's (${a.decimals})`);tf(e,n,r,i.dustThreshold);let o=e;return Qd.set(e,{id:o,symbol:e,name:t,kind:`stablecoin`,decimals:n,presentmentDecimals:r,denomination:a.denomination,valuation:{type:`par`},dustThreshold:i.dustThreshold}),o}rf(`USDC`,`USD Coin`,6,2,{denomination:nf(`USD`,`US Dollar`,6,2,{dustThreshold:`0.01`}),dustThreshold:`0.01`}),new Zd(1e6),new Zd(1e3),new Zd(1);const af=d.pipe(d.string(`Amount must be a string`),d.nonEmpty(`Amount must not be empty`),d.check(e=>e.trim()===e,`Amount must not have leading or trailing whitespace`),d.check(e=>!e.includes(`e`)&&!e.includes(`E`),`Scientific notation is not supported (e.g. use 1000000 instead of 1e6)`),d.check(e=>!e.startsWith(`+`),`Amount must not have a '+' prefix`),d.check(e=>!e.startsWith(`-`),`Amount must be non-negative`),d.check(e=>{try{return new Zd(e).gte(0)}catch{return!1}},`Amount must be a valid decimal (e.g. 100 or 100.50)`)),of=d.pipe(d.string(`Count must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+$/.test(e),`Count must be a whole number of transactions (e.g. 20)`),d.transform(Number),d.check(e=>Number.isSafeInteger(e),`Count is too large`),d.check(e=>e>=1,`Count must be at least 1`)),sf={s:1,m:60,h:3600,d:86400},cf=d.pipe(d.string(`Duration must be a string`),d.transform(e=>e.trim()),d.check(e=>/^\d+[smhd]?$/.test(e),`Duration must be a number of seconds or a value with a unit (e.g. 90s, 30m, 4h, 2d)`),d.transform(e=>{let t=e.at(-1)??``;return t in sf?Number(e.slice(0,-1))*sf[t]:Number(e)}),d.check(e=>e>=60,`Duration must be at least 1 minute`),d.check(e=>e<=604800,`Duration must be at most 7 days`)),lf=Q({profile:Xs,json:Zs}),uf=c({meta:{name:`show`,description:`Show the agent's assigned policy`},args:lf.args,async run({args:e}){await $(lf.parse(e))(e=>e.getPolicy())}}),df=Q({account:Z({description:`Account whose existing hard limit should increase. For a transfer limit, the source account funds move out of.`,required:!0}),capability:Bs({description:`Which capability's limit to increase: send (payments to counterparties) or transfer (between the user's own accounts)`,choices:as,default:`send`}),rule:Bs({description:`Which limit to adjust`,choices:fo,default:`per_transaction_amount`}),amount:Z({description:`New threshold for an amount limit, as a decimal USD string (e.g. 500.00)`,schema:af,showValueInError:!0}),count:Z({description:`New threshold for a transaction-count limit (e.g. 20)`,schema:of,showValueInError:!0}),duration:Z({description:`How long the override should last once approved (e.g. 90s, 30m, 4h, 2d). One minute to seven days.`,required:!0,schema:cf,showValueInError:!0}),reason:Z({description:`Why the task needs this, for the person who reviews the request`,required:!0}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:ju}),profile:Xs,json:Zs}),ff=c({meta:{name:`request-override`,description:`Ask a person to approve a temporary change to this agent's limits`},args:df.args,async run({args:e}){let t=df.parse(e),n=$(t),r={type:`policy_override`,operations:[pf(t)],durationSeconds:t.duration,reason:t.reason};await n(e=>e.submitIntent({action:r,...t.idempotencyKey!==void 0&&{idempotencyKey:t.idempotencyKey}}))}});function pf(e){return e.rule===`hourly_count`||e.rule===`daily_count`?(e.amount!==void 0&&X(`--amount does not apply to ${e.rule}; use --count`),e.count===void 0&&X(`--count is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{count:e.count}}):(e.count!==void 0&&X(`--count does not apply to ${e.rule}; use --amount`),e.amount===void 0&&X(`--amount is required for ${e.rule}`),{type:`increase_limit`,accountId:e.account,capability:e.capability,limitType:e.rule,newLimit:{amount:e.amount,assetId:`USD`}})}const mf=c({meta:{name:`policy`,description:`Inspect the agent's policy`},subCommands:{show:uf,"request-override":ff}}),hf=Q({profile:Ls({description:`Profile name`,required:!0})});function gf(){try{return eu({env:process.env[Xl],cwd:process.cwd(),log:e=>console.error(e)})}catch(e){return X(e)}}const _f=c({meta:{name:`use`,description:`Set the default credential profile`},args:hf.args,async run({args:e}){let t=hf.parse(e);try{zl(t.profile),hu({defaultProfile:t.profile})}catch(e){X(e)}}}),vf=c({meta:{name:`current`,description:`Show the selected credential profile and how it was chosen`},async run(){let e;try{e=Yl()}catch(e){X(e)}if(e!==null){hu({source:`secret-key`,credential:Kl,apiUrl:e.apiUrl});return}let t=gf(),n;try{n=Pl(t.name)}catch(e){X(e)}n===null&&X(`Profile "${t.name}" is not linked.\nRun 'catena link --profile ${t.name} <agent-id>' to authenticate.`),hu({profile:t.name,source:t.source,apiUrl:n.api_url,agentId:Tl(n)?n.agent_id:void 0})}}),yf=c({meta:{name:`list`,description:`List credential profiles and their directory bindings`},async run(){let e;try{e=xl()}catch(e){X(e)}let t=Jl(),n;try{n=t?null:eu({env:process.env[Xl],cwd:process.cwd()}).name}catch{n=null}let r=Object.entries(e.directories??{});hu({defaultProfile:e.default_profile,...t?{shadowedBy:Kl}:{},profiles:Object.entries(e.profiles).toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({name:e,apiUrl:t.api_url,agentId:Tl(t)?t.agent_id:void 0,directories:r.filter(([,t])=>t===e).map(([e])=>e).toSorted(),current:e===n}))})}}),bf=Q({profile:Ls({description:`Profile name to bind`,required:!0}),path:Ls({description:`Directory to bind (defaults to the current directory)`})}),xf=c({meta:{name:`bind`,description:`Bind a directory to a profile for automatic selection`},args:bf.args,async run({args:e}){let t=bf.parse(e);try{let e=t.path??process.cwd();if(md(e))throw Error(`Refusing to bind the home directory or an ancestor of it — that would shadow the default profile for every directory beneath it. Bind a specific agent directory instead.`);let n=Ml(e,t.profile);hu({profile:t.profile,directory:n})}catch(e){X(e)}}}),Sf=Q({path:Ls({description:`Directory to unbind (defaults to the current directory)`})}),Cf=c({meta:{name:`unbind`,description:`Remove a directory's profile binding`},args:Sf.args,async run({args:e}){let t=Sf.parse(e);try{hu(Nl(t.path??process.cwd()))}catch(e){X(e)}}}),wf=c({meta:{name:`profiles`,description:`Manage credential profiles`},subCommands:{use:_f,current:vf,list:yf,bind:xf,unbind:Cf}}),Tf=Q({account:Z({description:`Source account id; omit when the policy allows sends from exactly one account`,schema:$s}),rail:Z({description:`Destination counterparty rail id (cpr_...)`,required:!0,schema:$s}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:af,showValueInError:!0}),method:Bs({description:`ach | wire | on-chain; ach and wire require a bank rail, on-chain a wallet rail`,required:!0,choices:Eo}),memo:Z({description:`ACH/wire payment reference; deprecated for on-chain sends`}),description:Z({description:`Internal note stored in Catena`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:ju}),profile:Xs,json:Zs}),Ef=c({meta:{name:`send`,description:`Submit a USD send intent to a counterparty rail`},args:Tf.args,async run({args:e}){let t=Tf.parse(e),n={type:`send`,...t.account!==void 0&&{accountId:t.account},counterpartyRailId:t.rail,amount:t.amount,...t.description?{description:t.description}:{},method:t.method,...t.memo?{memo:t.memo}:{}};await $(t)(e=>e.submitIntent({action:n,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}}),Df=Q({from:Z({description:`Source account id`,required:!0,schema:$s}),to:Z({description:`Destination account id`,required:!0,schema:$s}),amount:Z({description:`USD amount as a decimal string (e.g. 125.00)`,required:!0,schema:af,showValueInError:!0}),memo:Z({description:`Memo on the underlying transfer`}),description:Z({description:`Operator-facing description`}),idempotencyKey:Z({description:`Optional operation key. Reuse the same value only when retrying the same submission; omitted generates a fresh key for this invocation.`,schema:ju}),profile:Xs,json:Zs}),Of=c({meta:{name:`transfer`,description:`Submit a USD transfer intent between two of this agent's accounts`},args:Df.args,async run({args:e}){let t=Df.parse(e),n=$(t),r={type:`transfer`,accountId:t.from,toAccountId:t.to,amount:t.amount,...t.memo?{memo:t.memo}:{},...t.description?{description:t.description}:{}};await n(e=>e.submitIntent({action:r,...t.idempotencyKey?{idempotencyKey:t.idempotencyKey}:{}}))}});function kf(){return`${Kl} is set, and this command removes only a linked profile. Revoke the key in the Catena console under the agent's Secret keys tab, or pass --profile <name> to target a profile on this machine.`}const Af=Q({profile:Xs,force:zs({description:`Remove the profile and its local credentials without contacting the server; use when the credential is missing, revoked, or a link was interrupted`,default:!1}),json:Zs}),jf=c({meta:{name:`unlink`,description:`Disconnect the selected agent profile`},args:Af.args,async run({args:e}){let t=Af.parse(e),n=lu();!t.force&&gu(t)===void 0&&Jl()&&X(kf());let r;try{r=eu({flag:gu(t),env:process.env[Xl],cwd:process.cwd(),log:e=>console.error(e)}).name}catch(e){X(e)}if(t.force){let e;try{if(e=Pl(r),e===null)throw Error(Jl()?`Profile "${r}" not found, and this machine holds no profile to clear. Revoke the key in the Catena console under the agent's Secret keys tab.`:`Profile "${r}" not found`);await n.delete(e.client_instance_id),await n.delete(Ed(e.client_instance_id)),kl(r)}catch(e){X(e)}hu({success:!0,profile:r,...Tl(e)?{agentId:e.agent_id}:{},local:!0},{compact:t.json});return}let i=`To remove only this machine's copy, run 'catena unlink --profile ${r} --force'.`,a=await Wl({profileName:r,fallbackApiUrl:Gl},n);a.ok||X(`${a.message} ${i}`);let o=cu(a);try{await o.unlinkAgent(),await n.delete(a.clientInstanceId),await n.delete(Ed(a.clientInstanceId)),kl(r)}catch(e){X(`${ks(mu(e,r))} ${i}`)}hu({success:!0,profile:r,agentId:a.agentId},{compact:t.json})}}),Mf=Q({profile:Xs,json:Zs}),Nf=c({meta:{name:`whoami`,description:`Show which agent you are currently acting as`},args:Mf.args,async run({args:e}){await $(Mf.parse(e))(e=>e.whoami())}});function Pf(e){throw Error(`Unhandled case: ${String(e)}`)}const Ff=d.object({requiredRail:Ao});function If(e,t){let n=d.safeParse(Ff,e);if(n.success&&n.output.requiredRail.walletAddress.toLowerCase()===t.toLowerCase())return n.output.requiredRail}function Lf(e,t){return t?.body!==void 0&&t.body!==null&&typeof t.body!=`string`&&!(t.body instanceof URLSearchParams)&&!(t.body instanceof Blob)&&!(t.body instanceof ArrayBuffer)&&!ArrayBuffer.isView(t.body)?!1:typeof Request<`u`&&e instanceof Request?e.body===null&&!e.bodyUsed:!0}function Rf(e,t){let n=new Headers(typeof Request<`u`&&e instanceof Request?e.headers:void 0);return new Headers(t?.headers).forEach((e,t)=>{n.set(t,e)}),n}const zf={"eip155:8453":`Base`,"eip155:84532":`Base Sepolia`,"eip155:5042":`Arc`};function Bf(e){let t=Object.hasOwn(zf,e)?zf[e]:void 0;return t?`${t} (${e})`:e}const Vf=/^0x[0-9a-fA-F]{64}$/;async function Hf(e,t,n,r){try{await e.reportSettlement({intentId:t,txHash:n,...r!==void 0&&{receipt:r}})}catch{return}}const Uf=[`PAYMENT-REQUIRED`,`X-Payment-Required`],Wf=/^0x[0-9a-fA-F]{40}$/,Gf=d.looseObject({success:d.boolean(),transaction:d.string(),extensions:d.optional(d.unknown())}),Kf=d.looseObject({x402Version:d.literal(2),accepts:d.array(Xo),resource:d.optional(Zo),extensions:d.optional(d.unknown())}),qf=`x402_network_mismatch`,Jf=`x402_counterparty_rail_not_found`,Yf=new Set([`x402_requirement_not_payable`,qf,Jf]);function Xf(e){let t=e.replaceAll(`-`,`+`).replaceAll(`_`,`/`),n=Uint8Array.from(atob(t),e=>e.charCodeAt(0));return JSON.parse(new TextDecoder().decode(n))}function Zf(e){let t=Uf.map(t=>e.headers.get(t)).find(e=>e!==null);if(t)try{let e=d.safeParse(Kf,Xf(t));return e.success?e.output:void 0}catch{return}}async function Qf(e,t,n){try{let r=n.headers.get(`PAYMENT-RESPONSE`);if(!r)return;let i=d.safeParse(Gf,Xf(r));if(!i.success||!i.output.success||!Vf.test(i.output.transaction))return;let a=ro(i.output.extensions);await Hf(e,t,i.output.transaction,a)}catch{}}var $f=class extends Error{reasons;constructor(e,t=[],n={}){super(t.length>0&&(n.appendReasonsToMessage??!0)?`${e}: ${t.join(`; `)}`:e),this.name=`X402PaymentError`,this.reasons=t}},ep=class extends $f{accountId;requiredNetworks;constructor(e,t,n=[]){super(`Account ${e} cannot fund this 402 challenge: it must be paid from a wallet account on ${t.map(Bf).join(` or `)}`,n,{appendReasonsToMessage:!1}),this.name=`X402NetworkMismatchError`,this.accountId=e,this.requiredNetworks=t}},tp=class extends $f{payTo;network;requiredRail;serviceName;constructor(e,t,n,r=[],i){super(`This 402 pays ${e} on ${Bf(t)}, which is not a saved counterparty wallet rail; add it as a counterparty before paying`,r,{appendReasonsToMessage:!1}),this.name=`X402CounterpartyNotFoundError`,this.payTo=e,this.network=t,this.serviceName=n,this.requiredRail=i}},np=class extends $f{intentId;expiresAt;constructor(e,t,n){super(`The payment is awaiting a human approval (intent ${e}); once an operator approves it, retry the request to complete the payment`,t),this.name=`X402ApprovalPendingError`,this.intentId=e,this.expiresAt=n}},rp=class extends $f{receipt;constructor(e,t){super(`The payment settled (intent ${e.intentId}) but the post-payment continuation failed; retry the request with the PAYMENT-SIGNATURE header from the receipt (or getIntent("${e.intentId}") data.paymentCredential.value) instead of paying again`),this.name=`X402RetryFailedError`,this.receipt=e,this.cause=t}};async function ip(e,t){try{return await t()}catch(t){throw new rp(e,t)}}var ap=class extends $f{intentId;requirements;constructor(e,t,n){super(`The payment could not be confirmed (intent ${e}); check getIntent("${e}") — completed: reuse its data.paymentCredential.value as the PAYMENT-SIGNATURE header; processing: poll until terminal; pay again only after blocked or failed`),this.name=`X402SubmitInterruptedError`,this.intentId=e,this.requirements=t,this.cause=n}};async function op(e,t){let n=t.paymentRequired.accepts.filter(e=>e.scheme===`exact`),r=n.filter(e=>t.maxAtomicAmount===void 0||/^\d+$/.test(e.amount)&&BigInt(e.amount)<=t.maxAtomicAmount).slice(0,5);if(r.length===0)throw new $f(n.length>0&&t.maxAtomicAmount!==void 0?`Every requirement in the 402 challenge costs more than the caller's maximum amount`:`The 402 challenge offers no exact-scheme requirement Catena can pay`);let i=t.resource??t.paymentRequired.resource,a=[];for(let n of r){let r=await sp(e,{accountId:t.accountId,requirements:n,resource:i,signedOffer:no(t.paymentRequired.extensions,n)}).catch(e=>{if(e instanceof ps&&e.code!==void 0&&Yf.has(e.code)){a.push({error:e,requirement:n});return}throw e});if(r)return r}let o=a.filter(e=>e.error.code===Jf),s=a.filter(e=>e.error.code===qf),c=a.filter(e=>e.error.code!==Jf&&e.error.code!==qf),l=[...new Set([...o,...s,...c].map(e=>e.error.message))],u=o.find(e=>e.error.status===404&&Wf.test(e.requirement.payTo));throw u?new tp(u.requirement.payTo,u.requirement.network,i?.serviceName,l,If(u.error.details,u.requirement.payTo)):s.length>0&&o.length===0?new ep(t.accountId,[...new Set(s.map(e=>e.requirement.network))],l):new $f(`No requirement in the 402 challenge is payable from this account`,l)}async function sp(e,t){let n=await e.submitIntent({action:{type:`x402`,accountId:t.accountId,paymentRequirements:t.requirements,...t.resource!==void 0&&{resource:t.resource},...t.signedOffer!==void 0&&{signedOffer:t.signedOffer}},idempotencyKey:crypto.randomUUID()}).catch(e=>{throw e instanceof vs&&e.outcome===`unknown`?new ap(e.intentId,t.requirements,e):e});if(n.status===`completed`){let e=Uo(n.data);if(e!==void 0)return{intentId:n.id,paymentSignature:e,requirements:t.requirements};throw new $f(`The completed payment did not carry an x402 payment signature`)}switch(n.status){case`pending`:throw new np(n.id,n.reasons,n.expiresAt);case`processing`:throw new $f(`The payment is still processing (intent ${n.id}); this client cannot resume an in-flight x402 settlement`);case`blocked`:case`failed`:throw new $f(`Catena declined the payment`,n.reasons)}return Pf(n.status)}function cp(e,t){let n=(t.baseFetch??globalThis.fetch).bind(globalThis);return async(r,i)=>{let a=await n(r,i);if(a.status!==402)return a;let o=Zf(a);if(!o)return a;if(!Lf(r,i))throw new $f(`The request body cannot be replayed after payment; buffer the body (string, Blob, or ArrayBuffer) before using the x402 fetch wrapper`);let s=await op(e,{accountId:t.accountId,paymentRequired:o,...t.maxAtomicAmount!==void 0&&{maxAtomicAmount:t.maxAtomicAmount}});await ip(s,()=>t.onPayment?.(s));let c=Rf(r,i);c.set(`PAYMENT-SIGNATURE`,s.paymentSignature);let l=await ip(s,()=>n(r,{...i,headers:c}));return Qf(e,s.intentId,l),l}}function lp(e){if(e===`@-`)return up(0,`stdin`);if(e.startsWith(`@`)){let t=e.slice(1);return t===``?X(`--data @<path>: no file path given`):up(t,`@${t}`)}return e}function up(e,t){try{return T(e,`utf8`)}catch(e){return X(`--data ${t}: ${ks(e)}`)}}function dp(e){let[t,n=``]=e.split(`.`);return BigInt(`${t}${n.padEnd(6,`0`)}`)}const fp=d.pipe(d.string(),d.check(e=>iu.test(e.slice(0,Math.max(e.indexOf(`:`),0))),`must be "Name: Value" with a valid HTTP header name`),d.transform(e=>{let t=e.indexOf(`:`);return{name:e.slice(0,t),value:e.slice(t+1).trimStart()}}),d.check(e=>/^[\t\x20-\x7e\x80-\xff]*$/.test(e.value),`header value contains characters not allowed in an HTTP header`));function pp(e,t){return e.some(e=>e.name.toLowerCase()===t)}function mp(e,t){pp(e,`content-type`)&&t!==void 0&&X(`--header "Content-Type: ..." conflicts with --content-type`)}function hp(e,t,n){let r=[...n!==void 0&&!pp(e,`content-type`)?[[`content-type`,t??`application/json`]]:[],...e.map(e=>[e.name,e.value])];return r.length>0?new Headers(r):void 0}const gp={"eip155:8453":`base`,"eip155:84532":`base-sepolia`,"eip155:5042":`arc`};function _p(e){return Object.hasOwn(gp,e)?gp[e]:void 0}function vp(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function yp(e){return e===void 0?``:` --profile ${vp(e)}`}function bp(e,t){return`Payment submission could not be confirmed (intent ${e}). It may have succeeded. Before paying again, run \`catena intents get ${e}${yp(t)}\`.`}function xp(e,t,n,r){let i=/^[a-z0-9][a-z0-9-]*$/.test(t)?t:vp(t);return`catena counterparties create wallet --name ${vp(n??`<name>`)} --address ${vp(e)} --network ${i}${yp(r)}`}function Sp(e,t){try{w(e,{recursive:!0,mode:448}),x(e,448);let n=te(e,t);return w(n,{recursive:!0,mode:448}),x(n,448),n}catch{return}}const Cp=4e3;function wp(e){try{return k(e)}catch{return}}function Tp(e,t,n){try{b(e,t)}catch{X(n)}}function Ep(e){let t=ne(e),n=j(t),r=wp(n);(r===void 0||!r.isDirectory())&&X(`--output ${e}: directory ${n} does not exist`);let i=wp(t);return i===void 0?(Tp(n,S.W_OK|S.X_OK,`--output ${e}: directory ${n} is not writable`),t):(i.isDirectory()&&X(`--output ${e}: destination is a directory`),i.isFile()||X(`--output ${e}: destination is not a regular file`),Tp(t,S.W_OK,`--output ${e}: destination is not writable`),t)}const Dp=/^(?:con|prn|aux|nul|com\d|lpt\d)$/i;function Op(e){if(e!==void 0&&Qs.test(e)&&!Dp.test(e))return`${e}.body`;let t=`${Date.now()}-${g(4).toString(`hex`)}.body`;return e===void 0?`unpaid-${t}`:`paid-${t}`}function kp(e,t){let n=Sp(hl(),`responses`);if(n===void 0)return;let r=te(n,Op(t));try{return A(r,e,{mode:384}),r}catch{return}}function Ap(e){let t=e.subarray(0,Cp*4),n=t.toString(`utf8`);return{decoded:n,complete:t.length===e.length&&n.length<=Cp&&ie(e)}}function jp({decoded:e,complete:t}){let n=e.slice(0,Cp),r=n.charCodeAt(n.length-1);return{body:r>=55296&&r<=56319?n.slice(0,-1):n,...!t&&{bodyTruncated:!0}}}function Mp(e,t){if(t.complete)return{body:t.decoded};if(e.length>268435456)return{...jp(t),error:`no writable location for the ${e.length}-byte body and it is too large to inline; only the .body preview survived`};if(ie(e)){let t=e.toString(`utf8`);if(6*t.length+2<=N.MAX_STRING_LENGTH)return{body:t};try{return JSON.stringify(t),{body:t}}catch{}}return{body:e.toString(`base64`),bodyEncoding:`base64`}}function Np(e){return e.error===void 0?e.bodyEncoding===void 0?`the full body is inlined in the result's .body field`:`the full body is inlined base64-encoded in the result's .body field`:e.error}function Pp(e,t,n){let r=kp(e,t);return r===void 0?Mp(e,n):{...jp(n),bodyPath:r}}function Fp(e,t,n){let r=Ap(e);if(n===void 0)return r.complete?{body:r.decoded}:Pp(e,t,r);try{A(n,e,{mode:384})}catch(i){let a=Pp(e,t,r),o=`--output ${n}: ${ks(i)}`;return`bodyPath`in a?{...a,error:`${o}; the full body was saved to ${a.bodyPath}`}:{...a,error:`${o}; ${Np(a)}`}}return{...jp(r),bodyPath:n}}function Ip(e){return{intentId:e.intentId,amountAtomicUsdc:e.requirements.amount,payTo:e.requirements.payTo,network:e.requirements.network}}function Lp(e){let t=e?.replaceAll(/[\p{C}\s]/gu,` `).replaceAll(/ {2,}/g,` `).trim();return t!==void 0&&t.length>0?t:void 0}function Rp(e,t){pp(e,`payment-signature`)&&X(`--header cannot set PAYMENT-SIGNATURE; the payment loop attaches it after paying`),mp(e,t)}const zp=Q({url:Z({description:`The paywalled URL to fetch (an x402 v2 endpoint)`,required:!0,schema:d.pipe(d.string(),d.url())}),account:Z({description:`Source wallet account id the payment draws from`,required:!0,schema:$s}),maxAmount:Z({description:`Refuse challenges above this USD amount (decimal string, e.g. 0.25). Policy limits still apply server-side.`,schema:d.pipe(d.string(),d.regex(/^\d+(\.\d{1,6})?$/))}),method:Bs({description:`HTTP method for the request`,choices:[`GET`,`POST`]}),data:Z({description:`Request body. Use @path to read a file or @- for stdin. Implies POST and a JSON content type unless overridden.`}),contentType:Z({description:`Content-Type header for the request body (default application/json when --data is set)`}),output:Z({description:`Write the full response body to this file (must be a regular file; written for any HTTP status — check .status). Without it .body is capped at 4000 characters; longer or non-UTF-8 bodies are saved to a file (path reported in .bodyPath)`}),header:Rs({description:`Request header as "Name: Value" (repeatable, like curl -H); sent on the initial request and the paid retry`,schema:fp}),profile:Xs,json:Zs}),Bp=c({meta:{name:`x402`,description:`Fetch a URL, paying its x402 (HTTP 402) challenge via USDC`},args:zp.args,async run({args:e,rawArgs:t}){let n=zp.parse(e,t),r=n.method??(n.data===void 0?`GET`:`POST`);n.data!==void 0&&r!==`POST`&&X(`--data cannot be sent with --method ${r}; a body requires POST`),n.contentType!==void 0&&n.data===void 0&&X(`--content-type has no effect without --data`),Rp(n.header,n.contentType);let i=n.output===void 0?void 0:Ep(n.output),a=n.data===void 0?void 0:lp(n.data),o=hp(n.header,n.contentType,a);await $(n)(async e=>{let t,s=cp(e,{accountId:n.account,...n.maxAmount!==void 0&&{maxAtomicAmount:dp(n.maxAmount)},onPayment:e=>{t=e}}),c;try{c=await s(n.url,{method:r,...a!==void 0&&{body:a},...o!==void 0&&{headers:o}})}catch(e){if(e instanceof ap)throw Error(bp(e.intentId,n.profile),{cause:e});if(e instanceof rp)return{status:null,paid:!0,retryFailed:!0,payment:Ip(e.receipt),error:e.message};if(e instanceof ep){let t=e.requiredNetworks.map(e=>_p(e)??e);return{status:null,paid:!1,retryFailed:!1,networkMismatch:{account:e.accountId,requiredNetworks:t,requiredNetworkIds:[...e.requiredNetworks]},error:`${e.message}. Re-run with --account set to a wallet account on ${t.join(` or `)} (your account ids are in \`catena accounts list${yp(n.profile)}\`).`}}if(e instanceof tp){let t=Lp(e.serviceName),r=e.requiredRail?.network??_p(e.network)??e.network,i=t!==void 0&&t.length<=40?t:void 0,a=xp(e.payTo,r,i,n.profile),o=t===void 0?``:` The endpoint calls itself "${t.length>40?`${t.slice(0,40)}…`:t}" (unverified) — rename it if that is not a service you recognize.`;return{status:null,paid:!1,retryFailed:!1,counterpartyNotFound:{payTo:e.payTo,network:r,networkId:e.network,...e.requiredRail!==void 0&&{requiredRail:e.requiredRail},createCommand:a,nameIsPlaceholder:i===void 0,...t!==void 0&&{serviceName:t}},error:`${e.message}. Add it, then re-run:\n ${a}\n(counterparty creation may require approval per your policy)${o}`}}if(e instanceof np)return{status:null,paid:!1,retryFailed:!1,approvalPending:{intentId:e.intentId,expiresAt:e.expiresAt,reasons:[...e.reasons]},error:e.message};throw e}let l={status:c.status,paid:t!==void 0,retryFailed:!1,...t!==void 0&&{payment:Ip(t)}},u;try{u=Buffer.from(await c.arrayBuffer())}catch(e){let r=t===void 0?``:`; the payment settled — re-read the PAYMENT-SIGNATURE with \`catena intents get ${t.intentId}${yp(n.profile)}\` to retry manually`;return{...l,error:`failed to read the response body: ${ks(e)}${r}`}}return{...l,...Fp(u,t?.intentId,i)}},{exitCode:e=>+(`error`in e)})}}),Vp=d.object({version:d.literal(1),result:d.literal(`latest-version`),latestVersion:d.string(),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Hp=d.object({version:d.literal(1),result:d.literal(`fetch-failure`),checkedAt:d.pipe(d.string(),d.isoTimestamp())}),Up=d.variant(`result`,[Vp,Hp]),Wp=d.object({"dist-tags":d.object({latest:d.string()})}),Gp=`cache`;function Kp(){return te(hl(),Gp,`cli-version.json`)}function qp(e){return new URL(encodeURIComponent(e),`https://registry.npmjs.org/`).href}function Jp(e){try{let t=JSON.parse(T(e,`utf8`)),n=d.safeParse(Up,t);return n.success?n.output:void 0}catch{return}}function Yp(e){let t=Jp(e);if(!t)return;let n=Date.parse(t.checkedAt);if(!Number.isFinite(n))return;let r=Date.now()-n,i=t.result===`fetch-failure`?36e5:864e5;if(!(r<0||r>=i))return t}function Xp(e){try{return!C(e)||k(e).isFile()}catch{return!1}}function Zp(e){let t=Sp(hl(),Gp);if(t===void 0||!Xp(e))return!1;let n=te(t,`.cli-version-check-${g(6).toString(`hex`)}.tmp`);try{return A(n,``,{encoding:`utf8`,mode:384}),O(n,{force:!0}),!0}catch{try{O(n,{force:!0})}catch{}return!1}}function Qp(e,t){if(Sp(hl(),Gp)===void 0)return!1;try{let n=`${e}.${g(6).toString(`hex`)}.tmp`;return A(n,`${JSON.stringify({version:1,...t,checkedAt:new Date().toISOString()},null,2)}\n`,{encoding:`utf8`,mode:384}),D(n,e),!0}catch{return!1}}async function $p(e){let t=new AbortController,n=setTimeout(()=>t.abort(),750);n.unref();try{let n=await fetch(qp(e.packageName),{headers:{accept:`application/json`},signal:t.signal});if(!n.ok)return;let r=await n.json(),i=d.safeParse(Wp,r);return i.success?i.output[`dist-tags`].latest:void 0}catch{return}finally{clearTimeout(n)}}function em(e){let t=ae.valid(e.currentVersion),n=ae.valid(e.latestVersion);t!==null&&n!==null&&ae.gt(n,t)&&console.error(`A newer ${e.packageName} version is available: ${n} (current ${t}).`)}async function tm({packageName:e,currentVersion:t}){let n=Kp(),r=Yp(n);if(r?.result===`latest-version`){em({packageName:e,currentVersion:t,latestVersion:r.latestVersion});return}if(r?.result===`fetch-failure`||!Zp(n))return;let i=await $p({packageName:e});if(i===void 0){Qp(n,{result:`fetch-failure`});return}Qp(n,{result:`latest-version`,latestVersion:i}),em({packageName:e,currentVersion:t,latestVersion:i})}const nm=[{command:`link`,from:`--bank-url`,to:`--api-url`},{command:`link`,from:`--bankUrl`,to:`--api-url`}];function rm(e){return e.find(e=>!e.startsWith(`-`))??null}function im(e,t){let n=nm.find(({command:n,from:r})=>n===t&&(e===r||e.startsWith(`${r}=`)));return n===void 0?null:{to:n.to+e.slice(n.from.length),notice:`${n.from} is deprecated; use ${n.to}`}}function am(e){let t=e.indexOf(`--`),n=t===-1?e.length:t,r=e.slice(0,n),i=rm(r),a=r.map(e=>({token:e,rename:im(e,i)}));return{rawArgs:[...a.map(({token:e,rename:t})=>t?.to??e),...e.slice(n)],notices:a.flatMap(({rename:e})=>e===null?[]:[e.notice])}}async function om(e){return typeof e==`function`?await e():await e}async function sm(e){return typeof e==`function`?await e():await e}async function cm(e){return typeof e==`function`?await e():await e}async function lm(e,t,n=[]){if(e===t)return n;let r=await cm(e.subCommands??{});return(await Promise.all(Object.entries(r).map(async([e,r])=>lm(await om(r),t,[...n,e])))).find(e=>e!==void 0)}async function um(e,t){if(!e||!t||t.length<2)return e;let n=await sm(e.meta??{});return{...e,meta:{...n,name:t.slice(0,-1).join(` `)}}}function dm(e){return async(t,n)=>{let r=await l(t,await um(n,await lm(e,t)));console.log(`${r}\n`)}}function fm({shouldCheckCliVersionFreshness:e}){return c({meta:{name:`catena`,version:oe,description:`Catena CLI`},async setup({rawArgs:t}){e&&t.length!==0&&await tm({packageName:P,currentVersion:oe})},subCommands:{link:Yd,unlink:jf,profiles:wf,whoami:Nf,policy:mf,accounts:Au,intents:fd,send:Ef,transfer:Of,mpp:()=>import(`./mpp-DDG3E9du.mjs`).then(e=>e.mppCommand),x402:Bp,counterparties:ed,feedback:ad,guide:sd}})}const pm=fm({shouldCheckCliVersionFreshness:!0});fm({shouldCheckCliVersionFreshness:!1});function mm(e){let t=am(e);for(let e of t.notices)console.error(e);return[...t.rawArgs]}function hm(){u(pm,{rawArgs:mm(process.argv.slice(2)),showUsage:dm(pm)})}hm();export{ps as A,Rs as C,Xs as D,Zs as E,Ba as M,he as N,X as O,Bs as S,Q as T,Lf as _,xp as a,$ as b,fp as c,lp as d,dp as f,Rf as g,Bf as h,hp as i,vs as j,ks as k,yp as l,Hf as m,Ep as n,pp as o,Vf as p,mp as r,_p as s,Fp as t,bp as u,If as v,Z as w,$s as x,Pf as y};