Files
NostrCounter/dist/assets/ndk-40656944.js
2025-07-19 09:31:12 +02:00

82 lines
360 KiB
JavaScript

var Ge=Object.defineProperty;var Ke=(n,e,t)=>e in n?Ge(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var g=(n,e,t)=>(Ke(n,typeof e!="symbol"?e+"":e,t),t);var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var lib$1={},types={};Object.defineProperty(types,"__esModule",{value:!0});var ee={},taskCollection$1={},taskCollection={},utils$1={};Object.defineProperty(utils$1,"__esModule",{value:!0});utils$1._fast_remove_single=void 0;function _fast_remove_single(n,e){e!==-1&&(e===0?n.shift():e===n.length-1?n.length=n.length-1:n.splice(e,1))}utils$1._fast_remove_single=_fast_remove_single;var bakeCollection={};(function(exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.bakeCollectionVariadic=exports.bakeCollectionAwait=exports.bakeCollection=exports.BAKED_EMPTY_FUNC=void 0,exports.BAKED_EMPTY_FUNC=function(){};var FORLOOP_FALLBACK=1500;function generateArgsDefCode(n){var e="";if(n===0)return e;for(var t=0;t<n-1;++t)e+="arg"+String(t)+", ";return e+="arg"+String(n-1),e}function generateBodyPartsCode(n,e){for(var t="",r="",s=0;s<e;++s)t+="var f".concat(s," = collection[").concat(s,`];
`),r+="f".concat(s,"(").concat(n,`)
`);return{funcDefCode:t,funcCallCode:r}}function generateBodyPartsVariadicCode(n){for(var e="",t="",r=0;r<n;++r)e+="var f".concat(r," = collection[").concat(r,`];
`),t+="f".concat(r,`.apply(undefined, arguments)
`);return{funcDefCode:e,funcCallCode:t}}function bakeCollection(collection,fixedArgsNum){if(collection.length===0)return exports.BAKED_EMPTY_FUNC;if(collection.length===1)return collection[0];var funcFactoryCode;if(collection.length<FORLOOP_FALLBACK){var argsDefCode=generateArgsDefCode(fixedArgsNum),_a=generateBodyPartsCode(argsDefCode,collection.length),funcDefCode=_a.funcDefCode,funcCallCode=_a.funcCallCode;funcFactoryCode=`(function(collection) {
`.concat(funcDefCode,`
collection = undefined;
return (function(`).concat(argsDefCode,`) {
`).concat(funcCallCode,`
});
})`)}else{var argsDefCode=generateArgsDefCode(fixedArgsNum);collection.length%10===0?funcFactoryCode=`(function(collection) {
return (function(`.concat(argsDefCode,`) {
for (var i = 0; i < collection.length; i += 10) {
collection[i](`).concat(argsDefCode,`);
collection[i+1](`).concat(argsDefCode,`);
collection[i+2](`).concat(argsDefCode,`);
collection[i+3](`).concat(argsDefCode,`);
collection[i+4](`).concat(argsDefCode,`);
collection[i+5](`).concat(argsDefCode,`);
collection[i+6](`).concat(argsDefCode,`);
collection[i+7](`).concat(argsDefCode,`);
collection[i+8](`).concat(argsDefCode,`);
collection[i+9](`).concat(argsDefCode,`);
}
});
})`):collection.length%4===0?funcFactoryCode=`(function(collection) {
return (function(`.concat(argsDefCode,`) {
for (var i = 0; i < collection.length; i += 4) {
collection[i](`).concat(argsDefCode,`);
collection[i+1](`).concat(argsDefCode,`);
collection[i+2](`).concat(argsDefCode,`);
collection[i+3](`).concat(argsDefCode,`);
}
});
})`):collection.length%3===0?funcFactoryCode=`(function(collection) {
return (function(`.concat(argsDefCode,`) {
for (var i = 0; i < collection.length; i += 3) {
collection[i](`).concat(argsDefCode,`);
collection[i+1](`).concat(argsDefCode,`);
collection[i+2](`).concat(argsDefCode,`);
}
});
})`):funcFactoryCode=`(function(collection) {
return (function(`.concat(argsDefCode,`) {
for (var i = 0; i < collection.length; ++i) {
collection[i](`).concat(argsDefCode,`);
}
});
})`)}{var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}}exports.bakeCollection=bakeCollection;function bakeCollectionAwait(collection,fixedArgsNum){if(collection.length===0)return exports.BAKED_EMPTY_FUNC;if(collection.length===1)return collection[0];var funcFactoryCode;if(collection.length<FORLOOP_FALLBACK){var argsDefCode=generateArgsDefCode(fixedArgsNum),_a=generateBodyPartsCode(argsDefCode,collection.length),funcDefCode=_a.funcDefCode,funcCallCode=_a.funcCallCode;funcFactoryCode=`(function(collection) {
`.concat(funcDefCode,`
collection = undefined;
return (function(`).concat(argsDefCode,`) {
return Promise.all([ `).concat(funcCallCode,` ]);
});
})`)}else{var argsDefCode=generateArgsDefCode(fixedArgsNum);funcFactoryCode=`(function(collection) {
return (function(`.concat(argsDefCode,`) {
var promises = Array(collection.length);
for (var i = 0; i < collection.length; ++i) {
promises[i] = collection[i](`).concat(argsDefCode,`);
}
return Promise.all(promises);
});
})`)}{var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}}exports.bakeCollectionAwait=bakeCollectionAwait;function bakeCollectionVariadic(collection){if(collection.length===0)return exports.BAKED_EMPTY_FUNC;if(collection.length===1)return collection[0];var funcFactoryCode;if(collection.length<FORLOOP_FALLBACK){var _a=generateBodyPartsVariadicCode(collection.length),funcDefCode=_a.funcDefCode,funcCallCode=_a.funcCallCode;funcFactoryCode=`(function(collection) {
`.concat(funcDefCode,`
collection = undefined;
return (function() {
`).concat(funcCallCode,`
});
})`)}else funcFactoryCode=`(function(collection) {
return (function() {
for (var i = 0; i < collection.length; ++i) {
collection[i].apply(undefined, arguments);
}
});
})`;{var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}}exports.bakeCollectionVariadic=bakeCollectionVariadic})(bakeCollection);var __spreadArray$1=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(taskCollection,"__esModule",{value:!0});taskCollection.TaskCollection=void 0;var utils_1$1=utils$1,bake_collection_1=bakeCollection;function push_norebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++}function push_rebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function removeLast_norebuild(n){this.length!==0&&(this.length===1?this._tasks===n&&(this.length=0):((0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length))}function removeLast_rebuild(n){if(this.length!==0){if(this.length===1)if(this._tasks===n&&(this.length=0),this.firstEmitBuildStrategy){this.call=bake_collection_1.BAKED_EMPTY_FUNC;return}else{this.rebuild();return}else(0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}}function insert_norebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length)}function insert_rebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length),this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function rebuild_noawait(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollection)(this._tasks,this.argsNum)}function rebuild_await(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollectionAwait)(this._tasks,this.argsNum)}function rebuild_on_first_call(){this.rebuild(),this.call.apply(void 0,arguments)}var TaskCollection=function(){function n(e,t,r,s){t===void 0&&(t=!0),r===void 0&&(r=null),s===void 0&&(s=!1),this.awaitTasks=s,this.call=bake_collection_1.BAKED_EMPTY_FUNC,this.argsNum=e,this.firstEmitBuildStrategy=!0,s?this.rebuild=rebuild_await.bind(this):this.rebuild=rebuild_noawait.bind(this),this.setAutoRebuild(t),r?typeof r=="function"?(this._tasks=r,this.length=1):(this._tasks=r,this.length=r.length):(this._tasks=null,this.length=0),t&&this.rebuild()}return n}();taskCollection.TaskCollection=TaskCollection;function fastClear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function clear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function growArgsNum(n){this.argsNum<n&&(this.argsNum=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}function setAutoRebuild(n){n?(this.push=push_rebuild.bind(this),this.insert=insert_rebuild.bind(this),this.removeLast=removeLast_rebuild.bind(this)):(this.push=push_norebuild.bind(this),this.insert=insert_norebuild.bind(this),this.removeLast=removeLast_norebuild.bind(this))}function tasksAsArray(){return this.length===0?[]:this.length===1?[this._tasks]:this._tasks}function setTasks(n){n.length===0?(this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC):n.length===1?(this.length=1,this.call=n[0],this._tasks=n[0]):(this.length=n.length,this._tasks=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}TaskCollection.prototype.fastClear=fastClear;TaskCollection.prototype.clear=clear;TaskCollection.prototype.growArgsNum=growArgsNum;TaskCollection.prototype.setAutoRebuild=setAutoRebuild;TaskCollection.prototype.tasksAsArray=tasksAsArray;TaskCollection.prototype.setTasks=setTasks;(function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var c=Object.getOwnPropertyDescriptor(s,o);(!c||("get"in c?!s.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,c)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(taskCollection,n)})(taskCollection$1);var utils={};Object.defineProperty(utils,"__esModule",{value:!0});utils.nullObj=void 0;function nullObj(){var n={};return n.__proto__=null,n}utils.nullObj=nullObj;var __spreadArray=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(ee,"__esModule",{value:!0});ee.EventEmitter=void 0;var task_collection_1=taskCollection$1,utils_1=utils$1,utils_2=utils;function emit(n,e,t,r,s,o){var a=this.events[n];if(a){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{for(var c=new Array(a.argsNum),l=0,f=c.length;l<f;++l)c[l]=arguments[l+1];a.call.apply(void 0,c)}return!0}return!1}function emitHasOnce(n,e,t,r,s,o){var a=this.events[n],c;if(a!==void 0){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{c=new Array(a.argsNum);for(var l=0,f=c.length;l<f;++l)c[l]=arguments[l+1];a.call.apply(void 0,c)}}var h=this.onceEvents[n];if(h){if(typeof h=="function")if(this.onceEvents[n]=void 0,arguments.length<6)h(e,t,r,s,o);else{if(c===void 0){c=new Array(arguments.length-1);for(var l=0,f=c.length;l<f;++l)c[l]=arguments[l+1]}h.apply(void 0,c)}else{var u=h;if(this.onceEvents[n]=void 0,arguments.length<6)for(var l=0;l<u.length;++l)u[l](e,t,r,s,o);else{if(c===void 0){c=new Array(arguments.length-1);for(var l=0,f=c.length;l<f;++l)c[l]=arguments[l+1]}for(var l=0;l<u.length;++l)u[l].apply(void 0,c)}}return!0}return a!==void 0}var EventEmitter=function(){function n(){this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set,this.maxListeners=1/0}return Object.defineProperty(n.prototype,"_eventsCount",{get:function(){return this.eventNames().length},enumerable:!1,configurable:!0}),n}();ee.EventEmitter=EventEmitter;function once(n,e){switch(this.emit===emit&&(this.emit=emitHasOnce),typeof this.onceEvents[n]){case"undefined":this.onceEvents[n]=e,typeof n=="symbol"&&this._symbolKeys.add(n);break;case"function":this.onceEvents[n]=[this.onceEvents[n],e];break;case"object":this.onceEvents[n].push(e)}return this}function addListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return r?(r.push(e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))):(this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeListener(n,e){var t=this.events[n];t&&t.removeLast(e);var r=this.onceEvents[n];return r&&(typeof r=="function"?this.onceEvents[n]=void 0:typeof r=="object"&&(r.length===1&&r[0]===e?this.onceEvents[n]=void 0:(0,utils_1._fast_remove_single)(r,r.lastIndexOf(e)))),this}function addListenerBound(n,e,t,r){t===void 0&&(t=this),r===void 0&&(r=e.length),this.boundFuncs||(this.boundFuncs=new Map);var s=e.bind(t);return this.boundFuncs.set(e,s),this.addListener(n,s,r)}function removeListenerBound(n,e){var t,r,s=(t=this.boundFuncs)===null||t===void 0?void 0:t.get(e);return(r=this.boundFuncs)===null||r===void 0||r.delete(e),this.removeListener(n,s)}function hasListeners(n){return this.events[n]&&!!this.events[n].length}function prependListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return!r||!(r instanceof task_collection_1.TaskCollection)?(r=this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)):(r.insert(0,e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))),this}function prependOnceListener(n,e){this.emit===emit&&(this.emit=emitHasOnce);var t=this.onceEvents[n];return t?typeof t!="object"?(this.onceEvents[n]=[e,t],typeof n=="symbol"&&this._symbolKeys.add(n)):(t.unshift(e),this.maxListeners!==1/0&&this.maxListeners<=t.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" once event!'))):(this.onceEvents[n]=[e],typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeAllListeners(n){return n===void 0?(this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set):(this.events[n]=void 0,this.onceEvents[n]=void 0,typeof n=="symbol"&&this._symbolKeys.delete(n)),this}function setMaxListeners(n){return this.maxListeners=n,this}function getMaxListeners(){return this.maxListeners}function listeners(n){return this.emit===emit?this.events[n]?this.events[n].tasksAsArray().slice():[]:this.events[n]&&this.onceEvents[n]?__spreadArray(__spreadArray([],this.events[n].tasksAsArray(),!0),typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n],!0):this.events[n]?this.events[n].tasksAsArray():this.onceEvents[n]?typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n]:[]}function eventNames(){var n=this;if(this.emit===emit){var e=Object.keys(this.events);return __spreadArray(__spreadArray([],e,!0),Array.from(this._symbolKeys),!0).filter(function(r){return r in n.events&&n.events[r]&&n.events[r].length})}else{var e=Object.keys(this.events).filter(function(s){return n.events[s]&&n.events[s].length}),t=Object.keys(this.onceEvents).filter(function(s){return n.onceEvents[s]&&n.onceEvents[s].length});return __spreadArray(__spreadArray(__spreadArray([],e,!0),t,!0),Array.from(this._symbolKeys).filter(function(s){return s in n.events&&n.events[s]&&n.events[s].length||s in n.onceEvents&&n.onceEvents[s]&&n.onceEvents[s].length}),!0)}}function listenerCount(n){return this.emit===emit?this.events[n]&&this.events[n].length||0:(this.events[n]&&this.events[n].length||0)+(this.onceEvents[n]&&this.onceEvents[n].length||0)}EventEmitter.prototype.emit=emit;EventEmitter.prototype.on=addListener;EventEmitter.prototype.once=once;EventEmitter.prototype.addListener=addListener;EventEmitter.prototype.removeListener=removeListener;EventEmitter.prototype.addListenerBound=addListenerBound;EventEmitter.prototype.removeListenerBound=removeListenerBound;EventEmitter.prototype.hasListeners=hasListeners;EventEmitter.prototype.prependListener=prependListener;EventEmitter.prototype.prependOnceListener=prependOnceListener;EventEmitter.prototype.off=removeListener;EventEmitter.prototype.removeAllListeners=removeAllListeners;EventEmitter.prototype.setMaxListeners=setMaxListeners;EventEmitter.prototype.getMaxListeners=getMaxListeners;EventEmitter.prototype.listeners=listeners;EventEmitter.prototype.eventNames=eventNames;EventEmitter.prototype.listenerCount=listenerCount;(function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var c=Object.getOwnPropertyDescriptor(s,o);(!c||("get"in c?!s.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,c)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(types,n),t(ee,n)})(lib$1);var browser={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var n=1e3,e=n*60,t=e*60,r=t*24,s=r*7,o=r*365.25;ms=function(h,u){u=u||{};var p=typeof h;if(p==="string"&&h.length>0)return a(h);if(p==="number"&&isFinite(h))return u.long?l(h):c(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function a(h){if(h=String(h),!(h.length>100)){var u=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(u){var p=parseFloat(u[1]),y=(u[2]||"ms").toLowerCase();switch(y){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*r;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function c(h){var u=Math.abs(h);return u>=r?Math.round(h/r)+"d":u>=t?Math.round(h/t)+"h":u>=e?Math.round(h/e)+"m":u>=n?Math.round(h/n)+"s":h+"ms"}function l(h){var u=Math.abs(h);return u>=r?f(h,u,r,"day"):u>=t?f(h,u,t,"hour"):u>=e?f(h,u,e,"minute"):u>=n?f(h,u,n,"second"):h+" ms"}function f(h,u,p,y){var b=u>=p*1.5;return Math.round(h/p)+" "+y+(b?"s":"")}return ms}function setup(n){t.debug=t,t.default=t,t.coerce=l,t.disable=a,t.enable=s,t.enabled=c,t.humanize=requireMs(),t.destroy=f,Object.keys(n).forEach(h=>{t[h]=n[h]}),t.names=[],t.skips=[],t.formatters={};function e(h){let u=0;for(let p=0;p<h.length;p++)u=(u<<5)-u+h.charCodeAt(p),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(h){let u,p=null,y,b;function m(...k){if(!m.enabled)return;const R=m,B=Number(new Date),D=B-(u||B);R.diff=D,R.prev=u,R.curr=B,u=B,k[0]=t.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let U=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(C,M)=>{if(C==="%%")return"%";U++;const F=t.formatters[M];if(typeof F=="function"){const O=k[U];C=F.call(R,O),k.splice(U,1),U--}return C}),t.formatArgs.call(R,k),(R.log||t.log).apply(R,k)}return m.namespace=h,m.useColors=t.useColors(),m.color=t.selectColor(h),m.extend=r,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(y!==t.namespaces&&(y=t.namespaces,b=t.enabled(h)),b),set:k=>{p=k}}),typeof t.init=="function"&&t.init(m),m}function r(h,u){const p=t(this.namespace+(typeof u>"u"?":":u)+h);return p.log=this.log,p}function s(h){t.save(h),t.namespaces=h,t.names=[],t.skips=[];const u=(typeof h=="string"?h:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const p of u)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(h,u){let p=0,y=0,b=-1,m=0;for(;p<h.length;)if(y<u.length&&(u[y]===h[p]||u[y]==="*"))u[y]==="*"?(b=y,m=p,y++):(p++,y++);else if(b!==-1)y=b+1,m++,p=m;else return!1;for(;y<u.length&&u[y]==="*";)y++;return y===u.length}function a(){const h=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),h}function c(h){for(const u of t.skips)if(o(h,u))return!1;for(const u of t.names)if(o(h,u))return!0;return!1}function l(h){return h instanceof Error?h.stack||h.message:h}function f(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var common=setup;(function(n,e){e.formatArgs=r,e.save=s,e.load=o,e.useColors=t,e.storage=a(),e.destroy=(()=>{let l=!1;return()=>{l||(l=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let l;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(l=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(l[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(l){if(l[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+l[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const f="color: "+this.color;l.splice(1,0,f,"color: inherit");let h=0,u=0;l[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(h++,p==="%c"&&(u=h))}),l.splice(u,0,f)}e.log=console.debug||console.log||(()=>{});function s(l){try{l?e.storage.setItem("debug",l):e.storage.removeItem("debug")}catch{}}function o(){let l;try{l=e.storage.getItem("debug")||e.storage.getItem("DEBUG")}catch{}return!l&&typeof process<"u"&&"env"in process&&(l={}.DEBUG),l}function a(){try{return localStorage}catch{}}n.exports=common(e);const{formatters:c}=n.exports;c.j=function(l){try{return JSON.stringify(l)}catch(f){return"[UnexpectedJSONParseError]: "+f.message}}})(browser,browser.exports);var browserExports=browser.exports;const createDebug2=getDefaultExportFromCjs(browserExports);function number$2(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes$2(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash$1(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(n.outputLen),number$2(n.blockLen)}function exists$1(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output$1(n,e){bytes$2(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const crypto$2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$2=n=>n instanceof Uint8Array,createView$2=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$2=(n,e)=>n<<32-e|n>>>e,isLE$2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$2)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$3(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$2(n){if(typeof n=="string"&&(n=utf8ToBytes$3(n)),!u8a$2(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$3(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$2(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$2=class{clone(){return this._cloneInto()}};function wrapConstructor$1(n){const e=r=>n().update(toBytes$2(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$2(n=32){if(crypto$2&&typeof crypto$2.getRandomValues=="function")return crypto$2.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$2(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),c=Number(t&o),l=r?4:0,f=r?0:4;n.setUint32(e+l,a,r),n.setUint32(e+f,c,r)}let SHA2$1=class extends Hash$2{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$2(this.buffer)}update(e){exists$1(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$2(e);const o=e.length;for(let a=0;a<o;){const c=Math.min(s-this.pos,o-a);if(c===s){const l=createView$2(e);for(;s<=o-a;a+=s)this.process(l,a);continue}r.set(e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){exists$1(this),output$1(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let u=a;u<s;u++)t[u]=0;setBigUint64$2(r,s-8,BigInt(this.length*8),o),this.process(r,0);const c=createView$2(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=l/4,h=this.get();if(f>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,h[u],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:c}=this;return e.length=s,e.pos=c,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}};const Chi$2=(n,e,t)=>n&e^~n&t,Maj$2=(n,e,t)=>n&e^n&t^e&t,SHA256_K$2=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$2=new Uint32Array(64);let SHA256$2=class extends SHA2$1{constructor(){super(64,32,8,!1),this.A=IV$1[0]|0,this.B=IV$1[1]|0,this.C=IV$1[2]|0,this.D=IV$1[3]|0,this.E=IV$1[4]|0,this.F=IV$1[5]|0,this.G=IV$1[6]|0,this.H=IV$1[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:c,H:l}=this;return[e,t,r,s,o,a,c,l]}set(e,t,r,s,o,a,c,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=c|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W$2[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=SHA256_W$2[u-15],y=SHA256_W$2[u-2],b=rotr$2(p,7)^rotr$2(p,18)^p>>>3,m=rotr$2(y,17)^rotr$2(y,19)^y>>>10;SHA256_W$2[u]=m+SHA256_W$2[u-7]+b+SHA256_W$2[u-16]|0}let{A:r,B:s,C:o,D:a,E:c,F:l,G:f,H:h}=this;for(let u=0;u<64;u++){const p=rotr$2(c,6)^rotr$2(c,11)^rotr$2(c,25),y=h+p+Chi$2(c,l,f)+SHA256_K$2[u]+SHA256_W$2[u]|0,m=(rotr$2(r,2)^rotr$2(r,13)^rotr$2(r,22))+Maj$2(r,s,o)|0;h=f,f=l,l=c,c=a+y|0,a=o,o=s,s=r,r=y+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,l=l+this.F|0,f=f+this.G|0,h=h+this.H|0,this.set(r,s,o,a,c,l,f,h)}roundClean(){SHA256_W$2.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const sha256$3=wrapConstructor$1(()=>new SHA256$2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$9=BigInt(0),_1n$9=BigInt(1),_2n$5=BigInt(2),u8a$1=n=>n instanceof Uint8Array,hexes$2=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$2(n){if(!u8a$1(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$2[n[t]];return e}function numberToHexUnpadded$1(n){const e=n.toString(16);return e.length&1?`0${e}`:e}function hexToNumber$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return BigInt(n===""?"0":`0x${n}`)}function hexToBytes$2(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function bytesToNumberBE$1(n){return hexToNumber$1(bytesToHex$2(n))}function bytesToNumberLE$1(n){if(!u8a$1(n))throw new Error("Uint8Array expected");return hexToNumber$1(bytesToHex$2(Uint8Array.from(n).reverse()))}function numberToBytesBE$1(n,e){return hexToBytes$2(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE$1(n,e){return numberToBytesBE$1(n,e).reverse()}function numberToVarBytesBE(n){return hexToBytes$2(numberToHexUnpadded$1(n))}function ensureBytes$1(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes$2(e)}catch(o){throw new Error(`${n} must be valid hex string, got "${e}". Cause: ${o}`)}else if(u8a$1(e))r=Uint8Array.from(e);else throw new Error(`${n} must be hex string or Uint8Array`);const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(`${n} expected ${t} bytes, got ${s}`);return r}function concatBytes$2(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$1(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}function equalBytes$1(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function utf8ToBytes$2(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function bitLen$1(n){let e;for(e=0;n>_0n$9;n>>=_1n$9,e+=1);return e}function bitGet(n,e){return n>>BigInt(e)&_1n$9}const bitSet=(n,e,t)=>n|(t?_1n$9:_0n$9)<<BigInt(e),bitMask$1=n=>(_2n$5<<BigInt(n-1))-_1n$9,u8n=n=>new Uint8Array(n),u8fr=n=>Uint8Array.from(n);function createHmacDrbg$1(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=u8n(n),s=u8n(n),o=0;const a=()=>{r.fill(1),s.fill(0),o=0},c=(...u)=>t(s,r,...u),l=(u=u8n())=>{s=c(u8fr([0]),u),r=c(),u.length!==0&&(s=c(u8fr([1]),u),r=c())},f=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let u=0;const p=[];for(;u<e;){r=c();const y=r.slice();p.push(y),u+=r.length}return concatBytes$2(...p)};return(u,p)=>{a(),l(u);let y;for(;!(y=p(f()));)l();return a(),y}}const validatorFns={bigint:n=>typeof n=="bigint",function:n=>typeof n=="function",boolean:n=>typeof n=="boolean",string:n=>typeof n=="string",stringOrUint8Array:n=>typeof n=="string"||n instanceof Uint8Array,isSafeInteger:n=>Number.isSafeInteger(n),array:n=>Array.isArray(n),field:(n,e)=>e.Fp.isValid(n),hash:n=>typeof n=="function"&&Number.isSafeInteger(n.outputLen)};function validateObject(n,e,t={}){const r=(s,o,a)=>{const c=validatorFns[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);const l=n[s];if(!(a&&l===void 0)&&!c(l,n))throw new Error(`Invalid param ${String(s)}=${l} (${typeof l}), expected ${o}`)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(t))r(s,o,!0);return n}const ut=Object.freeze(Object.defineProperty({__proto__:null,bitGet,bitLen:bitLen$1,bitMask:bitMask$1,bitSet,bytesToHex:bytesToHex$2,bytesToNumberBE:bytesToNumberBE$1,bytesToNumberLE:bytesToNumberLE$1,concatBytes:concatBytes$2,createHmacDrbg:createHmacDrbg$1,ensureBytes:ensureBytes$1,equalBytes:equalBytes$1,hexToBytes:hexToBytes$2,hexToNumber:hexToNumber$1,numberToBytesBE:numberToBytesBE$1,numberToBytesLE:numberToBytesLE$1,numberToHexUnpadded:numberToHexUnpadded$1,numberToVarBytesBE,utf8ToBytes:utf8ToBytes$2,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$8=BigInt(0),_1n$8=BigInt(1),_2n$4=BigInt(2),_3n$3=BigInt(3),_4n$2=BigInt(4),_5n$1=BigInt(5),_8n$1=BigInt(8);BigInt(9);BigInt(16);function mod$1(n,e){const t=n%e;return t>=_0n$8?t:e+t}function pow(n,e,t){if(t<=_0n$8||e<_0n$8)throw new Error("Expected power/modulo > 0");if(t===_1n$8)return _0n$8;let r=_1n$8;for(;e>_0n$8;)e&_1n$8&&(r=r*n%t),n=n*n%t,e>>=_1n$8;return r}function pow2$1(n,e,t){let r=n;for(;e-- >_0n$8;)r*=r,r%=t;return r}function invert$1(n,e){if(n===_0n$8||e<=_0n$8)throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);let t=mod$1(n,e),r=e,s=_0n$8,o=_1n$8;for(;t!==_0n$8;){const c=r/t,l=r%t,f=s-o*c;r=t,t=l,s=o,o=f}if(r!==_1n$8)throw new Error("invert: does not exist");return mod$1(s,e)}function tonelliShanks$1(n){const e=(n-_1n$8)/_2n$4;let t,r,s;for(t=n-_1n$8,r=0;t%_2n$4===_0n$8;t/=_2n$4,r++);for(s=_2n$4;s<n&&pow(s,e,n)!==n-_1n$8;s++);if(r===1){const a=(n+_1n$8)/_4n$2;return function(l,f){const h=l.pow(f,a);if(!l.eql(l.sqr(h),f))throw new Error("Cannot find square root");return h}}const o=(t+_1n$8)/_2n$4;return function(c,l){if(c.pow(l,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let f=r,h=c.pow(c.mul(c.ONE,s),t),u=c.pow(l,o),p=c.pow(l,t);for(;!c.eql(p,c.ONE);){if(c.eql(p,c.ZERO))return c.ZERO;let y=1;for(let m=c.sqr(p);y<f&&!c.eql(m,c.ONE);y++)m=c.sqr(m);const b=c.pow(h,_1n$8<<BigInt(f-y-1));h=c.sqr(b),u=c.mul(u,b),p=c.mul(p,h),f=y}return u}}function FpSqrt$1(n){if(n%_4n$2===_3n$3){const e=(n+_1n$8)/_4n$2;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(n%_8n$1===_5n$1){const e=(n-_5n$1)/_8n$1;return function(r,s){const o=r.mul(s,_2n$4),a=r.pow(o,e),c=r.mul(s,a),l=r.mul(r.mul(c,_2n$4),a),f=r.mul(c,r.sub(l,r.ONE));if(!r.eql(r.sqr(f),s))throw new Error("Cannot find square root");return f}}return tonelliShanks$1(n)}const FIELD_FIELDS$1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField$1(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=FIELD_FIELDS$1.reduce((r,s)=>(r[s]="function",r),e);return validateObject(n,t)}function FpPow$1(n,e,t){if(t<_0n$8)throw new Error("Expected power > 0");if(t===_0n$8)return n.ONE;if(t===_1n$8)return e;let r=n.ONE,s=e;for(;t>_0n$8;)t&_1n$8&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$8;return r}function FpInvertBatch$1(n,e){const t=new Array(e.length),r=e.reduce((o,a,c)=>n.is0(a)?o:(t[c]=o,n.mul(o,a)),n.ONE),s=n.inv(r);return e.reduceRight((o,a,c)=>n.is0(a)?o:(t[c]=n.mul(o,t[c]),n.mul(o,a)),s),t}function nLength$1(n,e){const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field$1(n,e,t=!1,r={}){if(n<=_0n$8)throw new Error(`Expected Field ORDER > 0, got ${n}`);const{nBitLength:s,nByteLength:o}=nLength$1(n,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const a=FpSqrt$1(n),c=Object.freeze({ORDER:n,BITS:s,BYTES:o,MASK:bitMask$1(s),ZERO:_0n$8,ONE:_1n$8,create:l=>mod$1(l,n),isValid:l=>{if(typeof l!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof l}`);return _0n$8<=l&&l<n},is0:l=>l===_0n$8,isOdd:l=>(l&_1n$8)===_1n$8,neg:l=>mod$1(-l,n),eql:(l,f)=>l===f,sqr:l=>mod$1(l*l,n),add:(l,f)=>mod$1(l+f,n),sub:(l,f)=>mod$1(l-f,n),mul:(l,f)=>mod$1(l*f,n),pow:(l,f)=>FpPow$1(c,l,f),div:(l,f)=>mod$1(l*invert$1(f,n),n),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>invert$1(l,n),sqrt:r.sqrt||(l=>a(c,l)),invertBatch:l=>FpInvertBatch$1(c,l),cmov:(l,f,h)=>h?f:l,toBytes:l=>t?numberToBytesLE$1(l,o):numberToBytesBE$1(l,o),fromBytes:l=>{if(l.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${l.length}`);return t?bytesToNumberLE$1(l):bytesToNumberBE$1(l)}});return Object.freeze(c)}function getFieldBytesLength$1(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength$1(n){const e=getFieldBytesLength$1(n);return e+Math.ceil(e/2)}function mapHashToField$1(n,e,t=!1){const r=n.length,s=getFieldBytesLength$1(e),o=getMinHashLength$1(e);if(r<16||r<o||r>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${r}`);const a=t?bytesToNumberBE$1(n):bytesToNumberLE$1(n),c=mod$1(a,e-_1n$8)+_1n$8;return t?numberToBytesLE$1(c,s):numberToBytesBE$1(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$7=BigInt(0),_1n$7=BigInt(1);function wNAF$1(n,e){const t=(s,o)=>{const a=o.negate();return s?a:o},r=s=>{const o=Math.ceil(e/s)+1,a=2**(s-1);return{windows:o,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,o){let a=n.ZERO,c=s;for(;o>_0n$7;)o&_1n$7&&(a=a.add(c)),c=c.double(),o>>=_1n$7;return a},precomputeWindow(s,o){const{windows:a,windowSize:c}=r(o),l=[];let f=s,h=f;for(let u=0;u<a;u++){h=f,l.push(h);for(let p=1;p<c;p++)h=h.add(f),l.push(h);f=h.double()}return l},wNAF(s,o,a){const{windows:c,windowSize:l}=r(s);let f=n.ZERO,h=n.BASE;const u=BigInt(2**s-1),p=2**s,y=BigInt(s);for(let b=0;b<c;b++){const m=b*l;let k=Number(a&u);a>>=y,k>l&&(k-=p,a+=_1n$7);const R=m,B=m+Math.abs(k)-1,D=b%2!==0,U=k<0;k===0?h=h.add(t(D,o[R])):f=f.add(t(U,o[B]))}return{p:f,f:h}},wNAFCached(s,o,a,c){const l=s._WINDOW_SIZE||1;let f=o.get(s);return f||(f=this.precomputeWindow(s,l),l!==1&&o.set(s,c(f))),this.wNAF(l,f,a)}}}function validateBasic(n){return validateField$1(n.Fp),validateObject(n,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength$1(n.n,n.nBitLength),...n,p:n.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(n){const e=validateBasic(n);validateObject(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER$1={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(n){const{Err:e}=DER$1;if(n.length<2||n[0]!==2)throw new e("Invalid signature integer tag");const t=n[1],r=n.subarray(2,t+2);if(!t||r.length!==t)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:b2n(r),l:n.subarray(t+2)}},toSig(n){const{Err:e}=DER$1,t=typeof n=="string"?h2b(n):n;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let r=t.length;if(r<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:s,l:o}=DER$1._parseInt(t.subarray(2)),{d:a,l:c}=DER$1._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:a}},hexFromSig(n){const e=f=>Number.parseInt(f[0],16)&8?"00"+f:f,t=f=>{const h=f.toString(16);return h.length&1?`0${h}`:h},r=e(t(n.s)),s=e(t(n.r)),o=r.length/2,a=s.length/2,c=t(o),l=t(a);return`30${t(a+o+4)}02${l}${s}02${c}${r}`}},_0n$6=BigInt(0),_1n$6=BigInt(1);BigInt(2);const _3n$2=BigInt(3);BigInt(4);function weierstrassPoints(n){const e=validatePointOpts(n),{Fp:t}=e,r=e.toBytes||((b,m,k)=>{const R=m.toAffine();return concatBytes$2(Uint8Array.from([4]),t.toBytes(R.x),t.toBytes(R.y))}),s=e.fromBytes||(b=>{const m=b.subarray(1),k=t.fromBytes(m.subarray(0,t.BYTES)),R=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:k,y:R}});function o(b){const{a:m,b:k}=e,R=t.sqr(b),B=t.mul(R,b);return t.add(t.add(B,t.mul(b,m)),k)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(b){return typeof b=="bigint"&&_0n$6<b&&b<e.n}function c(b){if(!a(b))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function l(b){const{allowedPrivateKeyLengths:m,nByteLength:k,wrapPrivateKey:R,n:B}=e;if(m&&typeof b!="bigint"){if(b instanceof Uint8Array&&(b=bytesToHex$2(b)),typeof b!="string"||!m.includes(b.length))throw new Error("Invalid key");b=b.padStart(k*2,"0")}let D;try{D=typeof b=="bigint"?b:bytesToNumberBE$1(ensureBytes$1("private key",b,k))}catch{throw new Error(`private key must be ${k} bytes, hex or bigint, not ${typeof b}`)}return R&&(D=mod$1(D,B)),c(D),D}const f=new Map;function h(b){if(!(b instanceof u))throw new Error("ProjectivePoint expected")}class u{constructor(m,k,R){if(this.px=m,this.py=k,this.pz=R,m==null||!t.isValid(m))throw new Error("x required");if(k==null||!t.isValid(k))throw new Error("y required");if(R==null||!t.isValid(R))throw new Error("z required")}static fromAffine(m){const{x:k,y:R}=m||{};if(!m||!t.isValid(k)||!t.isValid(R))throw new Error("invalid affine point");if(m instanceof u)throw new Error("projective point not allowed");const B=D=>t.eql(D,t.ZERO);return B(k)&&B(R)?u.ZERO:new u(k,R,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const k=t.invertBatch(m.map(R=>R.pz));return m.map((R,B)=>R.toAffine(k[B])).map(u.fromAffine)}static fromHex(m){const k=u.fromAffine(s(ensureBytes$1("pointHex",m)));return k.assertValidity(),k}static fromPrivateKey(m){return u.BASE.multiply(l(m))}_setWindowSize(m){this._WINDOW_SIZE=m,f.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:m,y:k}=this.toAffine();if(!t.isValid(m)||!t.isValid(k))throw new Error("bad point: x or y not FE");const R=t.sqr(k),B=o(m);if(!t.eql(R,B))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){h(m);const{px:k,py:R,pz:B}=this,{px:D,py:U,pz:H}=m,C=t.eql(t.mul(k,H),t.mul(D,B)),M=t.eql(t.mul(R,H),t.mul(U,B));return C&&M}negate(){return new u(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:k}=e,R=t.mul(k,_3n$2),{px:B,py:D,pz:U}=this;let H=t.ZERO,C=t.ZERO,M=t.ZERO,F=t.mul(B,B),O=t.mul(D,D),$=t.mul(U,U),E=t.mul(B,D);return E=t.add(E,E),M=t.mul(B,U),M=t.add(M,M),H=t.mul(m,M),C=t.mul(R,$),C=t.add(H,C),H=t.sub(O,C),C=t.add(O,C),C=t.mul(H,C),H=t.mul(E,H),M=t.mul(R,M),$=t.mul(m,$),E=t.sub(F,$),E=t.mul(m,E),E=t.add(E,M),M=t.add(F,F),F=t.add(M,F),F=t.add(F,$),F=t.mul(F,E),C=t.add(C,F),$=t.mul(D,U),$=t.add($,$),F=t.mul($,E),H=t.sub(H,F),M=t.mul($,O),M=t.add(M,M),M=t.add(M,M),new u(H,C,M)}add(m){h(m);const{px:k,py:R,pz:B}=this,{px:D,py:U,pz:H}=m;let C=t.ZERO,M=t.ZERO,F=t.ZERO;const O=e.a,$=t.mul(e.b,_3n$2);let E=t.mul(k,D),_=t.mul(R,U),T=t.mul(B,H),N=t.add(k,R),x=t.add(D,U);N=t.mul(N,x),x=t.add(E,_),N=t.sub(N,x),x=t.add(k,B);let w=t.add(D,H);return x=t.mul(x,w),w=t.add(E,T),x=t.sub(x,w),w=t.add(R,B),C=t.add(U,H),w=t.mul(w,C),C=t.add(_,T),w=t.sub(w,C),F=t.mul(O,x),C=t.mul($,T),F=t.add(C,F),C=t.sub(_,F),F=t.add(_,F),M=t.mul(C,F),_=t.add(E,E),_=t.add(_,E),T=t.mul(O,T),x=t.mul($,x),_=t.add(_,T),T=t.sub(E,T),T=t.mul(O,T),x=t.add(x,T),E=t.mul(_,x),M=t.add(M,E),E=t.mul(w,x),C=t.mul(N,C),C=t.sub(C,E),E=t.mul(N,_),F=t.mul(w,F),F=t.add(F,E),new u(C,M,F)}subtract(m){return this.add(m.negate())}is0(){return this.equals(u.ZERO)}wNAF(m){return y.wNAFCached(this,f,m,k=>{const R=t.invertBatch(k.map(B=>B.pz));return k.map((B,D)=>B.toAffine(R[D])).map(u.fromAffine)})}multiplyUnsafe(m){const k=u.ZERO;if(m===_0n$6)return k;if(c(m),m===_1n$6)return this;const{endo:R}=e;if(!R)return y.unsafeLadder(this,m);let{k1neg:B,k1:D,k2neg:U,k2:H}=R.splitScalar(m),C=k,M=k,F=this;for(;D>_0n$6||H>_0n$6;)D&_1n$6&&(C=C.add(F)),H&_1n$6&&(M=M.add(F)),F=F.double(),D>>=_1n$6,H>>=_1n$6;return B&&(C=C.negate()),U&&(M=M.negate()),M=new u(t.mul(M.px,R.beta),M.py,M.pz),C.add(M)}multiply(m){c(m);let k=m,R,B;const{endo:D}=e;if(D){const{k1neg:U,k1:H,k2neg:C,k2:M}=D.splitScalar(k);let{p:F,f:O}=this.wNAF(H),{p:$,f:E}=this.wNAF(M);F=y.constTimeNegate(U,F),$=y.constTimeNegate(C,$),$=new u(t.mul($.px,D.beta),$.py,$.pz),R=F.add($),B=O.add(E)}else{const{p:U,f:H}=this.wNAF(k);R=U,B=H}return u.normalizeZ([R,B])[0]}multiplyAndAddUnsafe(m,k,R){const B=u.BASE,D=(H,C)=>C===_0n$6||C===_1n$6||!H.equals(B)?H.multiplyUnsafe(C):H.multiply(C),U=D(this,k).add(D(m,R));return U.is0()?void 0:U}toAffine(m){const{px:k,py:R,pz:B}=this,D=this.is0();m==null&&(m=D?t.ONE:t.inv(B));const U=t.mul(k,m),H=t.mul(R,m),C=t.mul(B,m);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(C,t.ONE))throw new Error("invZ was invalid");return{x:U,y:H}}isTorsionFree(){const{h:m,isTorsionFree:k}=e;if(m===_1n$6)return!0;if(k)return k(u,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:k}=e;return m===_1n$6?this:k?k(u,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),r(u,this,m)}toHex(m=!0){return bytesToHex$2(this.toRawBytes(m))}}u.BASE=new u(e.Gx,e.Gy,t.ONE),u.ZERO=new u(t.ZERO,t.ONE,t.ZERO);const p=e.nBitLength,y=wNAF$1(u,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:u,normPrivateKeyToScalar:l,weierstrassEquation:o,isWithinCurveOrder:a}}function validateOpts(n){const e=validateBasic(n);return validateObject(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function weierstrass$1(n){const e=validateOpts(n),{Fp:t,n:r}=e,s=t.BYTES+1,o=2*t.BYTES+1;function a(x){return _0n$6<x&&x<t.ORDER}function c(x){return mod$1(x,r)}function l(x){return invert$1(x,r)}const{ProjectivePoint:f,normPrivateKeyToScalar:h,weierstrassEquation:u,isWithinCurveOrder:p}=weierstrassPoints({...e,toBytes(x,w,v){const S=w.toAffine(),A=t.toBytes(S.x),L=concatBytes$2;return v?L(Uint8Array.from([w.hasEvenY()?2:3]),A):L(Uint8Array.from([4]),A,t.toBytes(S.y))},fromBytes(x){const w=x.length,v=x[0],S=x.subarray(1);if(w===s&&(v===2||v===3)){const A=bytesToNumberBE$1(S);if(!a(A))throw new Error("Point is not on curve");const L=u(A);let I=t.sqrt(L);const P=(I&_1n$6)===_1n$6;return(v&1)===1!==P&&(I=t.neg(I)),{x:A,y:I}}else if(w===o&&v===4){const A=t.fromBytes(S.subarray(0,t.BYTES)),L=t.fromBytes(S.subarray(t.BYTES,2*t.BYTES));return{x:A,y:L}}else throw new Error(`Point of length ${w} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),y=x=>bytesToHex$2(numberToBytesBE$1(x,e.nByteLength));function b(x){const w=r>>_1n$6;return x>w}function m(x){return b(x)?c(-x):x}const k=(x,w,v)=>bytesToNumberBE$1(x.slice(w,v));class R{constructor(w,v,S){this.r=w,this.s=v,this.recovery=S,this.assertValidity()}static fromCompact(w){const v=e.nByteLength;return w=ensureBytes$1("compactSignature",w,v*2),new R(k(w,0,v),k(w,v,2*v))}static fromDER(w){const{r:v,s:S}=DER$1.toSig(ensureBytes$1("DER",w));return new R(v,S)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(w){return new R(this.r,this.s,w)}recoverPublicKey(w){const{r:v,s:S,recovery:A}=this,L=M(ensureBytes$1("msgHash",w));if(A==null||![0,1,2,3].includes(A))throw new Error("recovery id invalid");const I=A===2||A===3?v+e.n:v;if(I>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const P=A&1?"03":"02",V=f.fromHex(P+y(I)),z=l(I),W=c(-L*z),q=c(S*z),j=f.BASE.multiplyAndAddUnsafe(V,W,q);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new R(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes$2(this.toDERHex())}toDERHex(){return DER$1.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes$2(this.toCompactHex())}toCompactHex(){return y(this.r)+y(this.s)}}const B={isValidPrivateKey(x){try{return h(x),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const x=getMinHashLength$1(e.n);return mapHashToField$1(e.randomBytes(x),e.n)},precompute(x=8,w=f.BASE){return w._setWindowSize(x),w.multiply(BigInt(3)),w}};function D(x,w=!0){return f.fromPrivateKey(x).toRawBytes(w)}function U(x){const w=x instanceof Uint8Array,v=typeof x=="string",S=(w||v)&&x.length;return w?S===s||S===o:v?S===2*s||S===2*o:x instanceof f}function H(x,w,v=!0){if(U(x))throw new Error("first arg must be private key");if(!U(w))throw new Error("second arg must be public key");return f.fromHex(w).multiply(h(x)).toRawBytes(v)}const C=e.bits2int||function(x){const w=bytesToNumberBE$1(x),v=x.length*8-e.nBitLength;return v>0?w>>BigInt(v):w},M=e.bits2int_modN||function(x){return c(C(x))},F=bitMask$1(e.nBitLength);function O(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(_0n$6<=x&&x<F))throw new Error(`bigint expected < 2^${e.nBitLength}`);return numberToBytesBE$1(x,e.nByteLength)}function $(x,w,v=E){if(["recovered","canonical"].some(Z=>Z in v))throw new Error("sign() legacy options not supported");const{hash:S,randomBytes:A}=e;let{lowS:L,prehash:I,extraEntropy:P}=v;L==null&&(L=!0),x=ensureBytes$1("msgHash",x),I&&(x=ensureBytes$1("prehashed msgHash",S(x)));const V=M(x),z=h(w),W=[O(z),O(V)];if(P!=null){const Z=P===!0?A(t.BYTES):P;W.push(ensureBytes$1("extraEntropy",Z))}const q=concatBytes$2(...W),j=V;function G(Z){const Y=C(Z);if(!p(Y))return;const te=l(Y),J=f.BASE.multiply(Y).toAffine(),K=c(J.x);if(K===_0n$6)return;const Q=c(te*c(j+K*z));if(Q===_0n$6)return;let Se=(J.x===K?0:2)|Number(J.y&_1n$6),Ne=Q;return L&&b(Q)&&(Ne=m(Q),Se^=1),new R(K,Ne,Se)}return{seed:q,k2sig:G}}const E={lowS:e.lowS,prehash:!1},_={lowS:e.lowS,prehash:!1};function T(x,w,v=E){const{seed:S,k2sig:A}=$(x,w,v),L=e;return createHmacDrbg$1(L.hash.outputLen,L.nByteLength,L.hmac)(S,A)}f.BASE._setWindowSize(8);function N(x,w,v,S=_){var J;const A=x;if(w=ensureBytes$1("msgHash",w),v=ensureBytes$1("publicKey",v),"strict"in S)throw new Error("options.strict was renamed to lowS");const{lowS:L,prehash:I}=S;let P,V;try{if(typeof A=="string"||A instanceof Uint8Array)try{P=R.fromDER(A)}catch(K){if(!(K instanceof DER$1.Err))throw K;P=R.fromCompact(A)}else if(typeof A=="object"&&typeof A.r=="bigint"&&typeof A.s=="bigint"){const{r:K,s:Q}=A;P=new R(K,Q)}else throw new Error("PARSE");V=f.fromHex(v)}catch(K){if(K.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(L&&P.hasHighS())return!1;I&&(w=e.hash(w));const{r:z,s:W}=P,q=M(w),j=l(W),G=c(q*j),Z=c(z*j),Y=(J=f.BASE.multiplyAndAddUnsafe(V,G,Z))==null?void 0:J.toAffine();return Y?c(Y.x)===z:!1}return{CURVE:e,getPublicKey:D,getSharedSecret:H,sign:T,verify:N,ProjectivePoint:f,Signature:R,utils:B}}let HMAC$2=class extends Hash$2{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hash$1(e);const r=toBytes$2(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return exists$1(this),this.iHash.update(e),this}digestInto(e){exists$1(this),bytes$2(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=c,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$2=(n,e,t)=>new HMAC$2(n,e).update(t).digest();hmac$2.create=(n,e)=>new HMAC$2(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(n){return{hash:n,hmac:(e,...t)=>hmac$2(n,e,concatBytes$3(...t)),randomBytes:randomBytes$2}}function createCurve$1(n,e){const t=r=>weierstrass$1({...n,...getHash(r)});return Object.freeze({...t(e),create:t})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$5=BigInt(1),_2n$3=BigInt(2),divNearest$1=(n,e)=>(n+e/_2n$3)/e;function sqrtMod$1(n){const e=secp256k1P,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),c=BigInt(44),l=BigInt(88),f=n*n*n%e,h=f*f*n%e,u=pow2$1(h,t,e)*h%e,p=pow2$1(u,t,e)*h%e,y=pow2$1(p,_2n$3,e)*f%e,b=pow2$1(y,s,e)*y%e,m=pow2$1(b,o,e)*b%e,k=pow2$1(m,c,e)*m%e,R=pow2$1(k,l,e)*k%e,B=pow2$1(R,c,e)*m%e,D=pow2$1(B,t,e)*h%e,U=pow2$1(D,a,e)*b%e,H=pow2$1(U,r,e)*f%e,C=pow2$1(H,_2n$3,e);if(!Fp.eql(Fp.sqr(C),n))throw new Error("Cannot find square root");return C}const Fp=Field$1(secp256k1P,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1$1=createCurve$1({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:n=>{const e=secp256k1N,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_1n$5*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,a=BigInt("0x100000000000000000000000000000000"),c=divNearest$1(o*n,e),l=divNearest$1(-r*n,e);let f=mod$1(n-c*t-l*s,e),h=mod$1(-c*r-l*o,e);const u=f>a,p=h>a;if(u&&(f=e-f),p&&(h=e-h),f>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+n);return{k1neg:u,k1:f,k2neg:p,k2:h}}}},sha256$3),_0n$5=BigInt(0),fe=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1P,ge=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1N,TAGGED_HASH_PREFIXES$1={};function taggedHash$1(n,...e){let t=TAGGED_HASH_PREFIXES$1[n];if(t===void 0){const r=sha256$3(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes$2(r,r),TAGGED_HASH_PREFIXES$1[n]=t}return sha256$3(concatBytes$2(t,...e))}const pointToBytes$1=n=>n.toRawBytes(!0).slice(1),numTo32b$1=n=>numberToBytesBE$1(n,32),modP$1=n=>mod$1(n,secp256k1P),modN$1=n=>mod$1(n,secp256k1N),Point$1=secp256k1$1.ProjectivePoint,GmulAdd=(n,e,t)=>Point$1.BASE.multiplyAndAddUnsafe(n,e,t);function schnorrGetExtPubKey$1(n){let e=secp256k1$1.utils.normPrivateKeyToScalar(n),t=Point$1.fromPrivateKey(e);return{scalar:t.hasEvenY()?e:modN$1(-e),bytes:pointToBytes$1(t)}}function lift_x$1(n){if(!fe(n))throw new Error("bad x: need 0 < x < p");const e=modP$1(n*n),t=modP$1(e*n+BigInt(7));let r=sqrtMod$1(t);r%_2n$3!==_0n$5&&(r=modP$1(-r));const s=new Point$1(n,r,_1n$5);return s.assertValidity(),s}function challenge$1(...n){return modN$1(bytesToNumberBE$1(taggedHash$1("BIP0340/challenge",...n)))}function schnorrGetPublicKey$1(n){return schnorrGetExtPubKey$1(n).bytes}function schnorrSign$1(n,e,t=randomBytes$2(32)){const r=ensureBytes$1("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey$1(e),a=ensureBytes$1("auxRand",t,32),c=numTo32b$1(o^bytesToNumberBE$1(taggedHash$1("BIP0340/aux",a))),l=taggedHash$1("BIP0340/nonce",c,s,r),f=modN$1(bytesToNumberBE$1(l));if(f===_0n$5)throw new Error("sign failed: k is zero");const{bytes:h,scalar:u}=schnorrGetExtPubKey$1(f),p=challenge$1(h,s,r),y=new Uint8Array(64);if(y.set(h,0),y.set(numTo32b$1(modN$1(u+p*o)),32),!schnorrVerify$1(y,r,s))throw new Error("sign: Invalid signature produced");return y}function schnorrVerify$1(n,e,t){const r=ensureBytes$1("signature",n,64),s=ensureBytes$1("message",e),o=ensureBytes$1("publicKey",t,32);try{const a=lift_x$1(bytesToNumberBE$1(o)),c=bytesToNumberBE$1(r.subarray(0,32));if(!fe(c))return!1;const l=bytesToNumberBE$1(r.subarray(32,64));if(!ge(l))return!1;const f=challenge$1(numTo32b$1(c),pointToBytes$1(a),s),h=GmulAdd(a,l,modN$1(-f));return!(!h||!h.hasEvenY()||h.toAffine().x!==c)}catch{return!1}}const schnorr$1=(()=>({getPublicKey:schnorrGetPublicKey$1,sign:schnorrSign$1,verify:schnorrVerify$1,utils:{randomPrivateKey:secp256k1$1.utils.randomPrivateKey,lift_x:lift_x$1,pointToBytes:pointToBytes$1,numberToBytesBE:numberToBytesBE$1,bytesToNumberBE:bytesToNumberBE$1,taggedHash:taggedHash$1,mod:mod$1}}))(),crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a=n=>n instanceof Uint8Array,createView$1=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$1=(n,e)=>n<<32-e|n>>>e,isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$1)throw new Error("Non little-endian hardware is not supported");const hexes$1=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$1(n){if(!u8a(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$1[n[t]];return e}function hexToBytes$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function utf8ToBytes$1(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$1(n){if(typeof n=="string"&&(n=utf8ToBytes$1(n)),!u8a(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$1(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$1=class{clone(){return this._cloneInto()}};function wrapConstructor(n){const e=r=>n().update(toBytes$1(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$1(n=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function number$1(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool$1(n){if(typeof n!="boolean")throw new Error(`Expected boolean, not ${n}`)}function bytes$1(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$1(n.outputLen),number$1(n.blockLen)}function exists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output(n,e){bytes$1(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const assert={number:number$1,bool:bool$1,bytes:bytes$1,hash,exists,output};function setBigUint64$1(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),c=Number(t&o),l=r?4:0,f=r?0:4;n.setUint32(e+l,a,r),n.setUint32(e+f,c,r)}class SHA2 extends Hash$1{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$1(this.buffer)}update(e){assert.exists(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$1(e);const o=e.length;for(let a=0;a<o;){const c=Math.min(s-this.pos,o-a);if(c===s){const l=createView$1(e);for(;s<=o-a;a+=s)this.process(l,a);continue}r.set(e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){assert.exists(this),assert.output(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let u=a;u<s;u++)t[u]=0;setBigUint64$1(r,s-8,BigInt(this.length*8),o),this.process(r,0);const c=createView$1(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=l/4,h=this.get();if(f>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,h[u],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:c}=this;return e.length=s,e.pos=c,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}}const Chi$1=(n,e,t)=>n&e^~n&t,Maj$1=(n,e,t)=>n&e^n&t^e&t,SHA256_K$1=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$1=new Uint32Array(64);let SHA256$1=class extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:c,H:l}=this;return[e,t,r,s,o,a,c,l]}set(e,t,r,s,o,a,c,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=c|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W$1[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=SHA256_W$1[u-15],y=SHA256_W$1[u-2],b=rotr$1(p,7)^rotr$1(p,18)^p>>>3,m=rotr$1(y,17)^rotr$1(y,19)^y>>>10;SHA256_W$1[u]=m+SHA256_W$1[u-7]+b+SHA256_W$1[u-16]|0}let{A:r,B:s,C:o,D:a,E:c,F:l,G:f,H:h}=this;for(let u=0;u<64;u++){const p=rotr$1(c,6)^rotr$1(c,11)^rotr$1(c,25),y=h+p+Chi$1(c,l,f)+SHA256_K$1[u]+SHA256_W$1[u]|0,m=(rotr$1(r,2)^rotr$1(r,13)^rotr$1(r,22))+Maj$1(r,s,o)|0;h=f,f=l,l=c,c=a+y|0,a=o,o=s,s=r,r=y+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,l=l+this.F|0,f=f+this.G|0,h=h+this.H|0,this.set(r,s,o,a,c,l,f,h)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class SHA224 extends SHA256$1{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const sha256$2=wrapConstructor(()=>new SHA256$1);wrapConstructor(()=>new SHA224);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function assertNumber(n){if(!Number.isSafeInteger(n))throw new Error(`Wrong integer: ${n}`)}function chain$1(...n){const e=(s,o)=>a=>s(o(a)),t=Array.from(n).reverse().reduce((s,o)=>s?e(s,o.encode):o.encode,void 0),r=n.reduce((s,o)=>s?e(s,o.decode):o.decode,void 0);return{encode:t,decode:r}}function alphabet$1(n){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(t=>{if(assertNumber(t),t<0||t>=n.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${n.length})`);return n[t]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(t=>{if(typeof t!="string")throw new Error(`alphabet.decode: not string element=${t}`);const r=n.indexOf(t);if(r===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${n}`);return r})}}}function join$1(n=""){if(typeof n!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let t of e)if(typeof t!="string")throw new Error(`join.encode: non-string input=${t}`);return e.join(n)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(n)}}}function padding(n,e="="){if(assertNumber(n),typeof e!="string")throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of t)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;t.length*n%8;)t.push(e);return t},decode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let s of t)if(typeof s!="string")throw new Error(`padding.decode: non-string input=${s}`);let r=t.length;if(r*n%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&t[r-1]===e;r--)if(!((r-1)*n%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,r)}}}function normalize$1(n){if(typeof n!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>n(e)}}function convertRadix(n,e,t){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(t<2)throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);if(!Array.isArray(n))throw new Error("convertRadix: data should be array");if(!n.length)return[];let r=0;const s=[],o=Array.from(n);for(o.forEach(a=>{if(assertNumber(a),a<0||a>=e)throw new Error(`Wrong integer: ${a}`)});;){let a=0,c=!0;for(let l=r;l<o.length;l++){const f=o[l],h=e*a+f;if(!Number.isSafeInteger(h)||e*a/e!==a||h-f!==e*a)throw new Error("convertRadix: carry overflow");if(a=h%t,o[l]=Math.floor(h/t),!Number.isSafeInteger(o[l])||o[l]*t+a!==h)throw new Error("convertRadix: carry overflow");if(c)o[l]?c=!1:r=l;else continue}if(s.push(a),c)break}for(let a=0;a<n.length-1&&n[a]===0;a++)s.push(0);return s.reverse()}const gcd$1=(n,e)=>e?gcd$1(e,n%e):n,radix2carry$1=(n,e)=>n+(e-gcd$1(n,e));function convertRadix2$1(n,e,t,r){if(!Array.isArray(n))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(radix2carry$1(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${radix2carry$1(e,t)}`);let s=0,o=0;const a=2**t-1,c=[];for(const l of n){if(assertNumber(l),l>=2**e)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<<e|l,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)c.push((s>>o-t&a)>>>0);s&=2**o-1}if(s=s<<t-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&s)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&c.push(s>>>0),c}function radix(n){return assertNumber(n),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(e),2**8,n)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(e,n,2**8))}}}function radix2$1(n,e=!1){if(assertNumber(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry$1(8,n)>32||radix2carry$1(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2$1(Array.from(t),8,n,!e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2$1(t,n,8,e))}}}function unsafeWrapper$1(n){if(typeof n!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return n.apply(null,e)}catch{}}}const base16=chain$1(radix2$1(4),alphabet$1("0123456789ABCDEF"),join$1("")),base32=chain$1(radix2$1(5),alphabet$1("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join$1(""));chain$1(radix2$1(5),alphabet$1("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join$1(""));chain$1(radix2$1(5),alphabet$1("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join$1(""),normalize$1(n=>n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const base64=chain$1(radix2$1(6),alphabet$1("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join$1("")),base64url=chain$1(radix2$1(6),alphabet$1("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join$1("")),genBase58=n=>chain$1(radix(58),alphabet$1(n),join$1("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11],base58xmr={encode(n){let e="";for(let t=0;t<n.length;t+=8){const r=n.subarray(t,t+8);e+=base58.encode(r).padStart(XMR_BLOCK_LEN[r.length],"1")}return e},decode(n){let e=[];for(let t=0;t<n.length;t+=11){const r=n.slice(t,t+11),s=XMR_BLOCK_LEN.indexOf(r.length),o=base58.decode(r);for(let a=0;a<o.length-s;a++)if(o[a]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(o.slice(o.length-s)))}return Uint8Array.from(e)}},BECH_ALPHABET$1=chain$1(alphabet$1("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join$1("")),POLYMOD_GENERATORS$1=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod$1(n){const e=n>>25;let t=(n&33554431)<<5;for(let r=0;r<POLYMOD_GENERATORS$1.length;r++)(e>>r&1)===1&&(t^=POLYMOD_GENERATORS$1[r]);return t}function bechChecksum$1(n,e,t=1){const r=n.length;let s=1;for(let o=0;o<r;o++){const a=n.charCodeAt(o);if(a<33||a>126)throw new Error(`Invalid prefix (${n})`);s=bech32Polymod$1(s)^a>>5}s=bech32Polymod$1(s);for(let o=0;o<r;o++)s=bech32Polymod$1(s)^n.charCodeAt(o)&31;for(let o of e)s=bech32Polymod$1(s)^o;for(let o=0;o<6;o++)s=bech32Polymod$1(s);return s^=t,BECH_ALPHABET$1.encode(convertRadix2$1([s%2**30],30,5,!1))}function genBech32$1(n){const e=n==="bech32"?1:734539939,t=radix2$1(5),r=t.decode,s=t.encode,o=unsafeWrapper$1(r);function a(h,u,p=90){if(typeof h!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof h}`);if(!Array.isArray(u)||u.length&&typeof u[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof u}`);const y=h.length+7+u.length;if(p!==!1&&y>p)throw new TypeError(`Length ${y} exceeds limit ${p}`);return h=h.toLowerCase(),`${h}1${BECH_ALPHABET$1.encode(u)}${bechChecksum$1(h,u,e)}`}function c(h,u=90){if(typeof h!="string")throw new Error(`bech32.decode input should be string, not ${typeof h}`);if(h.length<8||u!==!1&&h.length>u)throw new TypeError(`Wrong string length: ${h.length} (${h}). Expected (8..${u})`);const p=h.toLowerCase();if(h!==p&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");h=p;const y=h.lastIndexOf("1");if(y===0||y===-1)throw new Error('Letter "1" must be present between prefix and data only');const b=h.slice(0,y),m=h.slice(y+1);if(m.length<6)throw new Error("Data must be at least 6 characters long");const k=BECH_ALPHABET$1.decode(m).slice(0,-6),R=bechChecksum$1(b,k,e);if(!m.endsWith(R))throw new Error(`Invalid checksum in ${h}: expected "${R}"`);return{prefix:b,words:k}}const l=unsafeWrapper$1(c);function f(h){const{prefix:u,words:p}=c(h,!1);return{prefix:u,words:p,bytes:r(p)}}return{encode:a,decode:c,decodeToBytes:f,decodeUnsafe:l,fromWords:r,fromWordsUnsafe:o,toWords:s}}const bech32$2=genBech32$1("bech32");genBech32$1("bech32m");const utf8$1={encode:n=>new TextDecoder().decode(n),decode:n=>new TextEncoder().encode(n)},hex$1=chain$1(radix2$1(4),alphabet$1("0123456789abcdef"),join$1(""),normalize$1(n=>{if(typeof n!="string"||n.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof n} with length ${n.length}`);return n.toLowerCase()})),CODERS={utf8:utf8$1,hex:hex$1,base16,base32,base64,base64url,base58,base58xmr};`${Object.keys(CODERS).join(", ")}`;function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, not ${n}`)}function bool(n){if(typeof n!="boolean")throw new Error(`boolean expected, not ${n}`)}function isBytes$2(n){return n instanceof Uint8Array||n!=null&&typeof n=="object"&&n.constructor.name==="Uint8Array"}function bytes(n,...e){if(!isBytes$2(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${n.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u32=n=>new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)),isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function checkOpts(n,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(n,e)}function equalBytes(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}const wrapCipher=(n,e)=>(Object.assign(e,n),e),BLOCK_SIZE=16,POLY=283;function mul2(n){return n<<1^POLY&-(n>>7)}function mul(n,e){let t=0;for(;e>0;e>>=1)t^=n&-(e&1),n=mul2(n);return t}const sbox=(()=>{let n=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=mul2(r))n[t]=r;const e=new Uint8Array(256);e[0]=99;for(let t=0;t<255;t++){let r=n[255-t];r|=r<<8,e[n[t]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return e})(),invSbox=sbox.map((n,e)=>sbox.indexOf(e)),rotr32_8=n=>n<<24|n>>>8,rotl32_8=n=>n<<8|n>>>24;function genTtable(n,e){if(n.length!==256)throw new Error("Wrong sbox length");const t=new Uint32Array(256).map((f,h)=>e(n[h])),r=t.map(rotl32_8),s=r.map(rotl32_8),o=s.map(rotl32_8),a=new Uint32Array(256*256),c=new Uint32Array(256*256),l=new Uint16Array(256*256);for(let f=0;f<256;f++)for(let h=0;h<256;h++){const u=f*256+h;a[u]=t[f]^r[h],c[u]=s[f]^o[h],l[u]=n[f]<<8|n[h]}return{sbox:n,sbox2:l,T0:t,T1:r,T2:s,T3:o,T01:a,T23:c}}const tableEncoding=genTtable(sbox,n=>mul(n,3)<<24|n<<16|n<<8|mul(n,2)),tableDecoding=genTtable(invSbox,n=>mul(n,11)<<24|mul(n,13)<<16|mul(n,9)<<8|mul(n,14)),xPowers=(()=>{const n=new Uint8Array(16);for(let e=0,t=1;e<16;e++,t=mul2(t))n[e]=t;return n})();function expandKeyLE(n){bytes(n);const e=n.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:t}=tableEncoding,r=u32(n),s=r.length,o=c=>applySbox(t,c,c,c,c),a=new Uint32Array(e+28);a.set(r);for(let c=s;c<a.length;c++){let l=a[c-1];c%s===0?l=o(rotr32_8(l))^xPowers[c/s-1]:s>6&&c%s===4&&(l=o(l)),a[c]=a[c-s]^l}return a}function expandKeyDecLE(n){const e=expandKeyLE(n),t=e.slice(),r=e.length,{sbox2:s}=tableEncoding,{T0:o,T1:a,T2:c,T3:l}=tableDecoding;for(let f=0;f<r;f+=4)for(let h=0;h<4;h++)t[f+h]=e[r-f-4+h];e.fill(0);for(let f=4;f<r-4;f++){const h=t[f],u=applySbox(s,h,h,h,h);t[f]=o[u&255]^a[u>>>8&255]^c[u>>>16&255]^l[u>>>24]}return t}function apply0123(n,e,t,r,s,o){return n[t<<8&65280|r>>>8&255]^e[s>>>8&65280|o>>>24&255]}function applySbox(n,e,t,r,s){return n[e&255|t&65280]|n[r>>>16&255|s>>>16&65280]<<16}function encrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:c}=tableEncoding;let l=0;e^=n[l++],t^=n[l++],r^=n[l++],s^=n[l++];const f=n.length/4-2;for(let b=0;b<f;b++){const m=n[l++]^apply0123(a,c,e,t,r,s),k=n[l++]^apply0123(a,c,t,r,s,e),R=n[l++]^apply0123(a,c,r,s,e,t),B=n[l++]^apply0123(a,c,s,e,t,r);e=m,t=k,r=R,s=B}const h=n[l++]^applySbox(o,e,t,r,s),u=n[l++]^applySbox(o,t,r,s,e),p=n[l++]^applySbox(o,r,s,e,t),y=n[l++]^applySbox(o,s,e,t,r);return{s0:h,s1:u,s2:p,s3:y}}function decrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:c}=tableDecoding;let l=0;e^=n[l++],t^=n[l++],r^=n[l++],s^=n[l++];const f=n.length/4-2;for(let b=0;b<f;b++){const m=n[l++]^apply0123(a,c,e,s,r,t),k=n[l++]^apply0123(a,c,t,e,s,r),R=n[l++]^apply0123(a,c,r,t,e,s),B=n[l++]^apply0123(a,c,s,r,t,e);e=m,t=k,r=R,s=B}const h=n[l++]^applySbox(o,e,s,r,t),u=n[l++]^applySbox(o,t,e,s,r),p=n[l++]^applySbox(o,r,t,e,s),y=n[l++]^applySbox(o,s,r,t,e);return{s0:h,s1:u,s2:p,s3:y}}function getDst(n,e){if(!e)return new Uint8Array(n);if(bytes(e),e.length<n)throw new Error(`aes: wrong destination length, expected at least ${n}, got: ${e.length}`);return e}function validateBlockDecrypt(n){if(bytes(n),n.length%BLOCK_SIZE!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`)}function validateBlockEncrypt(n,e,t){let r=n.length;const s=r%BLOCK_SIZE;if(!e&&s!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const o=u32(n);if(e){let l=BLOCK_SIZE-s;l||(l=BLOCK_SIZE),r=r+l}const a=getDst(r,t),c=u32(a);return{b:o,o:c,out:a}}function validatePCKS(n,e){if(!e)return n;const t=n.length;if(!t)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=n[t-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const s=n.subarray(0,-r);for(let o=0;o<r;o++)if(n[t-o-1]!==r)throw new Error("aes/pcks5: wrong padding");return s}function padPCKS(n){const e=new Uint8Array(16),t=u32(e);e.set(n);const r=BLOCK_SIZE-n.length;for(let s=BLOCK_SIZE-r;s<BLOCK_SIZE;s++)e[s]=r;return t}const cbc=wrapCipher({blockSize:16,nonceLength:16},function n(e,t,r={}){bytes(e),bytes(t,16);const s=!r.disablePadding;return{encrypt:(o,a)=>{const c=expandKeyLE(e),{b:l,o:f,out:h}=validateBlockEncrypt(o,s,a),u=u32(t);let p=u[0],y=u[1],b=u[2],m=u[3],k=0;for(;k+4<=l.length;)p^=l[k+0],y^=l[k+1],b^=l[k+2],m^=l[k+3],{s0:p,s1:y,s2:b,s3:m}=encrypt$2(c,p,y,b,m),f[k++]=p,f[k++]=y,f[k++]=b,f[k++]=m;if(s){const R=padPCKS(o.subarray(k*4));p^=R[0],y^=R[1],b^=R[2],m^=R[3],{s0:p,s1:y,s2:b,s3:m}=encrypt$2(c,p,y,b,m),f[k++]=p,f[k++]=y,f[k++]=b,f[k++]=m}return c.fill(0),h},decrypt:(o,a)=>{validateBlockDecrypt(o);const c=expandKeyDecLE(e),l=u32(t),f=getDst(o.length,a),h=u32(o),u=u32(f);let p=l[0],y=l[1],b=l[2],m=l[3];for(let k=0;k+4<=h.length;){const R=p,B=y,D=b,U=m;p=h[k+0],y=h[k+1],b=h[k+2],m=h[k+3];const{s0:H,s1:C,s2:M,s3:F}=decrypt$2(c,p,y,b,m);u[k++]=H^R,u[k++]=C^B,u[k++]=M^D,u[k++]=F^U}return c.fill(0),validatePCKS(f,s)}}}),_utf8ToBytes=n=>Uint8Array.from(n.split("").map(e=>e.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);sigma32_32.slice();function rotl(n,e){return n<<e|n>>>32-e}function isAligned32(n){return n.byteOffset%4===0}const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(n,e,t,r,s,o,a,c){const l=s.length,f=new Uint8Array(BLOCK_LEN),h=u32(f),u=isAligned32(s)&&isAligned32(o),p=u?u32(s):U32_EMPTY,y=u?u32(o):U32_EMPTY;for(let b=0;b<l;a++){if(n(e,t,r,h,a,c),a>=MAX_COUNTER)throw new Error("arx: counter overflow");const m=Math.min(BLOCK_LEN,l-b);if(u&&m===BLOCK_LEN){const k=b/4;if(b%4!==0)throw new Error("arx: invalid block position");for(let R=0,B;R<BLOCK_LEN32;R++)B=k+R,y[B]=p[B]^h[R];b+=BLOCK_LEN;continue}for(let k=0,R;k<m;k++)R=b+k,o[R]=s[R]^f[k];b+=m}}function createCipher(n,e){const{allowShortKeys:t,extendNonceFn:r,counterLength:s,counterRight:o,rounds:a}=checkOpts({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return number(s),number(a),bool(o),bool(t),(c,l,f,h,u=0)=>{bytes(c),bytes(l),bytes(f);const p=f.length;if(h||(h=new Uint8Array(p)),bytes(h),number(u),u<0||u>=MAX_COUNTER)throw new Error("arx: counter overflow");if(h.length<p)throw new Error(`arx: output (${h.length}) is shorter than data (${p})`);const y=[];let b=c.length,m,k;if(b===32)m=c.slice(),y.push(m),k=sigma32_32;else if(b===16&&t)m=new Uint8Array(32),m.set(c),m.set(c,16),k=sigma16_32,y.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${b}`);isAligned32(l)||(l=l.slice(),y.push(l));const R=u32(m);if(r){if(l.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(k,R,u32(l.subarray(0,16)),R),l=l.subarray(16)}const B=16-s;if(B!==l.length)throw new Error(`arx: nonce must be ${B} or 16 bytes`);if(B!==12){const U=new Uint8Array(12);U.set(l,o?0:12-l.length),l=U,y.push(l)}const D=u32(l);for(runCipher(n,k,R,D,f,h,u,a);y.length>0;)y.pop().fill(0);return h}}function chachaCore(n,e,t,r,s,o=20){let a=n[0],c=n[1],l=n[2],f=n[3],h=e[0],u=e[1],p=e[2],y=e[3],b=e[4],m=e[5],k=e[6],R=e[7],B=s,D=t[0],U=t[1],H=t[2],C=a,M=c,F=l,O=f,$=h,E=u,_=p,T=y,N=b,x=m,w=k,v=R,S=B,A=D,L=U,I=H;for(let V=0;V<o;V+=2)C=C+$|0,S=rotl(S^C,16),N=N+S|0,$=rotl($^N,12),C=C+$|0,S=rotl(S^C,8),N=N+S|0,$=rotl($^N,7),M=M+E|0,A=rotl(A^M,16),x=x+A|0,E=rotl(E^x,12),M=M+E|0,A=rotl(A^M,8),x=x+A|0,E=rotl(E^x,7),F=F+_|0,L=rotl(L^F,16),w=w+L|0,_=rotl(_^w,12),F=F+_|0,L=rotl(L^F,8),w=w+L|0,_=rotl(_^w,7),O=O+T|0,I=rotl(I^O,16),v=v+I|0,T=rotl(T^v,12),O=O+T|0,I=rotl(I^O,8),v=v+I|0,T=rotl(T^v,7),C=C+E|0,I=rotl(I^C,16),w=w+I|0,E=rotl(E^w,12),C=C+E|0,I=rotl(I^C,8),w=w+I|0,E=rotl(E^w,7),M=M+_|0,S=rotl(S^M,16),v=v+S|0,_=rotl(_^v,12),M=M+_|0,S=rotl(S^M,8),v=v+S|0,_=rotl(_^v,7),F=F+T|0,A=rotl(A^F,16),N=N+A|0,T=rotl(T^N,12),F=F+T|0,A=rotl(A^F,8),N=N+A|0,T=rotl(T^N,7),O=O+$|0,L=rotl(L^O,16),x=x+L|0,$=rotl($^x,12),O=O+$|0,L=rotl(L^O,8),x=x+L|0,$=rotl($^x,7);let P=0;r[P++]=a+C|0,r[P++]=c+M|0,r[P++]=l+F|0,r[P++]=f+O|0,r[P++]=h+$|0,r[P++]=u+E|0,r[P++]=p+_|0,r[P++]=y+T|0,r[P++]=b+N|0,r[P++]=m+x|0,r[P++]=k+w|0,r[P++]=R+v|0,r[P++]=B+S|0,r[P++]=D+A|0,r[P++]=U+L|0,r[P++]=H+I|0}const chacha20=createCipher(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1});let HMAC$1=class extends Hash$1{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert.hash(e);const r=toBytes$1(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return assert.exists(this),this.iHash.update(e),this}digestInto(e){assert.exists(this),assert.bytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=c,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$1=(n,e,t)=>new HMAC$1(n,e).update(t).digest();hmac$1.create=(n,e)=>new HMAC$1(n,e);function extract(n,e,t){return assert.hash(n),t===void 0&&(t=new Uint8Array(n.outputLen)),hmac$1(n,toBytes$1(t),toBytes$1(e))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(n,e,t,r=32){if(assert.hash(n),assert.number(r),r>255*n.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/n.outputLen);t===void 0&&(t=EMPTY_BUFFER);const o=new Uint8Array(s*n.outputLen),a=hmac$1.create(n,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let f=0;f<s;f++)HKDF_COUNTER[0]=f+1,c.update(f===0?EMPTY_BUFFER:l).update(t).update(HKDF_COUNTER).digestInto(l),o.set(l,n.outputLen*f),a._cloneInto(c);return a.destroy(),c.destroy(),l.fill(0),HKDF_COUNTER.fill(0),o.slice(0,r)}var __defProp=Object.defineProperty,__export=(n,e)=>{for(var t in e)__defProp(n,t,{get:e[t],enumerable:!0})},verifiedSymbol=Symbol("verified"),isRecord=n=>n instanceof Object;function validateEvent(n){if(!isRecord(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!n.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){let t=n.tags[e];if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(typeof t[r]!="string")return!1}return!0}var utils_exports={};__export(utils_exports,{Queue:()=>Queue$1,QueueNode:()=>QueueNode,binarySearch:()=>binarySearch,bytesToHex:()=>bytesToHex$1,hexToBytes:()=>hexToBytes$1,insertEventIntoAscendingList:()=>insertEventIntoAscendingList,insertEventIntoDescendingList:()=>insertEventIntoDescendingList,normalizeURL:()=>normalizeURL,utf8Decoder:()=>utf8Decoder,utf8Encoder:()=>utf8Encoder});var utf8Decoder=new TextDecoder("utf-8"),utf8Encoder=new TextEncoder;function normalizeURL(n){try{n.indexOf("://")===-1&&(n="wss://"+n);let e=new URL(n);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${n}`)}}function insertEventIntoDescendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:s.created_at-e.created_at);return r||n.splice(t,0,e),n}function insertEventIntoAscendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:e.created_at-s.created_at);return r||n.splice(t,0,e),n}function binarySearch(n,e){let t=0,r=n.length-1;for(;t<=r;){const s=Math.floor((t+r)/2),o=e(n[s]);if(o===0)return[s,!0];o<0?r=s-1:t=s+1}return[t,!1]}var QueueNode=class{constructor(n){g(this,"value");g(this,"next",null);g(this,"prev",null);this.value=n}},Queue$1=class{constructor(){g(this,"first");g(this,"last");this.first=null,this.last=null}enqueue(e){const t=new QueueNode(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,this.first&&(this.first.prev=null),e.value}},JS=class{generateSecretKey(){return schnorr$1.utils.randomPrivateKey()}getPublicKey(n){return bytesToHex$1(schnorr$1.getPublicKey(n))}finalizeEvent(n,e){const t=n;return t.pubkey=bytesToHex$1(schnorr$1.getPublicKey(e)),t.id=getEventHash$1(t),t.sig=bytesToHex$1(schnorr$1.sign(getEventHash$1(t),e)),t[verifiedSymbol]=!0,t}verifyEvent(n){if(typeof n[verifiedSymbol]=="boolean")return n[verifiedSymbol];const e=getEventHash$1(n);if(e!==n.id)return n[verifiedSymbol]=!1,!1;try{const t=schnorr$1.verify(n.sig,e,n.pubkey);return n[verifiedSymbol]=t,t}catch{return n[verifiedSymbol]=!1,!1}}};function serializeEvent(n){if(!validateEvent(n))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])}function getEventHash$1(n){let e=sha256$2(utf8Encoder.encode(serializeEvent(n)));return bytesToHex$1(e)}var i=new JS,generateSecretKey=i.generateSecretKey,getPublicKey=i.getPublicKey,finalizeEvent=i.finalizeEvent,verifyEvent=i.verifyEvent,kinds_exports={};__export(kinds_exports,{Application:()=>Application,BadgeAward:()=>BadgeAward,BadgeDefinition:()=>BadgeDefinition,BlockedRelaysList:()=>BlockedRelaysList,BookmarkList:()=>BookmarkList,Bookmarksets:()=>Bookmarksets,Calendar:()=>Calendar,CalendarEventRSVP:()=>CalendarEventRSVP,ChannelCreation:()=>ChannelCreation,ChannelHideMessage:()=>ChannelHideMessage,ChannelMessage:()=>ChannelMessage,ChannelMetadata:()=>ChannelMetadata,ChannelMuteUser:()=>ChannelMuteUser,ClassifiedListing:()=>ClassifiedListing,ClientAuth:()=>ClientAuth,CommunitiesList:()=>CommunitiesList,CommunityDefinition:()=>CommunityDefinition,CommunityPostApproval:()=>CommunityPostApproval,Contacts:()=>Contacts,CreateOrUpdateProduct:()=>CreateOrUpdateProduct,CreateOrUpdateStall:()=>CreateOrUpdateStall,Curationsets:()=>Curationsets,Date:()=>Date2,DirectMessageRelaysList:()=>DirectMessageRelaysList,DraftClassifiedListing:()=>DraftClassifiedListing,DraftLong:()=>DraftLong,Emojisets:()=>Emojisets,EncryptedDirectMessage:()=>EncryptedDirectMessage,EventDeletion:()=>EventDeletion,FileMetadata:()=>FileMetadata,FileServerPreference:()=>FileServerPreference,Followsets:()=>Followsets,GenericRepost:()=>GenericRepost,Genericlists:()=>Genericlists,GiftWrap:()=>GiftWrap,HTTPAuth:()=>HTTPAuth,Handlerinformation:()=>Handlerinformation,Handlerrecommendation:()=>Handlerrecommendation,Highlights:()=>Highlights,InterestsList:()=>InterestsList,Interestsets:()=>Interestsets,JobFeedback:()=>JobFeedback,JobRequest:()=>JobRequest,JobResult:()=>JobResult,Label:()=>Label,LightningPubRPC:()=>LightningPubRPC,LiveChatMessage:()=>LiveChatMessage,LiveEvent:()=>LiveEvent,LongFormArticle:()=>LongFormArticle,Metadata:()=>Metadata,Mutelist:()=>Mutelist,NWCWalletInfo:()=>NWCWalletInfo,NWCWalletRequest:()=>NWCWalletRequest,NWCWalletResponse:()=>NWCWalletResponse,NostrConnect:()=>NostrConnect,OpenTimestamps:()=>OpenTimestamps,Pinlist:()=>Pinlist,PrivateDirectMessage:()=>PrivateDirectMessage,ProblemTracker:()=>ProblemTracker,ProfileBadges:()=>ProfileBadges,PublicChatsList:()=>PublicChatsList,Reaction:()=>Reaction,RecommendRelay:()=>RecommendRelay,RelayList:()=>RelayList,Relaysets:()=>Relaysets,Report:()=>Report,Reporting:()=>Reporting,Repost:()=>Repost,Seal:()=>Seal,SearchRelaysList:()=>SearchRelaysList,ShortTextNote:()=>ShortTextNote,Time:()=>Time,UserEmojiList:()=>UserEmojiList,UserStatuses:()=>UserStatuses,Zap:()=>Zap,ZapGoal:()=>ZapGoal,ZapRequest:()=>ZapRequest,classifyKind:()=>classifyKind,isAddressableKind:()=>isAddressableKind,isEphemeralKind:()=>isEphemeralKind,isKind:()=>isKind,isRegularKind:()=>isRegularKind,isReplaceableKind:()=>isReplaceableKind});function isRegularKind(n){return 1e3<=n&&n<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(n)}function isReplaceableKind(n){return[0,3].includes(n)||1e4<=n&&n<2e4}function isEphemeralKind(n){return 2e4<=n&&n<3e4}function isAddressableKind(n){return 3e4<=n&&n<4e4}function classifyKind(n){return isRegularKind(n)?"regular":isReplaceableKind(n)?"replaceable":isEphemeralKind(n)?"ephemeral":isAddressableKind(n)?"parameterized":"unknown"}function isKind(n,e){const t=e instanceof Array?e:[e];return validateEvent(n)&&t.includes(n.kind)||!1}var Metadata=0,ShortTextNote=1,RecommendRelay=2,Contacts=3,EncryptedDirectMessage=4,EventDeletion=5,Repost=6,Reaction=7,BadgeAward=8,Seal=13,PrivateDirectMessage=14,GenericRepost=16,ChannelCreation=40,ChannelMetadata=41,ChannelMessage=42,ChannelHideMessage=43,ChannelMuteUser=44,OpenTimestamps=1040,GiftWrap=1059,FileMetadata=1063,LiveChatMessage=1311,ProblemTracker=1971,Report=1984,Reporting=1984,Label=1985,CommunityPostApproval=4550,JobRequest=5999,JobResult=6999,JobFeedback=7e3,ZapGoal=9041,ZapRequest=9734,Zap=9735,Highlights=9802,Mutelist=1e4,Pinlist=10001,RelayList=10002,BookmarkList=10003,CommunitiesList=10004,PublicChatsList=10005,BlockedRelaysList=10006,SearchRelaysList=10007,InterestsList=10015,UserEmojiList=10030,DirectMessageRelaysList=10050,FileServerPreference=10096,NWCWalletInfo=13194,LightningPubRPC=21e3,ClientAuth=22242,NWCWalletRequest=23194,NWCWalletResponse=23195,NostrConnect=24133,HTTPAuth=27235,Followsets=3e4,Genericlists=30001,Relaysets=30002,Bookmarksets=30003,Curationsets=30004,ProfileBadges=30008,BadgeDefinition=30009,Interestsets=30015,CreateOrUpdateStall=30017,CreateOrUpdateProduct=30018,LongFormArticle=30023,DraftLong=30024,Emojisets=30030,Application=30078,LiveEvent=30311,UserStatuses=30315,ClassifiedListing=30402,DraftClassifiedListing=30403,Date2=31922,Time=31923,Calendar=31924,CalendarEventRSVP=31925,Handlerrecommendation=31989,Handlerinformation=31990,CommunityDefinition=34550;function matchFilter$1(n,e){if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(let t in n)if(t[0]==="#"){let r=t.slice(1),s=n[`#${r}`];if(s&&!e.tags.find(([o,a])=>o===t.slice(1)&&s.indexOf(a)!==-1))return!1}return!(n.since&&e.created_at<n.since||n.until&&e.created_at>n.until)}function matchFilters(n,e){for(let t=0;t<n.length;t++)if(matchFilter$1(n[t],e))return!0;return!1}var fakejson_exports={};__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});function getHex64(n,e){let t=e.length+3,r=n.indexOf(`"${e}":`)+t,s=n.slice(r).indexOf('"')+r+1;return n.slice(s,s+64)}function getInt(n,e){let t=e.length,r=n.indexOf(`"${e}":`)+t+3,s=n.slice(r),o=Math.min(s.indexOf(","),s.indexOf("}"));return parseInt(s.slice(0,o),10)}function getSubscriptionId(n){let e=n.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let t=n.slice(e+7+1).indexOf('"');if(t===-1)return null;let r=e+7+1+t,s=n.slice(r+1,80).indexOf('"');if(s===-1)return null;let o=r+1+s;return n.slice(r+1,o)}function matchEventId(n,e){return e===getHex64(n,"id")}function matchEventPubkey(n,e){return e===getHex64(n,"pubkey")}function matchEventKind(n,e){return e===getInt(n,"kind")}var nip42_exports={};__export(nip42_exports,{makeAuthEvent:()=>makeAuthEvent});function makeAuthEvent(n,e){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",n],["challenge",e]],content:""}}var _WebSocket;try{_WebSocket=WebSocket}catch{}var _WebSocket2;try{_WebSocket2=WebSocket}catch{}var nip19_exports={};__export(nip19_exports,{BECH32_REGEX:()=>BECH32_REGEX$1,Bech32MaxSize:()=>Bech32MaxSize,NostrTypeGuard:()=>NostrTypeGuard,decode:()=>decode$1,decodeNostrURI:()=>decodeNostrURI,encodeBytes:()=>encodeBytes,naddrEncode:()=>naddrEncode,neventEncode:()=>neventEncode,noteEncode:()=>noteEncode,nprofileEncode:()=>nprofileEncode,npubEncode:()=>npubEncode,nsecEncode:()=>nsecEncode});var NostrTypeGuard={isNProfile:n=>/^nprofile1[a-z\d]+$/.test(n||""),isNEvent:n=>/^nevent1[a-z\d]+$/.test(n||""),isNAddr:n=>/^naddr1[a-z\d]+$/.test(n||""),isNSec:n=>/^nsec1[a-z\d]{58}$/.test(n||""),isNPub:n=>/^npub1[a-z\d]{58}$/.test(n||""),isNote:n=>/^note1[a-z\d]+$/.test(n||""),isNcryptsec:n=>/^ncryptsec1[a-z\d]+$/.test(n||"")},Bech32MaxSize=5e3,BECH32_REGEX$1=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(n){const e=new Uint8Array(4);return e[0]=n>>24&255,e[1]=n>>16&255,e[2]=n>>8&255,e[3]=n&255,e}function decodeNostrURI(n){try{return n.startsWith("nostr:")&&(n=n.substring(6)),decode$1(n)}catch{return{type:"invalid",data:null}}}function decode$1(n){var s,o,a,c,l,f,h;let{prefix:e,words:t}=bech32$2.decode(n,Bech32MaxSize),r=new Uint8Array(bech32$2.fromWords(t));switch(e){case"nprofile":{let u=parseTLV(r);if(!((s=u[0])!=null&&s[0]))throw new Error("missing TLV 0 for nprofile");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$1(u[0][0]),relays:u[1]?u[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nevent":{let u=parseTLV(r);if(!((o=u[0])!=null&&o[0]))throw new Error("missing TLV 0 for nevent");if(u[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(u[2]&&u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(u[3]&&u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$1(u[0][0]),relays:u[1]?u[1].map(p=>utf8Decoder.decode(p)):[],author:(a=u[2])!=null&&a[0]?bytesToHex$1(u[2][0]):void 0,kind:(c=u[3])!=null&&c[0]?parseInt(bytesToHex$1(u[3][0]),16):void 0}}}case"naddr":{let u=parseTLV(r);if(!((l=u[0])!=null&&l[0]))throw new Error("missing TLV 0 for naddr");if(!((f=u[2])!=null&&f[0]))throw new Error("missing TLV 2 for naddr");if(u[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((h=u[3])!=null&&h[0]))throw new Error("missing TLV 3 for naddr");if(u[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder.decode(u[0][0]),pubkey:bytesToHex$1(u[2][0]),kind:parseInt(bytesToHex$1(u[3][0]),16),relays:u[1]?u[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:bytesToHex$1(r)};default:throw new Error(`unknown prefix ${e}`)}}function parseTLV(n){let e={},t=n;for(;t.length>0;){let r=t[0],s=t[1],o=t.slice(2,2+s);if(t=t.slice(2+s),o.length<s)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(o)}return e}function nsecEncode(n){return encodeBytes("nsec",n)}function npubEncode(n){return encodeBytes("npub",hexToBytes$1(n))}function noteEncode(n){return encodeBytes("note",hexToBytes$1(n))}function encodeBech32(n,e){let t=bech32$2.toWords(e);return bech32$2.encode(n,t,Bech32MaxSize)}function encodeBytes(n,e){return encodeBech32(n,e)}function nprofileEncode(n){let e=encodeTLV({0:[hexToBytes$1(n.pubkey)],1:(n.relays||[]).map(t=>utf8Encoder.encode(t))});return encodeBech32("nprofile",e)}function neventEncode(n){let e;n.kind!==void 0&&(e=integerToUint8Array(n.kind));let t=encodeTLV({0:[hexToBytes$1(n.id)],1:(n.relays||[]).map(r=>utf8Encoder.encode(r)),2:n.author?[hexToBytes$1(n.author)]:[],3:e?[new Uint8Array(e)]:[]});return encodeBech32("nevent",t)}function naddrEncode(n){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,n.kind,!1);let t=encodeTLV({0:[utf8Encoder.encode(n.identifier)],1:(n.relays||[]).map(r=>utf8Encoder.encode(r)),2:[hexToBytes$1(n.pubkey)],3:[new Uint8Array(e)]});return encodeBech32("naddr",t)}function encodeTLV(n){let e=[];return Object.entries(n).reverse().forEach(([t,r])=>{r.forEach(s=>{let o=new Uint8Array(s.length+2);o.set([parseInt(t)],0),o.set([s.length],1),o.set(s,2),e.push(o)})}),concatBytes$1(...e)}var nip04_exports={};__export(nip04_exports,{decrypt:()=>decrypt$1,encrypt:()=>encrypt$1});function encrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$1(n):n,s=secp256k1$1.getSharedSecret(r,"02"+e),o=getNormalizedX(s);let a=Uint8Array.from(randomBytes$1(16)),c=utf8Encoder.encode(t),l=cbc(o,a).encrypt(c),f=base64.encode(new Uint8Array(l)),h=base64.encode(new Uint8Array(a.buffer));return`${f}?iv=${h}`}function decrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$1(n):n;let[s,o]=t.split("?iv="),a=secp256k1$1.getSharedSecret(r,"02"+e),c=getNormalizedX(a),l=base64.decode(o),f=base64.decode(s),h=cbc(c,l).decrypt(f);return utf8Decoder.decode(h)}function getNormalizedX(n){return n.slice(1,33)}var nip05_exports={};__export(nip05_exports,{NIP05_REGEX:()=>NIP05_REGEX$1,isNip05:()=>isNip05,isValid:()=>isValid,queryProfile:()=>queryProfile,searchDomain:()=>searchDomain,useFetchImplementation:()=>useFetchImplementation});var NIP05_REGEX$1=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,isNip05=n=>NIP05_REGEX$1.test(n||""),_fetch;try{_fetch=fetch}catch(n){}function useFetchImplementation(n){_fetch=n}async function searchDomain(n,e=""){try{const t=`https://${n}/.well-known/nostr.json?name=${e}`,r=await _fetch(t,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function queryProfile(n){var s;const e=n.match(NIP05_REGEX$1);if(!e)return null;const[,t="_",r]=e;try{const o=`https://${r}/.well-known/nostr.json?name=${t}`,a=await _fetch(o,{redirect:"manual"});if(a.status!==200)throw Error("Wrong response code");const c=await a.json(),l=c.names[t];return l?{pubkey:l,relays:(s=c.relays)==null?void 0:s[l]}:null}catch{return null}}async function isValid(n,e){const t=await queryProfile(e);return t?t.pubkey===n:!1}var nip10_exports={};__export(nip10_exports,{parse:()=>parse});function parse(n){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let t,r;for(let s=n.tags.length-1;s>=0;s--){const o=n.tags[s];if(o[0]==="e"&&o[1]){const[a,c,l,f,h]=o,u={id:c,relays:l?[l]:[],author:h};if(f==="root"){e.root=u;continue}if(f==="reply"){e.reply=u;continue}if(f==="mention"){e.mentions.push(u);continue}t?r=u:t=u,e.mentions.push(u);continue}if(o[0]==="q"&&o[1]){const[a,c,l]=o;e.quotes.push({id:c,relays:l?[l]:[]})}if(o[0]==="p"&&o[1]){e.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]});continue}}return e.root||(e.root=r||t||e.reply),e.reply||(e.reply=t||e.root),[e.reply,e.root].forEach(s=>{if(!s)return;let o=e.mentions.indexOf(s);if(o!==-1&&e.mentions.splice(o,1),s.author){let a=e.profiles.find(c=>c.pubkey===s.author);a&&a.relays&&(s.relays||(s.relays=[]),a.relays.forEach(c=>{var l;((l=s.relays)==null?void 0:l.indexOf(c))===-1&&s.relays.push(c)}),a.relays=s.relays)}}),e.mentions.forEach(s=>{if(s.author){let o=e.profiles.find(a=>a.pubkey===s.author);o&&o.relays&&(s.relays||(s.relays=[]),o.relays.forEach(a=>{s.relays.indexOf(a)===-1&&s.relays.push(a)}),o.relays=s.relays)}}),e}var nip11_exports={};__export(nip11_exports,{fetchRelayInformation:()=>fetchRelayInformation,useFetchImplementation:()=>useFetchImplementation2});var _fetch2;try{_fetch2=fetch}catch{}function useFetchImplementation2(n){_fetch2=n}async function fetchRelayInformation(n){return await(await fetch(n.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var nip13_exports={};__export(nip13_exports,{fastEventHash:()=>fastEventHash,getPow:()=>getPow,minePow:()=>minePow});function getPow(n){let e=0;for(let t=0;t<64;t+=8){const r=parseInt(n.substring(t,t+8),16);if(r===0)e+=32;else{e+=Math.clz32(r);break}}return e}function minePow(n,e){let t=0;const r=n,s=["nonce",t.toString(),e.toString()];for(r.tags.push(s);;){const o=Math.floor(new Date().getTime()/1e3);if(o!==r.created_at&&(t=0,r.created_at=o),s[1]=(++t).toString(),r.id=fastEventHash(r),getPow(r.id)>=e)break}return r}function fastEventHash(n){return bytesToHex$1(sha256$2(utf8Encoder.encode(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content]))))}var nip17_exports={};__export(nip17_exports,{unwrapEvent:()=>unwrapEvent2,unwrapManyEvents:()=>unwrapManyEvents2,wrapEvent:()=>wrapEvent2,wrapManyEvents:()=>wrapManyEvents2});var nip59_exports={};__export(nip59_exports,{createRumor:()=>createRumor,createSeal:()=>createSeal,createWrap:()=>createWrap,unwrapEvent:()=>unwrapEvent,unwrapManyEvents:()=>unwrapManyEvents,wrapEvent:()=>wrapEvent$1,wrapManyEvents:()=>wrapManyEvents});var nip44_exports={};__export(nip44_exports,{decrypt:()=>decrypt2$1,encrypt:()=>encrypt2$1,getConversationKey:()=>getConversationKey,v2:()=>v2});var minPlaintextSize=1,maxPlaintextSize=65535;function getConversationKey(n,e){const t=secp256k1$1.getSharedSecret(n,"02"+e).subarray(1,33);return extract(sha256$2,t,"nip44-v2")}function getMessageKeys(n,e){const t=expand(sha256$2,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function calcPaddedLen(n){if(!Number.isSafeInteger(n)||n<1)throw new Error("expected positive integer");if(n<=32)return 32;const e=1<<Math.floor(Math.log2(n-1))+1,t=e<=256?32:e/8;return t*(Math.floor((n-1)/t)+1)}function writeU16BE(n){if(!Number.isSafeInteger(n)||n<minPlaintextSize||n>maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,n,!1),e}function pad(n){const e=utf8Encoder.encode(n),t=e.length,r=writeU16BE(t),s=new Uint8Array(calcPaddedLen(t)-t);return concatBytes$1(r,e,s)}function unpad(n){const e=new DataView(n.buffer).getUint16(0),t=n.subarray(2,2+e);if(e<minPlaintextSize||e>maxPlaintextSize||t.length!==e||n.length!==2+calcPaddedLen(e))throw new Error("invalid padding");return utf8Decoder.decode(t)}function hmacAad(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=concatBytes$1(t,e);return hmac$1(sha256$2,n,r)}function decodePayload(n){if(typeof n!="string")throw new Error("payload must be a valid string");const e=n.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(n[0]==="#")throw new Error("unknown encryption version");let t;try{t=base64.decode(n)}catch(o){throw new Error("invalid base64: "+o.message)}const r=t.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const s=t[0];if(s!==2)throw new Error("unknown encryption version "+s);return{nonce:t.subarray(1,33),ciphertext:t.subarray(33,-32),mac:t.subarray(-32)}}function encrypt2$1(n,e,t=randomBytes$1(32)){const{chacha_key:r,chacha_nonce:s,hmac_key:o}=getMessageKeys(e,t),a=pad(n),c=chacha20(r,s,a),l=hmacAad(o,c,t);return base64.encode(concatBytes$1(new Uint8Array([2]),t,c,l))}function decrypt2$1(n,e){const{nonce:t,ciphertext:r,mac:s}=decodePayload(n),{chacha_key:o,chacha_nonce:a,hmac_key:c}=getMessageKeys(e,t),l=hmacAad(c,r,t);if(!equalBytes(l,s))throw new Error("invalid MAC");const f=chacha20(o,a,r);return unpad(f)}var v2={utils:{getConversationKey,calcPaddedLen},encrypt:encrypt2$1,decrypt:decrypt2$1},TWO_DAYS=2*24*60*60,now=()=>Math.round(Date.now()/1e3),randomNow=()=>Math.round(now()-Math.random()*TWO_DAYS),nip44ConversationKey=(n,e)=>getConversationKey(n,e),nip44Encrypt=(n,e,t)=>encrypt2$1(JSON.stringify(n),nip44ConversationKey(e,t)),nip44Decrypt=(n,e)=>JSON.parse(decrypt2$1(n.content,nip44ConversationKey(e,n.pubkey)));function createRumor(n,e){const t={created_at:now(),content:"",tags:[],...n,pubkey:getPublicKey(e)};return t.id=getEventHash$1(t),t}function createSeal(n,e,t){return finalizeEvent({kind:Seal,content:nip44Encrypt(n,e,t),created_at:randomNow(),tags:[]},e)}function createWrap(n,e){const t=generateSecretKey();return finalizeEvent({kind:GiftWrap,content:nip44Encrypt(n,t,e),created_at:randomNow(),tags:[["p",e]]},t)}function wrapEvent$1(n,e,t){const r=createRumor(n,e),s=createSeal(r,e,t);return createWrap(s,t)}function wrapManyEvents(n,e,t){if(!t||t.length===0)throw new Error("At least one recipient is required.");const r=getPublicKey(e),s=[wrapEvent$1(n,e,r)];return t.forEach(o=>{s.push(wrapEvent$1(n,e,o))}),s}function unwrapEvent(n,e){const t=nip44Decrypt(n,e);return nip44Decrypt(t,e)}function unwrapManyEvents(n,e){let t=[];return n.forEach(r=>{t.push(unwrapEvent(r,e))}),t.sort((r,s)=>r.created_at-s.created_at),t}function createEvent(n,e,t,r){const s={created_at:Math.ceil(Date.now()/1e3),kind:PrivateDirectMessage,tags:[],content:e};return(Array.isArray(n)?n:[n]).forEach(({publicKey:a,relayUrl:c})=>{s.tags.push(c?["p",a,c]:["p",a])}),r&&s.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),t&&s.tags.push(["subject",t]),s}function wrapEvent2(n,e,t,r,s){const o=createEvent(e,t,r,s);return wrapEvent$1(o,n,e.publicKey)}function wrapManyEvents2(n,e,t,r,s){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:getPublicKey(n)},...e].map(a=>wrapEvent2(n,a,t,r,s))}var unwrapEvent2=unwrapEvent,unwrapManyEvents2=unwrapManyEvents,nip18_exports={};__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});function finishRepostEvent(n,e,t,r){var a;let s;const o=[...n.tags??[],["e",e.id,t],["p",e.pubkey]];return e.kind===ShortTextNote?s=Repost:(s=GenericRepost,o.push(["k",String(e.kind)])),finalizeEvent({kind:s,tags:o,content:n.content===""||(a=e.tags)!=null&&a.find(c=>c[0]==="-")?"":JSON.stringify(e),created_at:n.created_at},r)}function getRepostedEventPointer(n){if(![Repost,GenericRepost].includes(n.kind))return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(e!==void 0)return{id:e[1],relays:[e[2],t==null?void 0:t[2]].filter(r=>typeof r=="string"),author:t==null?void 0:t[1]}}function getRepostedEvent(n,{skipVerification:e}={}){const t=getRepostedEventPointer(n);if(t===void 0||n.content==="")return;let r;try{r=JSON.parse(n.content)}catch{return}if(r.id===t.id&&!(!e&&!verifyEvent(r)))return r}var nip21_exports={};__export(nip21_exports,{NOSTR_URI_REGEX:()=>NOSTR_URI_REGEX,parse:()=>parse2,test:()=>test});var NOSTR_URI_REGEX=new RegExp(`nostr:(${BECH32_REGEX$1.source})`);function test(n){return typeof n=="string"&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(n)}function parse2(n){const e=n.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${n}`);return{uri:e[0],value:e[1],decoded:decode$1(e[1])}}var nip25_exports={};__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});function finishReactionEvent(n,e,t){const r=e.tags.filter(s=>s.length>=2&&(s[0]==="e"||s[0]==="p"));return finalizeEvent({...n,kind:Reaction,tags:[...n.tags??[],...r,["e",e.id],["p",e.pubkey]],content:n.content??"+"},t)}function getReactedEventPointer(n){if(n.kind!==Reaction)return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(!(e===void 0||t===void 0))return{id:e[1],relays:[e[2],t[2]].filter(r=>r!==void 0),author:t[1]}}var nip27_exports={};__export(nip27_exports,{parse:()=>parse3});var noCharacter=/\W/m,noURLCharacter=/\W |\W$|$|,| /m;function*parse3(n){const e=n.length;let t=0,r=0;for(;r<e;){let s=n.indexOf(":",r);if(s===-1)break;if(n.substring(s-5,s)==="nostr"){const o=n.substring(s+60).match(noCharacter),a=o?s+60+o.index:e;try{let c,{data:l,type:f}=decode$1(n.substring(s+1,a));switch(f){case"npub":c={pubkey:l};break;case"nsec":case"note":r=a+1;continue;default:c=l}t!==s-5&&(yield{type:"text",text:n.substring(t,s-5)}),yield{type:"reference",pointer:c},r=a,t=r;continue}catch{r=s+1;continue}}else if(n.substring(s-5,s)==="https"||n.substring(s-4,s)==="http"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,c=n[s-1]==="s"?5:4;try{let l=new URL(n.substring(s-c,a));if(l.hostname.indexOf(".")===-1)throw new Error("invalid url");if(t!==s-c&&(yield{type:"text",text:n.substring(t,s-c)}),l.pathname.endsWith(".png")||l.pathname.endsWith(".jpg")||l.pathname.endsWith(".jpeg")||l.pathname.endsWith(".gif")||l.pathname.endsWith(".webp")){yield{type:"image",url:l.toString()},r=a,t=r;continue}if(l.pathname.endsWith(".mp4")||l.pathname.endsWith(".avi")||l.pathname.endsWith(".webm")||l.pathname.endsWith(".mkv")){yield{type:"video",url:l.toString()},r=a,t=r;continue}if(l.pathname.endsWith(".mp3")||l.pathname.endsWith(".aac")||l.pathname.endsWith(".ogg")||l.pathname.endsWith(".opus")){yield{type:"audio",url:l.toString()},r=a,t=r;continue}yield{type:"url",url:l.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else if(n.substring(s-3,s)==="wss"||n.substring(s-2,s)==="ws"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,c=n[s-1]==="s"?3:2;try{let l=new URL(n.substring(s-c,a));if(l.hostname.indexOf(".")===-1)throw new Error("invalid ws url");t!==s-c&&(yield{type:"text",text:n.substring(t,s-c)}),yield{type:"relay",url:l.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else{r=s+1;continue}}t!==e&&(yield{type:"text",text:n.substring(t)})}var nip28_exports={};__export(nip28_exports,{channelCreateEvent:()=>channelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent({kind:ChannelCreation,tags:[...n.tags??[]],content:t,created_at:n.created_at},e)},channelMetadataEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent({kind:ChannelMetadata,tags:[["e",n.channel_create_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMessageEvent=(n,e)=>{const t=[["e",n.channel_create_event_id,n.relay_url,"root"]];return n.reply_to_channel_message_event_id&&t.push(["e",n.reply_to_channel_message_event_id,n.relay_url,"reply"]),finalizeEvent({kind:ChannelMessage,tags:[...t,...n.tags??[]],content:n.content,created_at:n.created_at},e)},channelHideMessageEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent({kind:ChannelHideMessage,tags:[["e",n.channel_message_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMuteUserEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent({kind:ChannelMuteUser,tags:[["p",n.pubkey_to_mute],...n.tags??[]],content:t,created_at:n.created_at},e)},nip30_exports={};__export(nip30_exports,{EMOJI_SHORTCODE_REGEX:()=>EMOJI_SHORTCODE_REGEX,matchAll:()=>matchAll,regex:()=>regex,replaceAll:()=>replaceAll});var EMOJI_SHORTCODE_REGEX=/:(\w+):/,regex=()=>new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`,"g");function*matchAll(n){const e=n.matchAll(regex());for(const t of e)try{const[r,s]=t;yield{shortcode:r,name:s,start:t.index,end:t.index+r.length}}catch{}}function replaceAll(n,e){return n.replaceAll(regex(),(t,r)=>e({shortcode:t,name:r}))}var nip39_exports={};__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation3,validateGithub:()=>validateGithub});var _fetch3;try{_fetch3=fetch}catch{}function useFetchImplementation3(n){_fetch3=n}async function validateGithub(n,e,t){try{return await(await _fetch3(`https://gist.github.com/${e}/${t}/raw`)).text()===`Verifying that I control the following Nostr public key: ${n}`}catch{return!1}}var nip47_exports={};__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});function parseConnectionString(n){const{pathname:e,searchParams:t}=new URL(n),r=e,s=t.get("relay"),o=t.get("secret");if(!r||!s||!o)throw new Error("invalid connection string");return{pubkey:r,relay:s,secret:o}}async function makeNwcRequestEvent(n,e,t){const s=encrypt$1(e,n,JSON.stringify({method:"pay_invoice",params:{invoice:t}})),o={kind:NWCWalletRequest,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n]]};return finalizeEvent(o,e)}var nip54_exports={};__export(nip54_exports,{normalizeIdentifier:()=>normalizeIdentifier});function normalizeIdentifier(n){return n=n.trim().toLowerCase(),n=n.normalize("NFKC"),Array.from(n).map(e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-").join("")}var nip57_exports={};__export(nip57_exports,{getSatoshisAmountFromBolt11:()=>getSatoshisAmountFromBolt11,getZapEndpoint:()=>getZapEndpoint,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation4,validateZapRequest:()=>validateZapRequest});var _fetch4;try{_fetch4=fetch}catch{}function useFetchImplementation4(n){_fetch4=n}async function getZapEndpoint(n){try{let e="",{lud06:t,lud16:r}=JSON.parse(n.content);if(t){let{words:a}=bech32$2.decode(t,1e3),c=bech32$2.fromWords(a);e=utf8Decoder.decode(c)}else if(r){let[a,c]=r.split("@");e=new URL(`/.well-known/lnurlp/${a}`,`https://${c}`).toString()}else return null;let o=await(await _fetch4(e)).json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch{}return null}function makeZapRequest({profile:n,event:e,amount:t,relays:r,comment:s=""}){if(!t)throw new Error("amount not given");if(!n)throw new Error("profile not given");let o={kind:9734,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n],["amount",t.toString()],["relays",...r]]};if(e&&typeof e=="string"&&o.tags.push(["e",e]),e&&typeof e=="object"){if(isReplaceableKind(e.kind)){const a=["a",`${e.kind}:${e.pubkey}:`];o.tags.push(a)}else if(isAddressableKind(e.kind)){let a=e.tags.find(([l,f])=>l==="d"&&f);if(!a)throw new Error("d tag not found or is empty");const c=["a",`${e.kind}:${e.pubkey}:${a[1]}`];o.tags.push(c)}}return o}function validateZapRequest(n){let e;try{e=JSON.parse(n)}catch{return"Invalid zap request JSON."}if(!validateEvent(e))return"Zap request is not a valid Nostr event.";if(!verifyEvent(e))return"Invalid signature on zap request.";let t=e.tags.find(([o,a])=>o==="p"&&a);if(!t)return"Zap request doesn't have a 'p' tag.";if(!t[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find(([o,a])=>o==="e"&&a);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([o,a])=>o==="relays"&&a)?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:n,preimage:e,bolt11:t,paidAt:r}){let s=JSON.parse(n),o=s.tags.filter(([c])=>c==="e"||c==="p"||c==="a"),a={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...o,["P",s.pubkey],["bolt11",t],["description",n]]};return e&&a.tags.push(["preimage",e]),a}function getSatoshisAmountFromBolt11(n){if(n.length<50)return 0;n=n.substring(0,50);const e=n.lastIndexOf("1");if(e===-1)return 0;const t=n.substring(0,e);if(!t.startsWith("lnbc"))return 0;const r=t.substring(4);if(r.length<1)return 0;const s=r[r.length-1],o=s.charCodeAt(0)-"0".charCodeAt(0),a=o>=0&&o<=9;let c=r.length-1;if(a&&c++,c<1)return 0;const l=parseInt(r.substring(0,c));switch(s){case"m":return l*1e5;case"u":return l*100;case"n":return l/10;case"p":return l/1e4;default:return l*1e8}}var nip98_exports={};__export(nip98_exports,{getToken:()=>getToken,hashPayload:()=>hashPayload,unpackEventFromToken:()=>unpackEventFromToken,validateEvent:()=>validateEvent2,validateEventKind:()=>validateEventKind,validateEventMethodTag:()=>validateEventMethodTag,validateEventPayloadTag:()=>validateEventPayloadTag,validateEventTimestamp:()=>validateEventTimestamp,validateEventUrlTag:()=>validateEventUrlTag,validateToken:()=>validateToken});var _authorizationScheme="Nostr ";async function getToken(n,e,t,r=!1,s){const o={kind:HTTPAuth,tags:[["u",n],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};s&&o.tags.push(["payload",hashPayload(s)]);const a=await t(o);return(r?_authorizationScheme:"")+base64.encode(utf8Encoder.encode(JSON.stringify(a)))}async function validateToken(n,e,t){const r=await unpackEventFromToken(n).catch(o=>{throw o});return await validateEvent2(r,e,t).catch(o=>{throw o})}async function unpackEventFromToken(n){if(!n)throw new Error("Missing token");n=n.replace(_authorizationScheme,"");const e=utf8Decoder.decode(base64.decode(n));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function validateEventTimestamp(n){return n.created_at?Math.round(new Date().getTime()/1e3)-n.created_at<60:!1}function validateEventKind(n){return n.kind===HTTPAuth}function validateEventUrlTag(n,e){const t=n.tags.find(r=>r[0]==="u");return t?t.length>0&&t[1]===e:!1}function validateEventMethodTag(n,e){const t=n.tags.find(r=>r[0]==="method");return t?t.length>0&&t[1].toLowerCase()===e.toLowerCase():!1}function hashPayload(n){const e=sha256$2(utf8Encoder.encode(JSON.stringify(n)));return bytesToHex$1(e)}function validateEventPayloadTag(n,e){const t=n.tags.find(s=>s[0]==="payload");if(!t)return!1;const r=hashPayload(e);return t.length>0&&t[1]===r}async function validateEvent2(n,e,t,r){if(!verifyEvent(n))throw new Error("Invalid nostr event, signature invalid");if(!validateEventKind(n))throw new Error("Invalid nostr event, kind invalid");if(!validateEventTimestamp(n))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!validateEventUrlTag(n,e))throw new Error("Invalid nostr event, url tag invalid");if(!validateEventMethodTag(n,t))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!validateEventPayloadTag(n,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes$1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function anumber$1(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function abytes(n,...e){if(!isBytes$1(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function ahash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");anumber$1(n.outputLen),anumber$1(n.blockLen)}function aexists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function aoutput(n,e){abytes(n);const t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function clean(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function createView(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function rotr(n,e){return n<<32-e|n>>>e}const hasHexBuiltin=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),hexes=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex(n){if(abytes(n),hasHexBuiltin)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=hexes[n[t]];return e}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(n){if(n>=asciis._0&&n<=asciis._9)return n-asciis._0;if(n>=asciis.A&&n<=asciis.F)return n-(asciis.A-10);if(n>=asciis.a&&n<=asciis.f)return n-(asciis.a-10)}function hexToBytes(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(hasHexBuiltin)return Uint8Array.fromHex(n);const e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){const a=asciiToBase16(n.charCodeAt(o)),c=asciiToBase16(n.charCodeAt(o+1));if(a===void 0||c===void 0){const l=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}r[s]=a*16+c}return r}function utf8ToBytes(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function toBytes(n){return typeof n=="string"&&(n=utf8ToBytes(n)),abytes(n),n}function concatBytes(...n){let e=0;for(let r=0;r<n.length;r++){const s=n[r];abytes(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){const o=n[r];t.set(o,s),s+=o.length}return t}class Hash{}function createHasher(n){const e=r=>n().update(toBytes(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes(n=32){if(crypto&&typeof crypto.getRandomValues=="function")return crypto.getRandomValues(new Uint8Array(n));if(crypto&&typeof crypto.randomBytes=="function")return Uint8Array.from(crypto.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),c=Number(t&o),l=r?4:0,f=r?0:4;n.setUint32(e+l,a,r),n.setUint32(e+f,c,r)}function Chi(n,e,t){return n&e^~n&t}function Maj(n,e,t){return n&e^n&t^e&t}class HashMD extends Hash{constructor(e,t,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),e=toBytes(e),abytes(e);const{view:t,buffer:r,blockLen:s}=this,o=e.length;for(let a=0;a<o;){const c=Math.min(s-this.pos,o-a);if(c===s){const l=createView(e);for(;s<=o-a;a+=s)this.process(l,a);continue}r.set(e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,clean(this.buffer.subarray(a)),this.padOffset>s-a&&(this.process(r,0),a=0);for(let u=a;u<s;u++)t[u]=0;setBigUint64(r,s-8,BigInt(this.length*8),o),this.process(r,0);const c=createView(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=l/4,h=this.get();if(f>h.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<f;u++)c.setUint32(4*u,h[u],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:c}=this;return e.destroyed=a,e.finished=o,e.length=s,e.pos=c,s%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_K=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(e=32){super(64,e,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:c,H:l}=this;return[e,t,r,s,o,a,c,l]}set(e,t,r,s,o,a,c,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=c|0,this.H=l|0}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const p=SHA256_W[u-15],y=SHA256_W[u-2],b=rotr(p,7)^rotr(p,18)^p>>>3,m=rotr(y,17)^rotr(y,19)^y>>>10;SHA256_W[u]=m+SHA256_W[u-7]+b+SHA256_W[u-16]|0}let{A:r,B:s,C:o,D:a,E:c,F:l,G:f,H:h}=this;for(let u=0;u<64;u++){const p=rotr(c,6)^rotr(c,11)^rotr(c,25),y=h+p+Chi(c,l,f)+SHA256_K[u]+SHA256_W[u]|0,m=(rotr(r,2)^rotr(r,13)^rotr(r,22))+Maj(r,s,o)|0;h=f,f=l,l=c,c=a+y|0,a=o,o=s,s=r,r=y+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,l=l+this.F|0,f=f+this.G|0,h=h+this.H|0,this.set(r,s,o,a,c,l,f,h)}roundClean(){clean(SHA256_W)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}}const sha256$1=createHasher(()=>new SHA256);class HMAC extends Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const r=toBytes(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),clean(o)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:c}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=c,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(n,e,t)=>new HMAC(n,e).update(t).digest();hmac.create=(n,e)=>new HMAC(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$4=BigInt(1);function abool(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}function numberToHexUnpadded(n){const e=n.toString(16);return e.length&1?"0"+e:e}function hexToNumber(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?_0n$4:BigInt("0x"+n)}function bytesToNumberBE(n){return hexToNumber(bytesToHex(n))}function bytesToNumberLE(n){return abytes(n),hexToNumber(bytesToHex(Uint8Array.from(n).reverse()))}function numberToBytesBE(n,e){return hexToBytes(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE(n,e){return numberToBytesBE(n,e).reverse()}function ensureBytes(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(isBytes$1(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(n+" of length "+t+" expected, got "+s);return r}const isPosBig=n=>typeof n=="bigint"&&_0n$4<=n;function inRange(n,e,t){return isPosBig(n)&&isPosBig(e)&&isPosBig(t)&&e<=n&&n<t}function aInRange(n,e,t,r){if(!inRange(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function bitLen(n){let e;for(e=0;n>_0n$4;n>>=_1n$4,e+=1);return e}const bitMask=n=>(_1n$4<<BigInt(n))-_1n$4;function createHmacDrbg(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");const r=y=>new Uint8Array(y),s=y=>Uint8Array.of(y);let o=r(n),a=r(n),c=0;const l=()=>{o.fill(1),a.fill(0),c=0},f=(...y)=>t(a,o,...y),h=(y=r(0))=>{a=f(s(0),y),o=f(),y.length!==0&&(a=f(s(1),y),o=f())},u=()=>{if(c++>=1e3)throw new Error("drbg: tried 1000 values");let y=0;const b=[];for(;y<e;){o=f();const m=o.slice();b.push(m),y+=o.length}return concatBytes(...b)};return(y,b)=>{l(),h(y);let m;for(;!(m=b(u()));)h();return l(),m}}function _validateObject(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(s,o,a){const c=n[s];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${s}" is invalid: expected ${o}, got ${l}`)}Object.entries(e).forEach(([s,o])=>r(s,o,!1)),Object.entries(t).forEach(([s,o])=>r(s,o,!0))}function memoized(n){const e=new WeakMap;return(t,...r)=>{const s=e.get(t);if(s!==void 0)return s;const o=n(t,...r);return e.set(t,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$3=BigInt(1),_2n$2=BigInt(2),_3n$1=BigInt(3),_4n$1=BigInt(4),_5n=BigInt(5),_7n=BigInt(7),_8n=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(n,e){const t=n%e;return t>=_0n$3?t:e+t}function pow2(n,e,t){let r=n;for(;e-- >_0n$3;)r*=r,r%=t;return r}function invert(n,e){if(n===_0n$3)throw new Error("invert: expected non-zero number");if(e<=_0n$3)throw new Error("invert: expected positive modulus, got "+e);let t=mod(n,e),r=e,s=_0n$3,o=_1n$3;for(;t!==_0n$3;){const c=r/t,l=r%t,f=s-o*c;r=t,t=l,s=o,o=f}if(r!==_1n$3)throw new Error("invert: does not exist");return mod(s,e)}function assertIsSquare(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function sqrt3mod4(n,e){const t=(n.ORDER+_1n$3)/_4n$1,r=n.pow(e,t);return assertIsSquare(n,r,e),r}function sqrt5mod8(n,e){const t=(n.ORDER-_5n)/_8n,r=n.mul(e,_2n$2),s=n.pow(r,t),o=n.mul(e,s),a=n.mul(n.mul(o,_2n$2),s),c=n.mul(o,n.sub(a,n.ONE));return assertIsSquare(n,c,e),c}function sqrt9mod16(n){const e=Field(n),t=tonelliShanks(n),r=t(e,e.neg(e.ONE)),s=t(e,r),o=t(e,e.neg(r)),a=(n+_7n)/_16n;return(c,l)=>{let f=c.pow(l,a),h=c.mul(f,r);const u=c.mul(f,s),p=c.mul(f,o),y=c.eql(c.sqr(h),l),b=c.eql(c.sqr(u),l);f=c.cmov(f,h,y),h=c.cmov(p,u,b);const m=c.eql(c.sqr(h),l),k=c.cmov(f,h,m);return assertIsSquare(c,k,l),k}}function tonelliShanks(n){if(n<_3n$1)throw new Error("sqrt is not defined for small field");let e=n-_1n$3,t=0;for(;e%_2n$2===_0n$3;)e/=_2n$2,t++;let r=_2n$2;const s=Field(n);for(;FpLegendre(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return sqrt3mod4;let o=s.pow(r,e);const a=(e+_1n$3)/_2n$2;return function(l,f){if(l.is0(f))return f;if(FpLegendre(l,f)!==1)throw new Error("Cannot find square root");let h=t,u=l.mul(l.ONE,o),p=l.pow(f,e),y=l.pow(f,a);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let b=1,m=l.sqr(p);for(;!l.eql(m,l.ONE);)if(b++,m=l.sqr(m),b===h)throw new Error("Cannot find square root");const k=_1n$3<<BigInt(h-b-1),R=l.pow(u,k);h=b,u=l.sqr(R),p=l.mul(p,u),y=l.mul(y,R)}return y}}function FpSqrt(n){return n%_4n$1===_3n$1?sqrt3mod4:n%_8n===_5n?sqrt5mod8:n%_16n===_9n?sqrt9mod16(n):tonelliShanks(n)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=FIELD_FIELDS.reduce((r,s)=>(r[s]="function",r),e);return _validateObject(n,t),n}function FpPow(n,e,t){if(t<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(t===_0n$3)return n.ONE;if(t===_1n$3)return e;let r=n.ONE,s=e;for(;t>_0n$3;)t&_1n$3&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$3;return r}function FpInvertBatch(n,e,t=!1){const r=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((a,c,l)=>n.is0(c)?a:(r[l]=a,n.mul(a,c)),n.ONE),o=n.inv(s);return e.reduceRight((a,c,l)=>n.is0(c)?a:(r[l]=n.mul(a,r[l]),n.mul(a,c)),o),r}function FpLegendre(n,e){const t=(n.ORDER-_1n$3)/_2n$2,r=n.pow(e,t),s=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),a=n.eql(r,n.neg(n.ONE));if(!s&&!o&&!a)throw new Error("invalid Legendre symbol result");return s?1:o?0:-1}function nLength(n,e){e!==void 0&&anumber$1(e);const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field(n,e,t=!1,r={}){if(n<=_0n$3)throw new Error("invalid field: expected ORDER > 0, got "+n);let s,o,a=!1,c;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");const p=e;p.BITS&&(s=p.BITS),p.sqrt&&(o=p.sqrt),typeof p.isLE=="boolean"&&(t=p.isLE),typeof p.modOnDecode=="boolean"&&(a=p.modOnDecode),c=p.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(o=r.sqrt);const{nBitLength:l,nByteLength:f}=nLength(n,s);if(f>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let h;const u=Object.freeze({ORDER:n,isLE:t,BITS:l,BYTES:f,MASK:bitMask(l),ZERO:_0n$3,ONE:_1n$3,allowedLengths:c,create:p=>mod(p,n),isValid:p=>{if(typeof p!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof p);return _0n$3<=p&&p<n},is0:p=>p===_0n$3,isValidNot0:p=>!u.is0(p)&&u.isValid(p),isOdd:p=>(p&_1n$3)===_1n$3,neg:p=>mod(-p,n),eql:(p,y)=>p===y,sqr:p=>mod(p*p,n),add:(p,y)=>mod(p+y,n),sub:(p,y)=>mod(p-y,n),mul:(p,y)=>mod(p*y,n),pow:(p,y)=>FpPow(u,p,y),div:(p,y)=>mod(p*invert(y,n),n),sqrN:p=>p*p,addN:(p,y)=>p+y,subN:(p,y)=>p-y,mulN:(p,y)=>p*y,inv:p=>invert(p,n),sqrt:o||(p=>(h||(h=FpSqrt(n)),h(u,p))),toBytes:p=>t?numberToBytesLE(p,f):numberToBytesBE(p,f),fromBytes:(p,y=!0)=>{if(c){if(!c.includes(p.length)||p.length>f)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+p.length);const m=new Uint8Array(f);m.set(p,t?0:m.length-p.length),p=m}if(p.length!==f)throw new Error("Field.fromBytes: expected "+f+" bytes, got "+p.length);let b=t?bytesToNumberLE(p):bytesToNumberBE(p);if(a&&(b=mod(b,n)),!y&&!u.isValid(b))throw new Error("invalid field element: outside of range 0..ORDER");return b},invertBatch:p=>FpInvertBatch(u,p),cmov:(p,y,b)=>b?y:p});return Object.freeze(u)}function getFieldBytesLength(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength(n){const e=getFieldBytesLength(n);return e+Math.ceil(e/2)}function mapHashToField(n,e,t=!1){const r=n.length,s=getFieldBytesLength(e),o=getMinHashLength(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const a=t?bytesToNumberLE(n):bytesToNumberBE(n),c=mod(a,e-_1n$3)+_1n$3;return t?numberToBytesLE(c,s):numberToBytesBE(c,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$2=BigInt(1);function negateCt(n,e){const t=e.negate();return n?t:e}function normalizeZ(n,e){const t=FpInvertBatch(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function validateW(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function calcWOpts(n,e){validateW(n,e);const t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,o=bitMask(n),a=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:s,shiftBy:a}}function calcOffsets(n,e,t){const{windowSize:r,mask:s,maxNumber:o,shiftBy:a}=t;let c=Number(n&s),l=n>>a;c>r&&(c-=o,l+=_1n$2);const f=e*r,h=f+Math.abs(c)-1,u=c===0,p=c<0,y=e%2!==0;return{nextN:l,offset:h,isZero:u,isNeg:p,isNegF:y,offsetF:f}}function validateMSMPoints(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function validateMSMScalars(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(n){return pointWindowSizes.get(n)||1}function assert0(n){if(n!==_0n$2)throw new Error("invalid wNAF")}class wNAF{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>_0n$2;)t&_1n$2&&(r=r.add(s)),s=s.double(),t>>=_1n$2;return r}precomputeWindow(e,t){const{windows:r,windowSize:s}=calcWOpts(t,this.bits),o=[];let a=e,c=a;for(let l=0;l<r;l++){c=a,o.push(c);for(let f=1;f<s;f++)c=c.add(a),o.push(c);a=c.double()}return o}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,o=this.BASE;const a=calcWOpts(e,this.bits);for(let c=0;c<a.windows;c++){const{nextN:l,offset:f,isZero:h,isNeg:u,isNegF:p,offsetF:y}=calcOffsets(r,c,a);r=l,h?o=o.add(negateCt(p,t[y])):s=s.add(negateCt(u,t[f]))}return assert0(r),{p:s,f:o}}wNAFUnsafe(e,t,r,s=this.ZERO){const o=calcWOpts(e,this.bits);for(let a=0;a<o.windows&&r!==_0n$2;a++){const{nextN:c,offset:l,isZero:f,isNeg:h}=calcOffsets(r,a,o);if(r=c,!f){const u=t[l];s=s.add(h?u.negate():u)}}return assert0(r),s}getPrecomputes(e,t,r){let s=pointPrecomputes.get(t);return s||(s=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(s=r(s)),pointPrecomputes.set(t,s))),s}cached(e,t,r){const s=getW(e);return this.wNAF(s,this.getPrecomputes(s,e,r),t)}unsafe(e,t,r,s){const o=getW(e);return o===1?this._unsafeLadder(e,t,s):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,s)}createCache(e,t){validateW(t,this.bits),pointWindowSizes.set(e,t),pointPrecomputes.delete(e)}hasCache(e){return getW(e)!==1}}function mulEndoUnsafe(n,e,t,r){let s=e,o=n.ZERO,a=n.ZERO;for(;t>_0n$2||r>_0n$2;)t&_1n$2&&(o=o.add(s)),r&_1n$2&&(a=a.add(s)),s=s.double(),t>>=_1n$2,r>>=_1n$2;return{p1:o,p2:a}}function pippenger(n,e,t,r){validateMSMPoints(t,n),validateMSMScalars(r,e);const s=t.length,o=r.length;if(s!==o)throw new Error("arrays of points and scalars must have equal length");const a=n.ZERO,c=bitLen(BigInt(s));let l=1;c>12?l=c-3:c>4?l=c-2:c>0&&(l=2);const f=bitMask(l),h=new Array(Number(f)+1).fill(a),u=Math.floor((e.BITS-1)/l)*l;let p=a;for(let y=u;y>=0;y-=l){h.fill(a);for(let m=0;m<o;m++){const k=r[m],R=Number(k>>BigInt(y)&f);h[R]=h[R].add(t[m])}let b=a;for(let m=h.length-1,k=a;m>0;m--)k=k.add(h[m]),b=b.add(k);if(p=p.add(b),y!==0)for(let m=0;m<l;m++)p=p.double()}return p}function createField(n,e){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(e),e}else return Field(n)}function _createCurveFields(n,e,t={}){if(!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>_0n$2))throw new Error(`CURVE.${c} must be positive bigint`)}const r=createField(e.p,t.Fp),s=createField(e.n,t.Fn),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(const c of a)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const divNearest=(n,e)=>(n+(n>=0?e:-e)/_2n$1)/e;function _splitEndoScalar(n,e,t){const[[r,s],[o,a]]=e,c=divNearest(a*n,t),l=divNearest(-s*n,t);let f=n-c*r-l*o,h=-c*s-l*a;const u=f<_0n$1,p=h<_0n$1;u&&(f=-f),p&&(h=-h);const y=bitMask(Math.ceil(bitLen(t)/2))+_1n$1;if(f<_0n$1||f>=y||h<_0n$1||h>=y)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:u,k1:f,k2neg:p,k2:h}}function validateSigVerOpts(n){n.lowS!==void 0&&abool("lowS",n.lowS),n.prehash!==void 0&&abool("prehash",n.prehash)}class DERErr extends Error{constructor(e=""){super(e)}}const DER={Err:DERErr,_tlv:{encode:(n,e)=>{const{Err:t}=DER;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,s=numberToHexUnpadded(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const o=r>127?numberToHexUnpadded(s.length/2|128):"";return numberToHexUnpadded(n)+o+s+e},decode(n,e){const{Err:t}=DER;let r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");const s=e[r++],o=!!(s&128);let a=0;if(!o)a=s;else{const l=s&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");const f=e.subarray(r,r+l);if(f.length!==l)throw new t("tlv.decode: length bytes not complete");if(f[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const h of f)a=a<<8|h;if(r+=l,a<128)throw new t("tlv.decode(long): not minimal encoding")}const c=e.subarray(r,r+a);if(c.length!==a)throw new t("tlv.decode: wrong value length");return{v:c,l:e.subarray(r+a)}}},_int:{encode(n){const{Err:e}=DER;if(n<_0n$1)throw new e("integer: negative integers are not allowed");let t=numberToHexUnpadded(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){const{Err:e}=DER;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(n)}},toSig(n){const{Err:e,_int:t,_tlv:r}=DER,s=ensureBytes("signature",n),{v:o,l:a}=r.decode(48,s);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:c,l}=r.decode(2,o),{v:f,l:h}=r.decode(2,l);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(c),s:t.decode(f)}},hexFromSig(n){const{_tlv:e,_int:t}=DER,r=e.encode(2,t.encode(n.r)),s=e.encode(2,t.encode(n.s)),o=r+s;return e.encode(48,o)}},_0n$1=BigInt(0),_1n$1=BigInt(1),_2n$1=BigInt(2),_3n=BigInt(3),_4n=BigInt(4);function _legacyHelperEquat(n,e,t){function r(s){const o=n.sqr(s),a=n.mul(o,s);return n.add(n.add(a,n.mul(s,e)),t)}return r}function _normFnElement(n,e){const{BYTES:t}=n;let r;if(typeof e=="bigint")r=e;else{let s=ensureBytes("private key",e);try{r=n.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!n.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function weierstrassN(n,e={}){const{Fp:t,Fn:r}=_createCurveFields("weierstrass",n,e),{h:s,n:o}=n;_validateObject(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:a}=e;if(a&&(!t.is0(n.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');function c(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(O,$,E){const{x:_,y:T}=$.toAffine(),N=t.toBytes(_);if(abool("isCompressed",E),E){c();const x=!t.isOdd(T);return concatBytes(pprefix(x),N)}else return concatBytes(Uint8Array.of(4),N,t.toBytes(T))}function f(O){abytes(O);const $=t.BYTES,E=$+1,_=2*$+1,T=O.length,N=O[0],x=O.subarray(1);if(T===E&&(N===2||N===3)){const w=t.fromBytes(x);if(!t.isValid(w))throw new Error("bad point: is not on curve, wrong x");const v=p(w);let S;try{S=t.sqrt(v)}catch(I){const P=I instanceof Error?": "+I.message:"";throw new Error("bad point: is not on curve, sqrt error"+P)}c();const A=t.isOdd(S);return(N&1)===1!==A&&(S=t.neg(S)),{x:w,y:S}}else if(T===_&&N===4){const w=t.fromBytes(x.subarray($*0,$*1)),v=t.fromBytes(x.subarray($*1,$*2));if(!y(w,v))throw new Error("bad point: is not on curve");return{x:w,y:v}}else throw new Error(`bad point: got length ${T}, expected compressed=${E} or uncompressed=${_}`)}const h=e.toBytes||l,u=e.fromBytes||f,p=_legacyHelperEquat(t,n.a,n.b);function y(O,$){const E=t.sqr($),_=p(O);return t.eql(E,_)}if(!y(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const b=t.mul(t.pow(n.a,_3n),_4n),m=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(b,m)))throw new Error("bad curve params: a or b");function k(O,$,E=!1){if(!t.isValid($)||E&&t.is0($))throw new Error(`bad point coordinate ${O}`);return $}function R(O){if(!(O instanceof C))throw new Error("ProjectivePoint expected")}function B(O){if(!a||!a.basises)throw new Error("no endo");return _splitEndoScalar(O,a.basises,r.ORDER)}const D=memoized((O,$)=>{const{X:E,Y:_,Z:T}=O;if(t.eql(T,t.ONE))return{x:E,y:_};const N=O.is0();$==null&&($=N?t.ONE:t.inv(T));const x=t.mul(E,$),w=t.mul(_,$),v=t.mul(T,$);if(N)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x,y:w}}),U=memoized(O=>{if(O.is0()){if(e.allowInfinityPoint&&!t.is0(O.Y))return;throw new Error("bad point: ZERO")}const{x:$,y:E}=O.toAffine();if(!t.isValid($)||!t.isValid(E))throw new Error("bad point: x or y not field elements");if(!y($,E))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function H(O,$,E,_,T){return E=new C(t.mul(E.X,O),E.Y,E.Z),$=negateCt(_,$),E=negateCt(T,E),$.add(E)}class C{constructor($,E,_){this.X=k("x",$),this.Y=k("y",E,!0),this.Z=k("z",_),Object.freeze(this)}static fromAffine($){const{x:E,y:_}=$||{};if(!$||!t.isValid(E)||!t.isValid(_))throw new Error("invalid affine point");if($ instanceof C)throw new Error("projective point not allowed");return t.is0(E)&&t.is0(_)?C.ZERO:new C(E,_,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}static normalizeZ($){return normalizeZ(C,$)}static fromBytes($){return abytes($),C.fromHex($)}static fromHex($){const E=C.fromAffine(u(ensureBytes("pointHex",$)));return E.assertValidity(),E}static fromPrivateKey($){return C.BASE.multiply(_normFnElement(r,$))}static msm($,E){return pippenger(C,r,$,E)}_setWindowSize($){this.precompute($)}precompute($=8,E=!0){return F.createCache(this,$),E||this.multiply(_3n),this}assertValidity(){U(this)}hasEvenY(){const{y:$}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd($)}equals($){R($);const{X:E,Y:_,Z:T}=this,{X:N,Y:x,Z:w}=$,v=t.eql(t.mul(E,w),t.mul(N,T)),S=t.eql(t.mul(_,w),t.mul(x,T));return v&&S}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:$,b:E}=n,_=t.mul(E,_3n),{X:T,Y:N,Z:x}=this;let w=t.ZERO,v=t.ZERO,S=t.ZERO,A=t.mul(T,T),L=t.mul(N,N),I=t.mul(x,x),P=t.mul(T,N);return P=t.add(P,P),S=t.mul(T,x),S=t.add(S,S),w=t.mul($,S),v=t.mul(_,I),v=t.add(w,v),w=t.sub(L,v),v=t.add(L,v),v=t.mul(w,v),w=t.mul(P,w),S=t.mul(_,S),I=t.mul($,I),P=t.sub(A,I),P=t.mul($,P),P=t.add(P,S),S=t.add(A,A),A=t.add(S,A),A=t.add(A,I),A=t.mul(A,P),v=t.add(v,A),I=t.mul(N,x),I=t.add(I,I),A=t.mul(I,P),w=t.sub(w,A),S=t.mul(I,L),S=t.add(S,S),S=t.add(S,S),new C(w,v,S)}add($){R($);const{X:E,Y:_,Z:T}=this,{X:N,Y:x,Z:w}=$;let v=t.ZERO,S=t.ZERO,A=t.ZERO;const L=n.a,I=t.mul(n.b,_3n);let P=t.mul(E,N),V=t.mul(_,x),z=t.mul(T,w),W=t.add(E,_),q=t.add(N,x);W=t.mul(W,q),q=t.add(P,V),W=t.sub(W,q),q=t.add(E,T);let j=t.add(N,w);return q=t.mul(q,j),j=t.add(P,z),q=t.sub(q,j),j=t.add(_,T),v=t.add(x,w),j=t.mul(j,v),v=t.add(V,z),j=t.sub(j,v),A=t.mul(L,q),v=t.mul(I,z),A=t.add(v,A),v=t.sub(V,A),A=t.add(V,A),S=t.mul(v,A),V=t.add(P,P),V=t.add(V,P),z=t.mul(L,z),q=t.mul(I,q),V=t.add(V,z),z=t.sub(P,z),z=t.mul(L,z),q=t.add(q,z),P=t.mul(V,q),S=t.add(S,P),P=t.mul(j,q),v=t.mul(W,v),v=t.sub(v,P),P=t.mul(W,V),A=t.mul(j,A),A=t.add(A,P),new C(v,S,A)}subtract($){return this.add($.negate())}is0(){return this.equals(C.ZERO)}multiply($){const{endo:E}=e;if(!r.isValidNot0($))throw new Error("invalid scalar: out of range");let _,T;const N=x=>F.cached(this,x,w=>normalizeZ(C,w));if(E){const{k1neg:x,k1:w,k2neg:v,k2:S}=B($),{p:A,f:L}=N(w),{p:I,f:P}=N(S);T=L.add(P),_=H(E.beta,A,I,x,v)}else{const{p:x,f:w}=N($);_=x,T=w}return normalizeZ(C,[_,T])[0]}multiplyUnsafe($){const{endo:E}=e,_=this;if(!r.isValid($))throw new Error("invalid scalar: out of range");if($===_0n$1||_.is0())return C.ZERO;if($===_1n$1)return _;if(F.hasCache(this))return this.multiply($);if(E){const{k1neg:T,k1:N,k2neg:x,k2:w}=B($),{p1:v,p2:S}=mulEndoUnsafe(C,_,N,w);return H(E.beta,v,S,T,x)}else return F.unsafe(_,$)}multiplyAndAddUnsafe($,E,_){const T=this.multiplyUnsafe(E).add($.multiplyUnsafe(_));return T.is0()?void 0:T}toAffine($){return D(this,$)}isTorsionFree(){const{isTorsionFree:$}=e;return s===_1n$1?!0:$?$(C,this):F.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:$}=e;return s===_1n$1?this:$?$(C,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes($=!0){return abool("isCompressed",$),this.assertValidity(),h(C,this,$)}toRawBytes($=!0){return this.toBytes($)}toHex($=!0){return bytesToHex(this.toBytes($))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}C.BASE=new C(n.Gx,n.Gy,t.ONE),C.ZERO=new C(t.ZERO,t.ONE,t.ZERO),C.Fp=t,C.Fn=r;const M=r.BITS,F=new wNAF(C,e.endo?Math.ceil(M/2):M);return C}function pprefix(n){return Uint8Array.of(n?2:3)}function ecdsa(n,e,t={}){ahash(e),_validateObject(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=t.randomBytes||randomBytes,s=t.hmac||((w,...v)=>hmac(e,w,concatBytes(...v))),{Fp:o,Fn:a}=n,{ORDER:c,BITS:l}=a,f=getMinHashLength(c),h={secret:a.BYTES,public:1+o.BYTES,publicUncompressed:1+2*o.BYTES,signature:2*a.BYTES,seed:f};function u(w){const v=c>>_1n$1;return w>v}function p(w){return u(w)?a.neg(w):w}function y(w,v){if(!a.isValidNot0(v))throw new Error(`invalid signature ${w}: out of range 1..CURVE.n`)}class b{constructor(v,S,A){y("r",v),y("s",S),this.r=v,this.s=S,A!=null&&(this.recovery=A),Object.freeze(this)}static fromBytes(v,S="compact"){if(S==="compact"){const A=a.BYTES;abytes(v,A*2);const L=v.subarray(0,A),I=v.subarray(A,A*2);return new b(a.fromBytes(L),a.fromBytes(I))}if(S==="der"){abytes(v);const{r:A,s:L}=DER.toSig(v);return new b(A,L)}throw new Error("invalid format")}static fromHex(v,S){return this.fromBytes(hexToBytes(v),S)}addRecoveryBit(v){return new b(this.r,this.s,v)}recoverPublicKey(v){const S=o.ORDER,{r:A,s:L,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(c*_2n$1<S&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const V=I===2||I===3?A+c:A;if(!o.isValid(V))throw new Error("recovery id 2 or 3 invalid");const z=o.toBytes(V),W=n.fromHex(concatBytes(pprefix((I&1)===0),z)),q=a.inv(V),j=M(ensureBytes("msgHash",v)),G=a.create(-j*q),Z=a.create(L*q),Y=n.BASE.multiplyUnsafe(G).add(W.multiplyUnsafe(Z));if(Y.is0())throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,a.neg(this.s),this.recovery):this}toBytes(v="compact"){if(v==="compact")return concatBytes(a.toBytes(this.r),a.toBytes(this.s));if(v==="der")return hexToBytes(DER.hexFromSig(this));throw new Error("invalid format")}toHex(v){return bytesToHex(this.toBytes(v))}assertValidity(){}static fromCompact(v){return b.fromBytes(ensureBytes("sig",v),"compact")}static fromDER(v){return b.fromBytes(ensureBytes("sig",v),"der")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex(this.toBytes("compact"))}}function m(w){try{return!!_normFnElement(a,w)}catch{return!1}}function k(w,v){try{const S=w.length;return v===!0&&S!==h.public||v===!1&&S!==h.publicUncompressed?!1:!!n.fromBytes(w)}catch{return!1}}function R(w=r(f)){return mapHashToField(w,c)}const B={isValidSecretKey:m,isValidPublicKey:k,randomSecretKey:R,isValidPrivateKey:m,randomPrivateKey:R,normPrivateKeyToScalar:w=>_normFnElement(a,w),precompute(w=8,v=n.BASE){return v.precompute(w,!1)}};function D(w,v=!0){return n.BASE.multiply(_normFnElement(a,w)).toBytes(v)}function U(w){if(typeof w=="bigint")return!1;if(w instanceof n)return!0;if(a.allowedLengths||h.secret===h.public)return;const v=ensureBytes("key",w).length;return v===h.public||v===h.publicUncompressed}function H(w,v,S=!0){if(U(w)===!0)throw new Error("first arg must be private key");if(U(v)===!1)throw new Error("second arg must be public key");const A=_normFnElement(a,w);return n.fromHex(v).multiply(A).toBytes(S)}const C=t.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const v=bytesToNumberBE(w),S=w.length*8-l;return S>0?v>>BigInt(S):v},M=t.bits2int_modN||function(w){return a.create(C(w))},F=bitMask(l);function O(w){return aInRange("num < 2^"+l,w,_0n$1,F),a.toBytes(w)}function $(w,v,S=E){if(["recovered","canonical"].some(G=>G in S))throw new Error("sign() legacy options not supported");let{lowS:A,prehash:L,extraEntropy:I}=S;A==null&&(A=!0),w=ensureBytes("msgHash",w),validateSigVerOpts(S),L&&(w=ensureBytes("prehashed msgHash",e(w)));const P=M(w),V=_normFnElement(a,v),z=[O(V),O(P)];if(I!=null&&I!==!1){const G=I===!0?r(h.secret):I;z.push(ensureBytes("extraEntropy",G))}const W=concatBytes(...z),q=P;function j(G){const Z=C(G);if(!a.isValidNot0(Z))return;const Y=a.inv(Z),te=n.BASE.multiply(Z).toAffine(),J=a.create(te.x);if(J===_0n$1)return;const K=a.create(Y*a.create(q+J*V));if(K===_0n$1)return;let Q=(te.x===J?0:2)|Number(te.y&_1n$1),Se=K;return A&&u(K)&&(Se=p(K),Q^=1),new b(J,Se,Q)}return{seed:W,k2sig:j}}const E={lowS:t.lowS,prehash:!1},_={lowS:t.lowS,prehash:!1};function T(w,v,S=E){const{seed:A,k2sig:L}=$(w,v,S);return createHmacDrbg(e.outputLen,a.BYTES,s)(A,L)}n.BASE.precompute(8);function N(w,v,S,A=_){const L=w;v=ensureBytes("msgHash",v),S=ensureBytes("publicKey",S),validateSigVerOpts(A);const{lowS:I,prehash:P,format:V}=A;if("strict"in A)throw new Error("options.strict was renamed to lowS");let z,W;if(V===void 0){const q=typeof L=="string"||isBytes$1(L),j=!q&&L!==null&&typeof L=="object"&&typeof L.r=="bigint"&&typeof L.s=="bigint";if(!q&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(j)z=new b(L.r,L.s);else if(q){try{z=b.fromDER(L)}catch(G){if(!(G instanceof DER.Err))throw G}if(!z)try{z=b.fromCompact(L)}catch{return!1}}}else if(V==="compact"||V==="der"){if(typeof L!="string"&&!isBytes$1(L))throw new Error('"der" / "compact" format expects Uint8Array signature');z=b.fromBytes(ensureBytes("sig",L),V)}else if(V==="js"){if(!(L instanceof b))throw new Error('"js" format expects Signature instance');z=L}else throw new Error('format must be "compact", "der" or "js"');if(!z)return!1;try{if(W=n.fromHex(S),I&&z.hasHighS())return!1;P&&(v=e(v));const{r:q,s:j}=z,G=M(v),Z=a.inv(j),Y=a.create(G*Z),te=a.create(q*Z),J=n.BASE.multiplyUnsafe(Y).add(W.multiplyUnsafe(te));return J.is0()?!1:a.create(J.x)===q}catch{return!1}}function x(w){const v=B.randomSecretKey(w);return{secretKey:v,publicKey:D(v)}}return Object.freeze({keygen:x,getPublicKey:D,sign:T,verify:N,getSharedSecret:H,utils:B,Point:n,Signature:b,info:{type:"weierstrass",lengths:h,publicKeyHasPrefix:!0}})}function _weierstrass_legacy_opts_to_new(n){const e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp;let r=n.allowedPrivateKeyLengths?Array.from(new Set(n.allowedPrivateKeyLengths.map(a=>Math.ceil(a/2)))):void 0;const s=Field(e.n,{BITS:n.nBitLength,allowedLengths:r,modOnDecode:n.wrapPrivateKey}),o={Fp:t,Fn:s,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:o}}function _ecdsa_legacy_opts_to_new(n){const{CURVE:e,curveOpts:t}=_weierstrass_legacy_opts_to_new(n),r={hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,hash:n.hash,ecdsaOpts:r}}function _ecdsa_new_output_to_legacy(n,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:n})}function weierstrass(n){const{CURVE:e,curveOpts:t,hash:r,ecdsaOpts:s}=_ecdsa_legacy_opts_to_new(n),o=weierstrassN(e,t),a=ecdsa(o,r,s);return _ecdsa_new_output_to_legacy(n,a)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createCurve(n,e){const t=r=>weierstrass({...n,hash:r});return{...t(e),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},secp256k1_ENDO={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2);function sqrtMod(n){const e=secp256k1_CURVE.p,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),c=BigInt(44),l=BigInt(88),f=n*n*n%e,h=f*f*n%e,u=pow2(h,t,e)*h%e,p=pow2(u,t,e)*h%e,y=pow2(p,_2n,e)*f%e,b=pow2(y,s,e)*y%e,m=pow2(b,o,e)*b%e,k=pow2(m,c,e)*m%e,R=pow2(k,l,e)*k%e,B=pow2(R,c,e)*m%e,D=pow2(B,t,e)*h%e,U=pow2(D,a,e)*b%e,H=pow2(U,r,e)*f%e,C=pow2(H,_2n,e);if(!Fpk1.eql(Fpk1.sqr(C),n))throw new Error("Cannot find square root");return C}const Fpk1=Field(secp256k1_CURVE.p,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$1),TAGGED_HASH_PREFIXES={};function taggedHash(n,...e){let t=TAGGED_HASH_PREFIXES[n];if(t===void 0){const r=sha256$1(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes(r,r),TAGGED_HASH_PREFIXES[n]=t}return sha256$1(concatBytes(t,...e))}const pointToBytes=n=>n.toBytes(!0).slice(1),numTo32b=n=>numberToBytesBE(n,32),modP=n=>mod(n,secp256k1_CURVE.p),modN=n=>mod(n,secp256k1_CURVE.n),Point=(()=>secp256k1.Point)(),hasEven=n=>n%_2n===_0n;function schnorrGetExtPubKey(n){let e=_normFnElement(Point.Fn,n),t=Point.BASE.multiply(e);return{scalar:hasEven(t.y)?e:modN(-e),bytes:pointToBytes(t)}}function lift_x(n){aInRange("x",n,_1n,secp256k1_CURVE.p);const e=modP(n*n),t=modP(e*n+BigInt(7));let r=sqrtMod(t);hasEven(r)||(r=modP(-r));const s=Point.fromAffine({x:n,y:r});return s.assertValidity(),s}const num=bytesToNumberBE;function challenge(...n){return modN(num(taggedHash("BIP0340/challenge",...n)))}function schnorrGetPublicKey(n){return schnorrGetExtPubKey(n).bytes}function schnorrSign(n,e,t=randomBytes(32)){const r=ensureBytes("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey(e),a=ensureBytes("auxRand",t,32),c=numTo32b(o^num(taggedHash("BIP0340/aux",a))),l=taggedHash("BIP0340/nonce",c,s,r),f=modN(num(l));if(f===_0n)throw new Error("sign failed: k is zero");const{bytes:h,scalar:u}=schnorrGetExtPubKey(f),p=challenge(h,s,r),y=new Uint8Array(64);if(y.set(h,0),y.set(numTo32b(modN(u+p*o)),32),!schnorrVerify(y,r,s))throw new Error("sign: Invalid signature produced");return y}function schnorrVerify(n,e,t){const r=ensureBytes("signature",n,64),s=ensureBytes("message",e),o=ensureBytes("publicKey",t,32);try{const a=lift_x(num(o)),c=num(r.subarray(0,32));if(!inRange(c,_1n,secp256k1_CURVE.p))return!1;const l=num(r.subarray(32,64));if(!inRange(l,_1n,secp256k1_CURVE.n))return!1;const f=challenge(numTo32b(c),pointToBytes(a),s),h=Point.BASE.multiplyUnsafe(l).add(a.multiplyUnsafe(modN(-f))),{x:u,y:p}=h.toAffine();return!(h.is0()||!hasEven(p)||u!==c)}catch{return!1}}const schnorr=(()=>{const t=(s=randomBytes(48))=>mapHashToField(s,secp256k1_CURVE.n);secp256k1.utils.randomSecretKey;function r(s){const o=t(s);return{secretKey:o,publicKey:schnorrGetPublicKey(o)}}return{keygen:r,getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,Point,utils:{randomSecretKey:t,randomPrivateKey:t,taggedHash,lift_x,pointToBytes,numberToBytesBE,bytesToNumberBE,mod},info:{type:"weierstrass",publicKeyHasPrefix:!1,lengths:{secret:32,public:32,signature:32*2,seed:48}}}})(),sha256=sha256$1;var dist={},LRUCache$1={},LRUCacheNode$1={};Object.defineProperty(LRUCacheNode$1,"__esModule",{value:!0});LRUCacheNode$1.LRUCacheNode=void 0;class LRUCacheNode{constructor(e,t,r){const{entryExpirationTimeInMS:s=null,next:o=null,prev:a=null,onEntryEvicted:c,onEntryMarkedAsMostRecentlyUsed:l,clone:f,cloneFn:h}=r??{};if(typeof s=="number"&&(s<=0||Number.isNaN(s)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.clone=f??!1,this.cloneFn=h??this.defaultClone,this.key=e,this.internalValue=this.clone?this.cloneFn(t):t,this.created=Date.now(),this.entryExpirationTimeInMS=s,this.next=o,this.prev=a,this.onEntryEvicted=c,this.onEntryMarkedAsMostRecentlyUsed=l}get value(){return this.clone?this.cloneFn(this.internalValue):this.internalValue}get isExpired(){return typeof this.entryExpirationTimeInMS=="number"&&Date.now()-this.created>this.entryExpirationTimeInMS}invokeOnEvicted(){if(this.onEntryEvicted){const{key:e,value:t,isExpired:r}=this;this.onEntryEvicted({key:e,value:t,isExpired:r})}}invokeOnEntryMarkedAsMostRecentlyUsed(){if(this.onEntryMarkedAsMostRecentlyUsed){const{key:e,value:t}=this;this.onEntryMarkedAsMostRecentlyUsed({key:e,value:t})}}defaultClone(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"?e:JSON.parse(JSON.stringify(e))}}LRUCacheNode$1.LRUCacheNode=LRUCacheNode;Object.defineProperty(LRUCache$1,"__esModule",{value:!0});LRUCache$1.LRUCache=void 0;const LRUCacheNode_1=LRUCacheNode$1;class LRUCache{constructor(e){this.lookupTable=new Map,this.head=null,this.tail=null;const{maxSize:t=25,entryExpirationTimeInMS:r=null,onEntryEvicted:s,onEntryMarkedAsMostRecentlyUsed:o,cloneFn:a,clone:c}=e??{};if(Number.isNaN(t)||t<=0)throw new Error("maxSize must be greater than 0.");if(typeof r=="number"&&(r<=0||Number.isNaN(r)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.maxSizeInternal=t,this.entryExpirationTimeInMS=r,this.onEntryEvicted=s,this.onEntryMarkedAsMostRecentlyUsed=o,this.clone=c,this.cloneFn=a}get size(){return this.cleanCache(),this.lookupTable.size}get remainingSize(){return this.maxSizeInternal-this.size}get newest(){return this.head?this.head.isExpired?(this.removeNodeFromListAndLookupTable(this.head),this.newest):this.mapNodeToEntry(this.head):null}get oldest(){return this.tail?this.tail.isExpired?(this.removeNodeFromListAndLookupTable(this.tail),this.oldest):this.mapNodeToEntry(this.tail):null}get maxSize(){return this.maxSizeInternal}set maxSize(e){if(Number.isNaN(e)||e<=0)throw new Error("maxSize must be greater than 0.");this.maxSizeInternal=e,this.enforceSizeLimit()}set(e,t,r){const s=this.lookupTable.get(e);s&&this.removeNodeFromListAndLookupTable(s);const o=new LRUCacheNode_1.LRUCacheNode(e,t,{entryExpirationTimeInMS:this.entryExpirationTimeInMS,onEntryEvicted:this.onEntryEvicted,onEntryMarkedAsMostRecentlyUsed:this.onEntryMarkedAsMostRecentlyUsed,clone:this.clone,cloneFn:this.cloneFn,...r});return this.setNodeAsHead(o),this.lookupTable.set(e,o),this.enforceSizeLimit(),this}get(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):(this.setNodeAsHead(t),t.value):null}peek(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):t.value:null}delete(e){const t=this.lookupTable.get(e);return t?this.removeNodeFromListAndLookupTable(t):!1}has(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),!1):!0:!1}clear(){this.head=null,this.tail=null,this.lookupTable.clear()}find(e){let t=this.head;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}const r=this.mapNodeToEntry(t);if(e(r))return this.setNodeAsHead(t),r;t=t.next}return null}forEach(e){let t=this.head,r=0;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}e(t.value,t.key,r),t=t.next,r++}}*values(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.value,e=e.next}}*keys(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.key,e=e.next}}*entries(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}*[Symbol.iterator](){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}enforceSizeLimit(){let e=this.tail;for(;e!==null&&this.size>this.maxSizeInternal;){const t=e.prev;this.removeNodeFromListAndLookupTable(e),e=t}}mapNodeToEntry({key:e,value:t}){return{key:e,value:t}}setNodeAsHead(e){this.removeNodeFromList(e),this.head?(e.next=this.head,this.head.prev=e,this.head=e):(this.head=e,this.tail=e),e.invokeOnEntryMarkedAsMostRecentlyUsed()}removeNodeFromList(e){e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.head===e&&(this.head=e.next),this.tail===e&&(this.tail=e.prev),e.next=null,e.prev=null}removeNodeFromListAndLookupTable(e){return e.invokeOnEvicted(),this.removeNodeFromList(e),this.lookupTable.delete(e.key)}cleanCache(){if(!this.entryExpirationTimeInMS)return;const e=[];for(const t of this.lookupTable.values())t.isExpired&&e.push(t);e.forEach(t=>this.removeNodeFromListAndLookupTable(t))}}LRUCache$1.LRUCache=LRUCache;(function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var c=Object.getOwnPropertyDescriptor(s,o);(!c||("get"in c?!s.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,c)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(LRUCache$1,n)})(dist);var lib={};(function(n){/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(n,"__esModule",{value:!0}),n.bytes=n.stringToBytes=n.str=n.bytesToString=n.hex=n.utf8=n.bech32m=n.bech32=n.base58check=n.base58xmr=n.base58xrp=n.base58flickr=n.base58=n.base64url=n.base64=n.base32crockford=n.base32hex=n.base32=n.base16=n.utils=n.assertNumber=void 0;function e(E){if(!Number.isSafeInteger(E))throw new Error(`Wrong integer: ${E}`)}n.assertNumber=e;function t(...E){const _=(x,w)=>v=>x(w(v)),T=Array.from(E).reverse().reduce((x,w)=>x?_(x,w.encode):w.encode,void 0),N=E.reduce((x,w)=>x?_(x,w.decode):w.decode,void 0);return{encode:T,decode:N}}function r(E){return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return _.map(T=>{if(e(T),T<0||T>=E.length)throw new Error(`Digit index outside alphabet: ${T} (alphabet: ${E.length})`);return E[T]})},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("alphabet.decode input should be array of strings");return _.map(T=>{if(typeof T!="string")throw new Error(`alphabet.decode: not string element=${T}`);const N=E.indexOf(T);if(N===-1)throw new Error(`Unknown letter: "${T}". Allowed: ${E}`);return N})}}}function s(E=""){if(typeof E!="string")throw new Error("join separator should be string");return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("join.encode input should be array of strings");for(let T of _)if(typeof T!="string")throw new Error(`join.encode: non-string input=${T}`);return _.join(E)},decode:_=>{if(typeof _!="string")throw new Error("join.decode input should be string");return _.split(E)}}}function o(E,_="="){if(e(E),typeof _!="string")throw new Error("padding chr should be string");return{encode(T){if(!Array.isArray(T)||T.length&&typeof T[0]!="string")throw new Error("padding.encode input should be array of strings");for(let N of T)if(typeof N!="string")throw new Error(`padding.encode: non-string input=${N}`);for(;T.length*E%8;)T.push(_);return T},decode(T){if(!Array.isArray(T)||T.length&&typeof T[0]!="string")throw new Error("padding.encode input should be array of strings");for(let x of T)if(typeof x!="string")throw new Error(`padding.decode: non-string input=${x}`);let N=T.length;if(N*E%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;N>0&&T[N-1]===_;N--)if(!((N-1)*E%8))throw new Error("Invalid padding: string has too much padding");return T.slice(0,N)}}}function a(E){if(typeof E!="function")throw new Error("normalize fn should be function");return{encode:_=>_,decode:_=>E(_)}}function c(E,_,T){if(_<2)throw new Error(`convertRadix: wrong from=${_}, base cannot be less than 2`);if(T<2)throw new Error(`convertRadix: wrong to=${T}, base cannot be less than 2`);if(!Array.isArray(E))throw new Error("convertRadix: data should be array");if(!E.length)return[];let N=0;const x=[],w=Array.from(E);for(w.forEach(v=>{if(e(v),v<0||v>=_)throw new Error(`Wrong integer: ${v}`)});;){let v=0,S=!0;for(let A=N;A<w.length;A++){const L=w[A],I=_*v+L;if(!Number.isSafeInteger(I)||_*v/_!==v||I-L!==_*v)throw new Error("convertRadix: carry overflow");if(v=I%T,w[A]=Math.floor(I/T),!Number.isSafeInteger(w[A])||w[A]*T+v!==I)throw new Error("convertRadix: carry overflow");if(S)w[A]?S=!1:N=A;else continue}if(x.push(v),S)break}for(let v=0;v<E.length-1&&E[v]===0;v++)x.push(0);return x.reverse()}const l=(E,_)=>_?l(_,E%_):E,f=(E,_)=>E+(_-l(E,_));function h(E,_,T,N){if(!Array.isArray(E))throw new Error("convertRadix2: data should be array");if(_<=0||_>32)throw new Error(`convertRadix2: wrong from=${_}`);if(T<=0||T>32)throw new Error(`convertRadix2: wrong to=${T}`);if(f(_,T)>32)throw new Error(`convertRadix2: carry overflow from=${_} to=${T} carryBits=${f(_,T)}`);let x=0,w=0;const v=2**T-1,S=[];for(const A of E){if(e(A),A>=2**_)throw new Error(`convertRadix2: invalid data word=${A} from=${_}`);if(x=x<<_|A,w+_>32)throw new Error(`convertRadix2: carry overflow pos=${w} from=${_}`);for(w+=_;w>=T;w-=T)S.push((x>>w-T&v)>>>0);x&=2**w-1}if(x=x<<T-w&v,!N&&w>=_)throw new Error("Excess padding");if(!N&&x)throw new Error(`Non-zero padding: ${x}`);return N&&w>0&&S.push(x>>>0),S}function u(E){return e(E),{encode:_=>{if(!(_ instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(_),2**8,E)},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(_,E,2**8))}}}function p(E,_=!1){if(e(E),E<=0||E>32)throw new Error("radix2: bits should be in (0..32]");if(f(8,E)>32||f(E,8)>32)throw new Error("radix2: carry overflow");return{encode:T=>{if(!(T instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(T),8,E,!_)},decode:T=>{if(!Array.isArray(T)||T.length&&typeof T[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(T,E,8,_))}}}function y(E){if(typeof E!="function")throw new Error("unsafeWrapper fn should be function");return function(..._){try{return E.apply(null,_)}catch{}}}function b(E,_){if(e(E),typeof _!="function")throw new Error("checksum fn should be function");return{encode(T){if(!(T instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const N=_(T).slice(0,E),x=new Uint8Array(T.length+E);return x.set(T),x.set(N,T.length),x},decode(T){if(!(T instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const N=T.slice(0,-E),x=_(N).slice(0,E),w=T.slice(-E);for(let v=0;v<E;v++)if(x[v]!==w[v])throw new Error("Invalid checksum");return N}}}n.utils={alphabet:r,chain:t,checksum:b,radix:u,radix2:p,join:s,padding:o},n.base16=t(p(4),r("0123456789ABCDEF"),s("")),n.base32=t(p(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),o(5),s("")),n.base32hex=t(p(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),o(5),s("")),n.base32crockford=t(p(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),s(""),a(E=>E.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),n.base64=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),o(6),s("")),n.base64url=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),o(6),s(""));const m=E=>t(u(58),r(E),s(""));n.base58=m("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),n.base58flickr=m("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),n.base58xrp=m("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const k=[0,2,3,5,6,7,9,10,11];n.base58xmr={encode(E){let _="";for(let T=0;T<E.length;T+=8){const N=E.subarray(T,T+8);_+=n.base58.encode(N).padStart(k[N.length],"1")}return _},decode(E){let _=[];for(let T=0;T<E.length;T+=11){const N=E.slice(T,T+11),x=k.indexOf(N.length),w=n.base58.decode(N);for(let v=0;v<w.length-x;v++)if(w[v]!==0)throw new Error("base58xmr: wrong padding");_=_.concat(Array.from(w.slice(w.length-x)))}return Uint8Array.from(_)}};const R=E=>t(b(4,_=>E(E(_))),n.base58);n.base58check=R;const B=t(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),D=[996825010,642813549,513874426,1027748829,705979059];function U(E){const _=E>>25;let T=(E&33554431)<<5;for(let N=0;N<D.length;N++)(_>>N&1)===1&&(T^=D[N]);return T}function H(E,_,T=1){const N=E.length;let x=1;for(let w=0;w<N;w++){const v=E.charCodeAt(w);if(v<33||v>126)throw new Error(`Invalid prefix (${E})`);x=U(x)^v>>5}x=U(x);for(let w=0;w<N;w++)x=U(x)^E.charCodeAt(w)&31;for(let w of _)x=U(x)^w;for(let w=0;w<6;w++)x=U(x);return x^=T,B.encode(h([x%2**30],30,5,!1))}function C(E){const _=E==="bech32"?1:734539939,T=p(5),N=T.decode,x=T.encode,w=y(N);function v(I,P,V=90){if(typeof I!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof I}`);if(!Array.isArray(P)||P.length&&typeof P[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof P}`);const z=I.length+7+P.length;if(V!==!1&&z>V)throw new TypeError(`Length ${z} exceeds limit ${V}`);return I=I.toLowerCase(),`${I}1${B.encode(P)}${H(I,P,_)}`}function S(I,P=90){if(typeof I!="string")throw new Error(`bech32.decode input should be string, not ${typeof I}`);if(I.length<8||P!==!1&&I.length>P)throw new TypeError(`Wrong string length: ${I.length} (${I}). Expected (8..${P})`);const V=I.toLowerCase();if(I!==V&&I!==I.toUpperCase())throw new Error("String must be lowercase or uppercase");I=V;const z=I.lastIndexOf("1");if(z===0||z===-1)throw new Error('Letter "1" must be present between prefix and data only');const W=I.slice(0,z),q=I.slice(z+1);if(q.length<6)throw new Error("Data must be at least 6 characters long");const j=B.decode(q).slice(0,-6),G=H(W,j,_);if(!q.endsWith(G))throw new Error(`Invalid checksum in ${I}: expected "${G}"`);return{prefix:W,words:j}}const A=y(S);function L(I){const{prefix:P,words:V}=S(I,!1);return{prefix:P,words:V,bytes:N(V)}}return{encode:v,decode:S,decodeToBytes:L,decodeUnsafe:A,fromWords:N,fromWordsUnsafe:w,toWords:x}}n.bech32=C("bech32"),n.bech32m=C("bech32m"),n.utf8={encode:E=>new TextDecoder().decode(E),decode:E=>new TextEncoder().encode(E)},n.hex=t(p(4),r("0123456789abcdef"),s(""),a(E=>{if(typeof E!="string"||E.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof E} with length ${E.length}`);return E.toLowerCase()}));const M={utf8:n.utf8,hex:n.hex,base16:n.base16,base32:n.base32,base64:n.base64,base64url:n.base64url,base58:n.base58,base58xmr:n.base58xmr},F=`Invalid encoding type. Available types: ${Object.keys(M).join(", ")}`,O=(E,_)=>{if(typeof E!="string"||!M.hasOwnProperty(E))throw new TypeError(F);if(!(_ instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return M[E].encode(_)};n.bytesToString=O,n.str=n.bytesToString;const $=(E,_)=>{if(!M.hasOwnProperty(E))throw new TypeError(F);if(typeof _!="string")throw new TypeError("stringToBytes() expects string");return M[E].decode(_)};n.stringToBytes=$,n.bytes=n.stringToBytes})(lib);const{bech32:bech32$1,hex,utf8}=lib,DEFAULTNETWORK={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},TESTNETWORK={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},SIGNETNETWORK={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},REGTESTNETWORK={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},SIMNETWORK={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},FEATUREBIT_ORDER=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],DIVISORS={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},MAX_MILLISATS=BigInt("2100000000000000000"),MILLISATS_PER_BTC=BigInt(1e11),TAGCODES={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},TAGNAMES={};for(let n=0,e=Object.keys(TAGCODES);n<e.length;n++){const t=e[n],r=TAGCODES[e[n]].toString();TAGNAMES[r]=t}const TAGPARSERS={1:n=>hex.encode(bech32$1.fromWordsUnsafe(n)),16:n=>hex.encode(bech32$1.fromWordsUnsafe(n)),13:n=>utf8.encode(bech32$1.fromWordsUnsafe(n)),19:n=>hex.encode(bech32$1.fromWordsUnsafe(n)),23:n=>hex.encode(bech32$1.fromWordsUnsafe(n)),27:n=>hex.encode(bech32$1.fromWordsUnsafe(n)),6:wordsToIntBE,24:wordsToIntBE,3:routingInfoParser,5:featureBitsParser};function getUnknownParser(n){return e=>({tagCode:parseInt(n),words:bech32$1.encode("unknown",e,Number.MAX_SAFE_INTEGER)})}function wordsToIntBE(n){return n.reverse().reduce((e,t,r)=>e+t*Math.pow(32,r),0)}function routingInfoParser(n){const e=[];let t,r,s,o,a,c=bech32$1.fromWordsUnsafe(n);for(;c.length>0;)t=hex.encode(c.slice(0,33)),r=hex.encode(c.slice(33,41)),s=parseInt(hex.encode(c.slice(41,45)),16),o=parseInt(hex.encode(c.slice(45,49)),16),a=parseInt(hex.encode(c.slice(49,51)),16),c=c.slice(51),e.push({pubkey:t,short_channel_id:r,fee_base_msat:s,fee_proportional_millionths:o,cltv_expiry_delta:a});return e}function featureBitsParser(n){const e=n.slice().reverse().map(s=>[!!(s&1),!!(s&2),!!(s&4),!!(s&8),!!(s&16)]).reduce((s,o)=>s.concat(o),[]);for(;e.length<FEATUREBIT_ORDER.length*2;)e.push(!1);const t={};FEATUREBIT_ORDER.forEach((s,o)=>{let a;e[o*2]?a="required":e[o*2+1]?a="supported":a="unsupported",t[s]=a});const r=e.slice(FEATUREBIT_ORDER.length*2);return t.extra_bits={start_bit:FEATUREBIT_ORDER.length*2,bits:r,has_required:r.reduce((s,o,a)=>a%2!==0?s||!1:s||o,!1)},t}function hrpToMillisat(n,e){let t,r;if(n.slice(-1).match(/^[munp]$/))t=n.slice(-1),r=n.slice(0,-1);else{if(n.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");r=n}if(!r.match(/^\d+$/))throw new Error("Not a valid human readable amount");const s=BigInt(r),o=t?s*MILLISATS_PER_BTC/DIVISORS[t]:s*MILLISATS_PER_BTC;if(t==="p"&&s%BigInt(10)!==BigInt(0)||o>MAX_MILLISATS)throw new Error("Amount is outside of valid range");return e?o.toString():o}function decode(n,e){if(typeof n!="string")throw new Error("Lightning Payment Request must be string");if(n.slice(0,2).toLowerCase()!=="ln")throw new Error("Not a proper lightning payment request");const t=[],r=bech32$1.decode(n,Number.MAX_SAFE_INTEGER);n=n.toLowerCase();const s=r.prefix;let o=r.words,a=n.slice(s.length+1),c=o.slice(-104);o=o.slice(0,-104);let l=s.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(l&&!l[2]&&(l=s.match(/^ln(\S+)$/)),!l)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const f=l[1];let h;if(e){if(e.bech32===void 0||e.pubKeyHash===void 0||e.scriptHash===void 0||!Array.isArray(e.validWitnessVersions))throw new Error("Invalid network");h=e}else switch(f){case DEFAULTNETWORK.bech32:h=DEFAULTNETWORK;break;case TESTNETWORK.bech32:h=TESTNETWORK;break;case SIGNETNETWORK.bech32:h=SIGNETNETWORK;break;case REGTESTNETWORK.bech32:h=REGTESTNETWORK;break;case SIMNETWORK.bech32:h=SIMNETWORK;break}if(!h||h.bech32!==f)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:f,value:h});const u=l[2];let p;if(u){const U=l[3];p=hrpToMillisat(u+U,!0),t.push({name:"amount",letters:l[2]+l[3],value:p})}else p=null;t.push({name:"separator",letters:"1"});const y=wordsToIntBE(o.slice(0,7));o=o.slice(7),t.push({name:"timestamp",letters:a.slice(0,7),value:y}),a=a.slice(7);let b,m,k,R;for(;o.length>0;){const U=o[0].toString();b=TAGNAMES[U]||"unknown_tag",m=TAGPARSERS[U]||getUnknownParser(U),o=o.slice(1),k=wordsToIntBE(o.slice(0,2)),o=o.slice(2),R=o.slice(0,k),o=o.slice(k),t.push({name:b,tag:a[0],letters:a.slice(0,1+2+k),value:m(R)}),a=a.slice(1+2+k)}t.push({name:"signature",letters:a.slice(0,104),value:hex.encode(bech32$1.fromWordsUnsafe(c))}),a=a.slice(104),t.push({name:"checksum",letters:a});let B={paymentRequest:n,sections:t,get expiry(){let U=t.find(H=>H.name==="expiry");if(U)return D("timestamp")+U.value},get route_hints(){return t.filter(U=>U.name==="route_hint").map(U=>U.value)}};for(let U in TAGCODES)U!=="route_hint"&&Object.defineProperty(B,U,{get(){return D(U)}});return B;function D(U){let H=t.find(C=>C.name===U);return H?H.value:void 0}}var bolt11={decode,hrpToMillisat};/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function isArrayOf(n,e){return Array.isArray(e)?e.length===0?!0:n?e.every(t=>typeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function afn(n){if(typeof n!="function")throw new Error("function expected");return!0}function astr(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function anumber(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function aArr(n){if(!Array.isArray(n))throw new Error("array expected")}function astrArr(n,e){if(!isArrayOf(!0,e))throw new Error(`${n}: array of strings expected`)}function anumArr(n,e){if(!isArrayOf(!1,e))throw new Error(`${n}: array of numbers expected`)}function chain(...n){const e=o=>o,t=(o,a)=>c=>o(a(c)),r=n.map(o=>o.encode).reduceRight(t,e),s=n.map(o=>o.decode).reduce(t,e);return{encode:r,decode:s}}function alphabet(n){const e=typeof n=="string"?n.split(""):n,t=e.length;astrArr("alphabet",e);const r=new Map(e.map((s,o)=>[s,o]));return{encode:s=>(aArr(s),s.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${n}`);return e[o]})),decode:s=>(aArr(s),s.map(o=>{astr("alphabet.decode",o);const a=r.get(o);if(a===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${n}`);return a}))}}function join(n=""){return astr("join",n),{encode:e=>(astrArr("join.decode",e),e.join(n)),decode:e=>(astr("join.decode",e),e.split(n))}}const gcd=(n,e)=>e===0?n:gcd(e,n%e),radix2carry=(n,e)=>n+(e-gcd(n,e)),powers=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function convertRadix2(n,e,t,r){if(aArr(n),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(radix2carry(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${radix2carry(e,t)}`);let s=0,o=0;const a=powers[e],c=powers[t]-1,l=[];for(const f of n){if(anumber(f),f>=a)throw new Error(`convertRadix2: invalid data word=${f} from=${e}`);if(s=s<<e|f,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)l.push((s>>o-t&c)>>>0);const h=powers[o];if(h===void 0)throw new Error("invalid carry");s&=h-1}if(s=s<<t-o&c,!r&&o>=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&l.push(s>>>0),l}function radix2(n,e=!1){if(anumber(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,n)>32||radix2carry(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!isBytes(t))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(t),8,n,!e)},decode:t=>(anumArr("radix2.decode",t),Uint8Array.from(convertRadix2(t,n,8,e)))}}function unsafeWrapper(n){return afn(n),function(...e){try{return n.apply(null,e)}catch{}}}const BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(n){const e=n>>25;let t=(n&33554431)<<5;for(let r=0;r<POLYMOD_GENERATORS.length;r++)(e>>r&1)===1&&(t^=POLYMOD_GENERATORS[r]);return t}function bechChecksum(n,e,t=1){const r=n.length;let s=1;for(let o=0;o<r;o++){const a=n.charCodeAt(o);if(a<33||a>126)throw new Error(`Invalid prefix (${n})`);s=bech32Polymod(s)^a>>5}s=bech32Polymod(s);for(let o=0;o<r;o++)s=bech32Polymod(s)^n.charCodeAt(o)&31;for(let o of e)s=bech32Polymod(s)^o;for(let o=0;o<6;o++)s=bech32Polymod(s);return s^=t,BECH_ALPHABET.encode(convertRadix2([s%powers[30]],30,5,!1))}function genBech32(n){const e=n==="bech32"?1:734539939,t=radix2(5),r=t.decode,s=t.encode,o=unsafeWrapper(r);function a(u,p,y=90){astr("bech32.encode prefix",u),isBytes(p)&&(p=Array.from(p)),anumArr("bech32.encode",p);const b=u.length;if(b===0)throw new TypeError(`Invalid prefix length ${b}`);const m=b+7+p.length;if(y!==!1&&m>y)throw new TypeError(`Length ${m} exceeds limit ${y}`);const k=u.toLowerCase(),R=bechChecksum(k,p,e);return`${k}1${BECH_ALPHABET.encode(p)}${R}`}function c(u,p=90){astr("bech32.decode input",u);const y=u.length;if(y<8||p!==!1&&y>p)throw new TypeError(`invalid string length: ${y} (${u}). Expected (8..${p})`);const b=u.toLowerCase();if(u!==b&&u!==u.toUpperCase())throw new Error("String must be lowercase or uppercase");const m=b.lastIndexOf("1");if(m===0||m===-1)throw new Error('Letter "1" must be present between prefix and data only');const k=b.slice(0,m),R=b.slice(m+1);if(R.length<6)throw new Error("Data must be at least 6 characters long");const B=BECH_ALPHABET.decode(R).slice(0,-6),D=bechChecksum(k,B,e);if(!R.endsWith(D))throw new Error(`Invalid checksum in ${u}: expected "${D}"`);return{prefix:k,words:B}}const l=unsafeWrapper(c);function f(u){const{prefix:p,words:y}=c(u,!1);return{prefix:p,words:y,bytes:r(y)}}function h(u,p){return a(u,s(p))}return{encode:a,decode:c,encodeFromBytes:h,decodeToBytes:f,decodeUnsafe:l,fromWords:r,fromWordsUnsafe:o,toWords:s}}const bech32=genBech32("bech32");var NdkNutzapStatus=(n=>(n.INITIAL="initial",n.PROCESSING="processing",n.REDEEMED="redeemed",n.SPENT="spent",n.MISSING_PRIVKEY="missing_privkey",n.TEMPORARY_ERROR="temporary_error",n.PERMANENT_ERROR="permanent_error",n.INVALID_NUTZAP="invalid_nutzap",n))(NdkNutzapStatus||{}),NDKKind=(n=>(n[n.Metadata=0]="Metadata",n[n.Text=1]="Text",n[n.RecommendRelay=2]="RecommendRelay",n[n.Contacts=3]="Contacts",n[n.EncryptedDirectMessage=4]="EncryptedDirectMessage",n[n.EventDeletion=5]="EventDeletion",n[n.Repost=6]="Repost",n[n.Reaction=7]="Reaction",n[n.BadgeAward=8]="BadgeAward",n[n.GroupChat=9]="GroupChat",n[n.Thread=11]="Thread",n[n.GroupReply=12]="GroupReply",n[n.GiftWrapSeal=13]="GiftWrapSeal",n[n.PrivateDirectMessage=14]="PrivateDirectMessage",n[n.Image=20]="Image",n[n.Video=21]="Video",n[n.ShortVideo=22]="ShortVideo",n[n.Story=23]="Story",n[n.Vanish=62]="Vanish",n[n.CashuWalletBackup=375]="CashuWalletBackup",n[n.GiftWrap=1059]="GiftWrap",n[n.GenericRepost=16]="GenericRepost",n[n.ChannelCreation=40]="ChannelCreation",n[n.ChannelMetadata=41]="ChannelMetadata",n[n.ChannelMessage=42]="ChannelMessage",n[n.ChannelHideMessage=43]="ChannelHideMessage",n[n.ChannelMuteUser=44]="ChannelMuteUser",n[n.WikiMergeRequest=818]="WikiMergeRequest",n[n.GenericReply=1111]="GenericReply",n[n.Media=1063]="Media",n[n.DraftCheckpoint=1234]="DraftCheckpoint",n[n.Task=1934]="Task",n[n.Report=1984]="Report",n[n.Label=1985]="Label",n[n.DVMReqTextExtraction=5e3]="DVMReqTextExtraction",n[n.DVMReqTextSummarization=5001]="DVMReqTextSummarization",n[n.DVMReqTextTranslation=5002]="DVMReqTextTranslation",n[n.DVMReqTextGeneration=5050]="DVMReqTextGeneration",n[n.DVMReqImageGeneration=5100]="DVMReqImageGeneration",n[n.DVMReqTextToSpeech=5250]="DVMReqTextToSpeech",n[n.DVMReqDiscoveryNostrContent=5300]="DVMReqDiscoveryNostrContent",n[n.DVMReqDiscoveryNostrPeople=5301]="DVMReqDiscoveryNostrPeople",n[n.DVMReqTimestamping=5900]="DVMReqTimestamping",n[n.DVMEventSchedule=5905]="DVMEventSchedule",n[n.DVMJobFeedback=7e3]="DVMJobFeedback",n[n.Subscribe=7001]="Subscribe",n[n.Unsubscribe=7002]="Unsubscribe",n[n.SubscriptionReceipt=7003]="SubscriptionReceipt",n[n.CashuReserve=7373]="CashuReserve",n[n.CashuQuote=7374]="CashuQuote",n[n.CashuToken=7375]="CashuToken",n[n.CashuWalletTx=7376]="CashuWalletTx",n[n.GroupAdminAddUser=9e3]="GroupAdminAddUser",n[n.GroupAdminRemoveUser=9001]="GroupAdminRemoveUser",n[n.GroupAdminEditMetadata=9002]="GroupAdminEditMetadata",n[n.GroupAdminEditStatus=9006]="GroupAdminEditStatus",n[n.GroupAdminCreateGroup=9007]="GroupAdminCreateGroup",n[n.GroupAdminRequestJoin=9021]="GroupAdminRequestJoin",n[n.MuteList=1e4]="MuteList",n[n.PinList=10001]="PinList",n[n.RelayList=10002]="RelayList",n[n.BookmarkList=10003]="BookmarkList",n[n.CommunityList=10004]="CommunityList",n[n.PublicChatList=10005]="PublicChatList",n[n.BlockRelayList=10006]="BlockRelayList",n[n.SearchRelayList=10007]="SearchRelayList",n[n.SimpleGroupList=10009]="SimpleGroupList",n[n.InterestList=10015]="InterestList",n[n.CashuMintList=10019]="CashuMintList",n[n.EmojiList=10030]="EmojiList",n[n.DirectMessageReceiveRelayList=10050]="DirectMessageReceiveRelayList",n[n.BlossomList=10063]="BlossomList",n[n.NostrWaletConnectInfo=13194]="NostrWaletConnectInfo",n[n.TierList=17e3]="TierList",n[n.CashuWallet=17375]="CashuWallet",n[n.FollowSet=3e4]="FollowSet",n[n.CategorizedPeopleList=3e4]="CategorizedPeopleList",n[n.CategorizedBookmarkList=30001]="CategorizedBookmarkList",n[n.RelaySet=30002]="RelaySet",n[n.CategorizedRelayList=30002]="CategorizedRelayList",n[n.BookmarkSet=30003]="BookmarkSet",n[n.CurationSet=30004]="CurationSet",n[n.ArticleCurationSet=30004]="ArticleCurationSet",n[n.VideoCurationSet=30005]="VideoCurationSet",n[n.ImageCurationSet=30006]="ImageCurationSet",n[n.InterestSet=30015]="InterestSet",n[n.InterestsList=30015]="InterestsList",n[n.ProjectTemplate=30717]="ProjectTemplate",n[n.EmojiSet=30030]="EmojiSet",n[n.ModularArticle=30040]="ModularArticle",n[n.ModularArticleItem=30041]="ModularArticleItem",n[n.Wiki=30818]="Wiki",n[n.Draft=31234]="Draft",n[n.Project=31933]="Project",n[n.SubscriptionTier=37001]="SubscriptionTier",n[n.EcashMintRecommendation=38e3]="EcashMintRecommendation",n[n.HighlightSet=39802]="HighlightSet",n[n.CategorizedHighlightList=39802]="CategorizedHighlightList",n[n.Nutzap=9321]="Nutzap",n[n.ZapRequest=9734]="ZapRequest",n[n.Zap=9735]="Zap",n[n.Highlight=9802]="Highlight",n[n.ClientAuth=22242]="ClientAuth",n[n.NostrWalletConnectReq=23194]="NostrWalletConnectReq",n[n.NostrWalletConnectRes=23195]="NostrWalletConnectRes",n[n.NostrConnect=24133]="NostrConnect",n[n.BlossomUpload=24242]="BlossomUpload",n[n.HttpAuth=27235]="HttpAuth",n[n.ProfileBadge=30008]="ProfileBadge",n[n.BadgeDefinition=30009]="BadgeDefinition",n[n.MarketStall=30017]="MarketStall",n[n.MarketProduct=30018]="MarketProduct",n[n.Article=30023]="Article",n[n.AppSpecificData=30078]="AppSpecificData",n[n.Classified=30402]="Classified",n[n.HorizontalVideo=34235]="HorizontalVideo",n[n.VerticalVideo=34236]="VerticalVideo",n[n.LegacyCashuWallet=37375]="LegacyCashuWallet",n[n.GroupMetadata=39e3]="GroupMetadata",n[n.GroupAdmins=39001]="GroupAdmins",n[n.GroupMembers=39002]="GroupMembers",n[n.FollowPack=39089]="FollowPack",n[n.MediaFollowPack=39092]="MediaFollowPack",n[n.AppRecommendation=31989]="AppRecommendation",n[n.AppHandler=31990]="AppHandler",n))(NDKKind||{}),NDKListKinds=[1e4,10001,10002,10003,10004,10005,10006,10007,10015,10030,10050,3e4,30003,30001,30002,30004,30005,30015,30030,39802];function getRelaysForSync(n,e,t="write"){if(!n.outboxTracker)return;const r=n.outboxTracker.data.get(e);if(r)return t==="write"?r.writeRelays:r.readRelays}async function getWriteRelaysFor(n,e,t="write"){if(n.outboxTracker)return n.outboxTracker.data.has(e)||await n.outboxTracker.trackUsers([e]),getRelaysForSync(n,e,t)}function getTopRelaysForAuthors(n,e){const t=new Map;return e.forEach(s=>{const o=getRelaysForSync(n,s);o&&o.forEach(a=>{const c=t.get(a)||0;t.set(a,c+1)})}),Array.from(t.entries()).sort((s,o)=>o[1]-s[1]).map(s=>s[0])}function getAllRelaysForAllPubkeys(n,e,t="read"){const r=new Map,s=new Set;return e.forEach(o=>{const a=getRelaysForSync(n,o,t);a&&a.size>0?(a.forEach(c=>{(r.get(c)||new Set).add(o)}),r.set(o,a)):s.add(o)}),{pubkeysToRelays:r,authorsMissingRelays:s}}function chooseRelayCombinationForPubkeys(n,e,t,{count:r,preferredRelays:s}={}){r??(r=2),s??(s=new Set);const o=n.pool,a=o.connectedRelays();a.forEach(p=>{s==null||s.add(p.url)});const c=new Map,{pubkeysToRelays:l,authorsMissingRelays:f}=getAllRelaysForAllPubkeys(n,e,t),h=getTopRelaysForAuthors(n,e),u=(p,y)=>{const b=c.get(y)||[];b.push(p),c.set(y,b)};for(const[p,y]of l.entries()){let b=r;for(const m of a)y.has(m.url)&&(u(p,m.url),b--);for(const m of y)c.has(m)&&(u(p,m),b--);if(!(b<=0))for(const m of h){if(b<=0)break;y.has(m)&&(u(p,m),b--)}}for(const p of f)o.permanentAndConnectedRelays().forEach(y=>{const b=c.get(y.url)||[];b.push(p),c.set(y.url,b)});return c}function getRelaysForFilterWithAuthors(n,e,t=2){return chooseRelayCombinationForPubkeys(n,e,"write",{count:t})}function tryNormalizeRelayUrl(n){try{return normalizeRelayUrl(n)}catch{return}}function normalizeRelayUrl(n){let e=normalizeUrl(n,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return e.endsWith("/")||(e+="/"),e}function normalize(n){const e=new Set;for(const t of n)try{e.add(normalizeRelayUrl(t))}catch{}return Array.from(e)}var DATA_URL_DEFAULT_MIME_TYPE="text/plain",DATA_URL_DEFAULT_CHARSET="us-ascii",testParameter=(n,e)=>e.some(t=>t instanceof RegExp?t.test(n):t===n),supportedProtocols=new Set(["https:","http:","file:"]),hasCustomProtocol=n=>{try{const{protocol:e}=new URL(n);return e.endsWith(":")&&!e.includes(".")&&!supportedProtocols.has(e)}catch{return!1}},normalizeDataURL=(n,{stripHash:e})=>{var u,p,y,b;const t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(n);if(!t)throw new Error(`Invalid URL: ${n}`);const r=((u=t.groups)==null?void 0:u.type)??"",s=((p=t.groups)==null?void 0:p.data)??"";let o=((y=t.groups)==null?void 0:y.hash)??"";const a=r.split(";");o=e?"":o;let c=!1;a[a.length-1]==="base64"&&(a.pop(),c=!0);const l=((b=a.shift())==null?void 0:b.toLowerCase())??"",h=[...a.map(m=>{let[k,R=""]=m.split("=").map(B=>B.trim());return k==="charset"&&(R=R.toLowerCase(),R===DATA_URL_DEFAULT_CHARSET)?"":`${k}${R?`=${R}`:""}`}).filter(Boolean)];return c&&h.push("base64"),(h.length>0||l&&l!==DATA_URL_DEFAULT_MIME_TYPE)&&h.unshift(l),`data:${h.join(";")},${c?s.trim():s}${o?`#${o}`:""}`};function normalizeUrl(n,e={}){if(e={defaultProtocol:"http",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,removeExplicitPort:!1,sortQueryParameters:!0,...e},typeof e.defaultProtocol=="string"&&!e.defaultProtocol.endsWith(":")&&(e.defaultProtocol=`${e.defaultProtocol}:`),n=n.trim(),/^data:/i.test(n))return normalizeDataURL(n,e);if(hasCustomProtocol(n))return n;const t=n.startsWith("//");!t&&/^\.*\//.test(n)||(n=n.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));const s=new URL(n);if(s.hostname=s.hostname.toLowerCase(),e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&s.protocol==="https:"&&(s.protocol="http:"),e.forceHttps&&s.protocol==="http:"&&(s.protocol="https:"),e.stripAuthentication&&(s.username="",s.password=""),e.stripHash?s.hash="":e.stripTextFragment&&(s.hash=s.hash.replace(/#?:~:text.*?$/i,"")),s.pathname){const a=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let c=0,l="";for(;;){const h=a.exec(s.pathname);if(!h)break;const u=h[0],p=h.index,y=s.pathname.slice(c,p);l+=y.replace(/\/{2,}/g,"/"),l+=u,c=p+u.length}const f=s.pathname.slice(c,s.pathname.length);l+=f.replace(/\/{2,}/g,"/"),s.pathname=l}if(s.pathname)try{s.pathname=decodeURI(s.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let a=s.pathname.split("/");const c=a[a.length-1];testParameter(c,e.removeDirectoryIndex)&&(a=a.slice(0,-1),s.pathname=`${a.slice(1).join("/")}/`)}if(s.hostname&&(s.hostname=s.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(s.hostname)&&(s.hostname=s.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(const a of[...s.searchParams.keys()])testParameter(a,e.removeQueryParameters)&&s.searchParams.delete(a);if(!Array.isArray(e.keepQueryParameters)&&e.removeQueryParameters===!0&&(s.search=""),Array.isArray(e.keepQueryParameters)&&e.keepQueryParameters.length>0)for(const a of[...s.searchParams.keys()])testParameter(a,e.keepQueryParameters)||s.searchParams.delete(a);if(e.sortQueryParameters){s.searchParams.sort();try{s.search=decodeURIComponent(s.search)}catch{}}e.removeTrailingSlash&&(s.pathname=s.pathname.replace(/\/$/,"")),e.removeExplicitPort&&s.port&&(s.port="");const o=n;return n=s.toString(),!e.removeSingleSlash&&s.pathname==="/"&&!o.endsWith("/")&&s.hash===""&&(n=n.replace(/\/$/,"")),(e.removeTrailingSlash||s.pathname==="/")&&s.hash===""&&e.removeSingleSlash&&(n=n.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(n=n.replace(/^http:\/\//,"//")),e.stripProtocol&&(n=n.replace(/^(?:https?:)?\/\//,"")),n}var MAX_RECONNECT_ATTEMPTS=5,FLAPPING_THRESHOLD_MS=1e3,NDKRelayConnectivity=class{constructor(n,e){g(this,"ndkRelay");g(this,"ws");g(this,"_status");g(this,"timeoutMs");g(this,"connectedAt");g(this,"_connectionStats",{attempts:0,success:0,durations:[]});g(this,"debug");g(this,"netDebug");g(this,"connectTimeout");g(this,"reconnectTimeout");g(this,"ndk");g(this,"openSubs",new Map);g(this,"openCountRequests",new Map);g(this,"openEventPublishes",new Map);g(this,"serial",0);g(this,"baseEoseTimeout",4400);g(this,"updateConnectionStats",{connected:()=>{this._connectionStats.success++,this._connectionStats.connectedAt=Date.now()},disconnected:()=>{this._connectionStats.connectedAt&&(this._connectionStats.durations.push(Date.now()-this._connectionStats.connectedAt),this._connectionStats.durations.length>100&&this._connectionStats.durations.shift()),this._connectionStats.connectedAt=void 0},attempt:()=>{this._connectionStats.attempts++,this._connectionStats.connectedAt=Date.now()}});this.ndkRelay=n,this._status=1;const t=Math.floor(Math.random()*1e3);this.debug=this.ndkRelay.debug.extend(`connectivity${t}`),this.ndk=e}async connect(n,e=!0){if(this._status!==2&&this._status!==1){this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);return}this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),n??(n=this.timeoutMs),!this.timeoutMs&&n&&(this.timeoutMs=n),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(e),this.timeoutMs));try{this.updateConnectionStats.attempt(),this._status===1?this._status=4:this._status=2,this.ws=new WebSocket(this.ndkRelay.url),this.ws.onopen=this.onConnect.bind(this),this.ws.onclose=this.onDisconnect.bind(this),this.ws.onmessage=this.onMessage.bind(this),this.ws.onerror=this.onError.bind(this)}catch(t){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,t),this._status=1,e?this.handleReconnection():this.ndkRelay.emit("delayed-connect",2*24*60*60*1e3),t}}disconnect(){var n;this._status=0;try{(n=this.ws)==null||n.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(n){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),n&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){var n;(n=this.netDebug)==null||n.call(this,"connected",this.ndkRelay),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.updateConnectionStats.connected(),this._status=5,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){var n;(n=this.netDebug)==null||n.call(this,"disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this._status===5&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(n){var e;(e=this.netDebug)==null||e.call(this,n.data,this.ndkRelay,"recv");try{const t=JSON.parse(n.data),[r,s,...o]=t;switch(r){case"EVENT":{const a=this.openSubs.get(s),c=t[2];if(!a){this.debug(`Received event for unknown subscription ${s}`);return}a.onevent(c);return}case"COUNT":{const a=t[2],c=this.openCountRequests.get(s);c&&(c.resolve(a.count),this.openCountRequests.delete(s));return}case"EOSE":{const a=this.openSubs.get(s);if(!a)return;a.oneose(s);return}case"OK":{const a=t[2],c=t[3],l=this.openEventPublishes.get(s),f=l==null?void 0:l.pop();if(!l||!f){this.debug("Received OK for unknown event publish",s);return}a?f.resolve(c):f.reject(new Error(c)),l.length===0?this.openEventPublishes.delete(s):this.openEventPublishes.set(s,l);return}case"CLOSED":{const a=this.openSubs.get(s);if(!a)return;a.onclosed(t[2]);return}case"NOTICE":this.onNotice(t[1]);return;case"AUTH":{this.onAuthRequested(t[1]);return}}}catch(t){this.debug(`Error parsing message from ${this.ndkRelay.url}: ${t.message}`,t==null?void 0:t.stack);return}}async onAuthRequested(n){var t,r,s;const e=this.ndkRelay.authPolicy??((t=this.ndk)==null?void 0:t.relayAuthDefaultPolicy);if(this.debug("Relay requested authentication",{havePolicy:!!e}),this._status===7){this.debug("Already authenticating, ignoring");return}if(this._status=6,e){if(this._status>=5){this._status=7;let o;try{o=await e(this.ndkRelay,n)}catch(a){this.debug("Authentication policy threw an error",a),o=!1}if(this.debug("Authentication policy returned",!!o),o instanceof NDKEvent||o===!0){o instanceof NDKEvent&&await this.auth(o);const a=async()=>{if(this._status>=5&&this._status<8){const c=new NDKEvent(this.ndk);c.kind=22242,c.tags=[["relay",this.ndkRelay.url],["challenge",n]],await c.sign(),this.auth(c).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(l=>{this._status=6,this.ndkRelay.emit("auth:failed",l),this.debug("Authentication failed",l)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};o===!0&&((r=this.ndk)!=null&&r.signer?a().catch(c=>{console.error("Error authenticating",c)}):(this.debug("No signer available for authentication localhost"),(s=this.ndk)==null||s.once("signer:ready",a))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",n)}onError(n){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,n)}get status(){return this._status}isAvailable(){return this._status===5}isFlapping(){const n=this._connectionStats.durations;if(n.length%3!==0)return!1;const t=n.reduce((a,c)=>a+c,0)/n.length,r=n.map(a=>(a-t)**2).reduce((a,c)=>a+c,0)/n.length;return Math.sqrt(r)<FLAPPING_THRESHOLD_MS}async onNotice(n){this.ndkRelay.emit("notice",n)}handleReconnection(n=0){if(this.reconnectTimeout)return;if(this.isFlapping()){this.ndkRelay.emit("flapping",this._connectionStats),this._status=3;return}const e=this.connectedAt?Math.max(0,6e4-(Date.now()-this.connectedAt)):5e3*(this._connectionStats.attempts+1);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{n<MAX_RECONNECT_ATTEMPTS?setTimeout(()=>{this.handleReconnection(n+1)},1e3*(n+1)^4):this.debug("Reconnect failed")})},e),this.ndkRelay.emit("delayed-connect",e),this.debug("Reconnecting in",e),this._connectionStats.nextReconnectAt=Date.now()+e}async send(n){var e,t,r;this._status>=5&&((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN?((t=this.ws)==null||t.send(n),(r=this.netDebug)==null||r.call(this,n,this.ndkRelay,"send")):this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${n}`,this._status)}async auth(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["AUTH",${JSON.stringify(n.rawEvent())}]`),e}async publish(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${n.id} twice`),s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["EVENT",${JSON.stringify(n)}]`),e}async count(n,e){this.serial++;const t=(e==null?void 0:e.id)||`count:${this.serial}`,r=new Promise((s,o)=>{this.openCountRequests.set(t,{resolve:s,reject:o})});return this.send(`["COUNT","${t}",${JSON.stringify(n).substring(1)}`),r}close(n,e){this.send(`["CLOSE","${n}"]`);const t=this.openSubs.get(n);this.openSubs.delete(n),t&&t.onclose(e)}req(n){`${this.send(`["REQ","${n.subId}",${JSON.stringify(n.executeFilters).substring(1)}`)}`,this.openSubs.set(n.subId,n)}get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){var n;return this._status>=5&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN}},NDKRelayPublisher=class{constructor(n){g(this,"ndkRelay");g(this,"debug");this.ndkRelay=n,this.debug=n.debug.extend("publisher")}async publish(n,e=2500){let t;const r=()=>new Promise((h,u)=>{try{this.publishEvent(n).then(p=>{this.ndkRelay.emit("published",n),n.emit("relay:published",this.ndkRelay),h(!0)}).catch(u)}catch(p){u(p)}}),s=new Promise((h,u)=>{t=setTimeout(()=>{t=void 0,u(new Error(`Timeout: ${e}ms`))},e)}),o=()=>{r().then(h=>a(h)).catch(h=>c(h))};let a,c;const l=h=>{throw this.ndkRelay.debug("Publish failed",h,n.id),this.ndkRelay.emit("publish:failed",n,h),n.emit("relay:publish:failed",this.ndkRelay,h),h},f=()=>{t&&clearTimeout(t),this.ndkRelay.removeListener("connect",o)};return this.ndkRelay.status>=5?Promise.race([r(),s]).catch(l).finally(f):(this.ndkRelay.status<=1?(console.warn("Relay is disconnected, trying to connect to publish an event",this.ndkRelay.url),this.ndkRelay.connect()):console.warn("Relay not connected, waiting for connection to publish an event",this.ndkRelay.url),Promise.race([new Promise((h,u)=>{a=h,c=u,this.ndkRelay.on("connect",o)}),s]).catch(l).finally(f))}async publishEvent(n){return this.ndkRelay.connectivity.publish(n.rawEvent())}};function filterFingerprint(n,e){const t=[];for(const s of n){const o=Object.entries(s||{}).map(([a,c])=>["since","until"].includes(a)?`${a}:${c}`:a).sort().join("-");t.push(o)}let r=e?"+":"";return r+=t.join("|"),r}function mergeFilters(n){const e=[],t={};return n.filter(r=>!!r.limit).forEach(r=>e.push(r)),n=n.filter(r=>!r.limit),n.length===0?e:(n.forEach(r=>{Object.entries(r).forEach(([s,o])=>{Array.isArray(o)?t[s]===void 0?t[s]=[...o]:t[s]=Array.from(new Set([...t[s],...o])):t[s]=o})}),[...e,t])}var NDKRelaySubscription=class{constructor(n,e,t){g(this,"fingerprint");g(this,"items",new Map);g(this,"topSubManager");g(this,"debug");g(this,"status",0);g(this,"onClose");g(this,"relay");g(this,"eosed",!1);g(this,"executionTimer");g(this,"fireTime");g(this,"delayType");g(this,"executeFilters");g(this,"id",Math.random().toString(36).substring(7));g(this,"_subId");g(this,"subIdParts",new Set);g(this,"executeOnRelayReady",()=>{if(this.status===2){if(this.items.size===0){this.debug("No items to execute; this relay was probably too slow to respond and the caller gave up",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size,id:this.id,subId:this.subId}),this.cleanup();return}this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.status=1,this.execute()}});g(this,"reExecuteAfterAuth",(()=>{const n=this.subId;this.debug("Re-executing after auth",this.items.size),this.eosed?this.relay.close(this.subId):this.debug("We are abandoning an opened subscription, once it EOSE's, the handler will close it",{oldSubId:n}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",n,this.subId)}).bind(this));this.relay=n,this.topSubManager=t,this.debug=n.debug.extend(`sub[${this.id}]`),this.fingerprint=e||Math.random().toString(36).substring(7)}get subId(){return this._subId?this._subId:(this._subId=this.fingerprint.slice(0,15),this._subId)}addSubIdPart(n){this.subIdParts.add(n)}addItem(n,e){if(this.debug("Adding item",{filters:e,internalId:n.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,items:this.items,itemsSize:this.items.size}),!this.items.has(n.internalId))switch(n.on("close",this.removeItem.bind(this,n)),this.items.set(n.internalId,{subscription:n,filters:e}),this.status!==3&&n.subId&&(!this._subId||this._subId.length<48)&&(this.status===0||this.status===1)&&this.addSubIdPart(n.subId),this.status){case 0:this.evaluateExecutionPlan(n);break;case 3:break;case 1:this.evaluateExecutionPlan(n);break;case 4:throw this.debug("Subscription is closed, cannot add new items %o (%o)",n,e),new Error("Cannot add new items to a closed subscription")}}removeItem(n){if(this.items.delete(n.internalId),this.items.size===0){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(this.status===4)return;const n=this.status;if(this.status=4,n===3)try{this.relay.close(this.subId)}catch(e){this.debug("Error closing subscription",e,this)}else this.debug("Subscription wanted to close but it wasn't running, this is probably ok",{subId:this.subId,prevStatus:n,sub:this});this.cleanup()}cleanup(){this.executionTimer&&clearTimeout(this.executionTimer),this.relay.off("ready",this.executeOnRelayReady),this.relay.off("authed",this.reExecuteAfterAuth),this.onClose&&this.onClose(this)}evaluateExecutionPlan(n){if(!n.isGroupable()){this.status=1,this.execute();return}if(n.filters.find(r=>!!r.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10)){this.status=1,this.execute();return}const e=n.groupableDelay,t=n.groupableDelayType;if(!e)throw new Error("Cannot group a subscription without a delay");if(this.status===0)this.schedule(e,t);else{const r=this.delayType,s=this.fireTime-Date.now();if(r==="at-least"&&t==="at-least")s<e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-least"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-least")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else throw new Error(`Unknown delay type combination ${r} ${t}`)}}schedule(n,e){this.status=1;const t=Date.now();this.fireTime=t+n,this.delayType=e;const r=setTimeout(this.execute.bind(this),n);e==="at-least"&&(this.executionTimer=r)}finalizeSubId(){this.subIdParts.size>0?this._subId=Array.from(this.subIdParts).join("-"):this._subId=this.fingerprint.slice(0,15),this._subId+=`-${Math.random().toString(36).substring(2,7)}`}execute(){if(this.status===1){if(!this.relay.connected){this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.relay.once("ready",this.executeOnRelayReady);return}this.relay.status<8&&this.relay.once("authed",this.reExecuteAfterAuth),this.status=3,this.finalizeSubId(),this.executeFilters=this.compileFilters(),this.relay.req(this)}}onstart(){}onevent(n){this.topSubManager.dispatchEvent(n,this.relay)}oneose(n){if(this.eosed=!0,n!==this.subId){this.debug("Received EOSE for an abandoned subscription",n,this.subId),this.relay.close(n);return}this.items.size===0&&this.close();for(const{subscription:e}of this.items.values())e.eoseReceived(this.relay),e.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:e.filters,internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.removeItem(e))}onclose(n){this.status=4}onclosed(n){if(n)for(const{subscription:e}of this.items.values())e.closedReceived(this.relay,n)}compileFilters(){const n=[],e=Array.from(this.items.values()).map(r=>r.filters);if(!e[0])return this.debug("👀 No filters to merge",this.items),console.error("BUG: No filters to merge!",this.items),[];const t=e[0].length;for(let r=0;r<t;r++){const s=e.map(o=>o[r]);n.push(...mergeFilters(s))}return n}},NDKRelaySubscriptionManager=class{constructor(n,e){g(this,"relay");g(this,"subscriptions");g(this,"generalSubManager");this.relay=n,this.subscriptions=new Map,this.generalSubManager=e}addSubscription(n,e){let t;if(!n.isGroupable())t=this.createSubscription(n,e);else{const r=filterFingerprint(e,n.closeOnEose);r&&(t=(this.subscriptions.get(r)||[]).find(o=>o.status<3)),t??(t=this.createSubscription(n,e,r))}t.addItem(n,e)}createSubscription(n,e,t){const r=new NDKRelaySubscription(this.relay,t||null,this.generalSubManager);r.onClose=this.onRelaySubscriptionClose.bind(this);const s=this.subscriptions.get(r.fingerprint)??[];return this.subscriptions.set(r.fingerprint,[...s,r]),r}onRelaySubscriptionClose(n){let e=this.subscriptions.get(n.fingerprint)??[];e?e.length===1?this.subscriptions.delete(n.fingerprint):(e=e.filter(t=>t.id!==n.id),this.subscriptions.set(n.fingerprint,e)):console.warn("Unexpectedly did not find a subscription with fingerprint",n.fingerprint)}},SignatureVerificationStats=class{constructor(n,e=1e4){g(this,"ndk");g(this,"debug");g(this,"intervalId",null);g(this,"intervalMs");this.ndk=n,this.debug=createDebug2("ndk:signature-verification-stats"),this.intervalMs=e}start(){if(this.intervalId){this.debug("Stats tracking already started");return}this.debug(`Starting signature verification stats reporting every ${this.intervalMs}ms`),this.intervalId=setInterval(()=>{this.reportStats()},this.intervalMs)}stop(){if(!this.intervalId){this.debug("Stats tracking not started");return}clearInterval(this.intervalId),this.intervalId=null,this.debug("Stopped signature verification stats reporting")}reportStats(){const n=this.collectStats();console.log(`
=== Signature Verification Sampling Stats ===`),console.log(`Timestamp: ${new Date().toISOString()}`),console.log(`Total Relays: ${n.totalRelays}`),console.log(`Connected Relays: ${n.connectedRelays}`),n.relayStats.length===0?console.log("No relay statistics available"):(console.log(`
Relay Statistics:`),n.relayStats.sort((e,t)=>e.url.localeCompare(t.url)),n.relayStats.forEach(e=>{var t;console.log(`
${e.url} ${e.connected?"(connected)":"(disconnected)"}`),console.log(` Validated Events: ${e.validatedCount}`),console.log(` Non-validated Events: ${e.nonValidatedCount}`),console.log(` Total Events: ${e.totalEvents}`),console.log(` Current Validation Ratio: ${e.validationRatio.toFixed(4)} (${(e.validationRatio*100).toFixed(2)}%)`),console.log(` Target Validation Ratio: ${((t=e.targetValidationRatio)==null?void 0:t.toFixed(4))||"N/A"} (${e.targetValidationRatio?(e.targetValidationRatio*100).toFixed(2)+"%":"N/A"})`),console.log(` Trusted: ${e.trusted?"Yes":"No"}`)})),console.log(`
Global Settings:`),console.log(` Initial Validation Ratio: ${n.initialValidationRatio.toFixed(4)} (${(n.initialValidationRatio*100).toFixed(2)}%)`),console.log(` Lowest Validation Ratio: ${n.lowestValidationRatio.toFixed(4)} (${(n.lowestValidationRatio*100).toFixed(2)}%)`),console.log(` Auto-blacklist Invalid Relays: ${n.autoBlacklistInvalidRelays?"Yes":"No"}`),console.log(` Blacklisted Relays: ${n.blacklistedRelayCount}`),console.log(`===========================================
`)}collectStats(){var e;const n=[];for(const t of this.ndk.pool.relays.values())n.push({url:t.url,connected:t.connected,validatedCount:t.validatedEventCount,nonValidatedCount:t.nonValidatedEventCount,totalEvents:t.validatedEventCount+t.nonValidatedEventCount,validationRatio:t.validationRatio,targetValidationRatio:t.targetValidationRatio,trusted:t.trusted});return{totalRelays:this.ndk.pool.relays.size,connectedRelays:this.ndk.pool.connectedRelays().length,relayStats:n,initialValidationRatio:this.ndk.initialValidationRatio,lowestValidationRatio:this.ndk.lowestValidationRatio,autoBlacklistInvalidRelays:this.ndk.autoBlacklistInvalidRelays,blacklistedRelayCount:((e=this.ndk.blacklistRelayUrls)==null?void 0:e.length)||0}}};function startSignatureVerificationStats(n,e=1e4){const t=new SignatureVerificationStats(n,e);return t.start(),t}var NDKRelayStatus=(n=>(n[n.DISCONNECTING=0]="DISCONNECTING",n[n.DISCONNECTED=1]="DISCONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.FLAPPING=3]="FLAPPING",n[n.CONNECTING=4]="CONNECTING",n[n.CONNECTED=5]="CONNECTED",n[n.AUTH_REQUESTED=6]="AUTH_REQUESTED",n[n.AUTHENTICATING=7]="AUTHENTICATING",n[n.AUTHENTICATED=8]="AUTHENTICATED",n))(NDKRelayStatus||{}),Te,NDKRelay=(Te=class extends lib$1.EventEmitter{constructor(t,r,s){super();g(this,"url");g(this,"scores");g(this,"connectivity");g(this,"subs");g(this,"publisher");g(this,"authPolicy");g(this,"lowestValidationRatio");g(this,"targetValidationRatio");g(this,"validationRatioFn");g(this,"validatedEventCount",0);g(this,"nonValidatedEventCount",0);g(this,"trusted",!1);g(this,"complaining",!1);g(this,"debug");g(this,"req");g(this,"close");this.url=normalizeRelayUrl(t),this.scores=new Map,this.debug=createDebug2(`ndk:relay:${t}`),this.connectivity=new NDKRelayConnectivity(this,s),this.connectivity.netDebug=s==null?void 0:s.netDebug,this.req=this.connectivity.req.bind(this.connectivity),this.close=this.connectivity.close.bind(this.connectivity),this.subs=new NDKRelaySubscriptionManager(this,s.subManager),this.publisher=new NDKRelayPublisher(this),this.authPolicy=r,this.targetValidationRatio=s==null?void 0:s.initialValidationRatio,this.lowestValidationRatio=s==null?void 0:s.lowestValidationRatio,this.validationRatioFn=((s==null?void 0:s.validationRatioFn)??Te.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),s||console.trace("relay created without ndk")}updateValidationRatio(){if(this.validationRatioFn&&this.validatedEventCount>0){const t=this.validationRatioFn(this,this.validatedEventCount,this.nonValidatedEventCount);this.targetValidationRatio=t}setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(t,r=!0){return this.connectivity.connect(t,r)}disconnect(){this.status!==1&&this.connectivity.disconnect()}subscribe(t,r){this.subs.addSubscription(t,r)}async publish(t,r=2500){return this.publisher.publish(t,r)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return this.nonValidatedEventCount===0?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return this.trusted?!1:this.targetValidationRatio===void 0||this.targetValidationRatio>=1?!0:Math.random()<this.targetValidationRatio}get connected(){return this.connectivity.connected}},g(Te,"defaultValidationRatioUpdateFn",(t,r,s)=>{if(t.lowestValidationRatio===void 0||t.targetValidationRatio===void 0)return 1;let o=t.validationRatio;if(t.validationRatio>t.targetValidationRatio){const a=r/100;o=Math.max(t.lowestValidationRatio,t.validationRatio-a)}return o<t.validationRatio?o:t.validationRatio}),Te),NDKPublishError=class extends Error{constructor(e,t,r,s){super(e);g(this,"errors");g(this,"publishedToRelays");g(this,"intendedRelaySet");this.errors=t,this.publishedToRelays=r,this.intendedRelaySet=s}get relayErrors(){const e=[];for(const[t,r]of this.errors)e.push(`${t.url}: ${r}`);return e.join(`
`)}},NDKRelaySet=class Ie{constructor(e,t,r){g(this,"relays");g(this,"debug");g(this,"ndk");g(this,"pool");this.relays=e,this.ndk=t,this.pool=r??t.pool,this.debug=t.debug.extend("relayset")}addRelay(e){this.relays.add(e)}get relayUrls(){return Array.from(this.relays).map(e=>e.url)}static fromRelayUrls(e,t,r=!0,s){if(s=s??t.pool,!s)throw new Error("No pool provided");const o=new Set;for(const a of e){const c=s.relays.get(normalizeRelayUrl(a));if(c)c.status<5&&r&&c.connect(),o.add(c);else{const l=new NDKRelay(normalizeRelayUrl(a),t==null?void 0:t.relayAuthDefaultPolicy,t);s.useTemporaryRelay(l,void 0,`requested from fromRelayUrls ${e}`),o.add(l)}}return new Ie(new Set(o),t,s)}async publish(e,t,r=1){var l;const s=new Set,o=new Map,a=e.isEphemeral();e.publishStatus="pending";const c=f=>{s.add(f)};e.on("relay:published",c);try{const f=Array.from(this.relays).map(h=>new Promise(u=>{const p=t?setTimeout(()=>{s.has(h)||(o.set(h,new Error(`Publish timeout after ${t}ms`)),u(!1))},t):null;h.publish(e,t).then(y=>{p&&clearTimeout(p),y?(s.add(h),u(!0)):u(!1)}).catch(y=>{p&&clearTimeout(p),a||o.set(h,y),u(!1)})}));if(await Promise.all(f),s.size<r){if(!a){const h=new NDKPublishError("Not enough relays received the event ("+s.size+" published, "+r+" required)",o,s,this);throw e.publishStatus="error",e.publishError=h,(l=this.ndk)==null||l.emit("event:publish-failed",e,h,this.relayUrls),h}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:s});return s}finally{e.off("relay:published",c)}}get size(){return this.relays.size}},d=createDebug2("ndk:outbox:calculate");async function calculateRelaySetFromEvent(n,e,t){var c,l;const r=new Set,s=await getWriteRelaysFor(n,e.pubkey);s&&s.forEach(f=>{var u;const h=(u=n.pool)==null?void 0:u.getRelay(f);h&&r.add(h)});let o=e.tags.filter(f=>["a","e"].includes(f[0])).map(f=>f[2]).filter(f=>f==null?void 0:f.startsWith("wss://")).filter(f=>{try{return new URL(f),!0}catch{return!1}}).map(f=>normalizeRelayUrl(f));o=Array.from(new Set(o)).slice(0,5),o.forEach(f=>{var u;const h=(u=n.pool)==null?void 0:u.getRelay(f,!0,!0);h&&(d("Adding relay hint %s",f),r.add(h))});const a=e.getMatchingTags("p").map(f=>f[1]);if(a.length<5?Array.from(chooseRelayCombinationForPubkeys(n,a,"read",{preferredRelays:new Set(s)}).keys()).forEach(h=>{var p;const u=(p=n.pool)==null?void 0:p.getRelay(h,!1,!0);u&&(d("Adding p-tagged relay %s",h),r.add(u))}):d("Too many p-tags to consider %d",a.length),(c=n.pool)==null||c.permanentAndConnectedRelays().forEach(f=>r.add(f)),t&&r.size<t){const f=(l=n.explicitRelayUrls)==null?void 0:l.filter(h=>!Array.from(r).some(u=>u.url===h)).slice(0,t-r.size);f==null||f.forEach(h=>{var p;const u=(p=n.pool)==null?void 0:p.getRelay(h,!1,!0);u&&(d("Adding explicit relay %s",h),r.add(u))})}return new NDKRelaySet(r,n)}function calculateRelaySetsFromFilter(n,e,t){const r=new Map,s=new Set;if(e.forEach(o=>{o.authors&&o.authors.forEach(a=>s.add(a))}),s.size>0){const o=getRelaysForFilterWithAuthors(n,Array.from(s));for(const a of o.keys())r.set(a,[]);for(const a of e)if(a.authors)for(const[c,l]of o.entries()){const f=a.authors.filter(h=>l.includes(h));r.set(c,[...r.get(c),{...a,authors:f}])}else for(const c of o.keys())r.set(c,[...r.get(c),a])}else n.explicitRelayUrls&&n.explicitRelayUrls.forEach(o=>{r.set(o,e)});return r.size===0&&t.permanentAndConnectedRelays().slice(0,5).forEach(o=>{r.set(o.url,e)}),r}function calculateRelaySetsFromFilters(n,e,t){return calculateRelaySetsFromFilter(n,e,t)}function mergeTags(n,e){const t=new Map,r=a=>a.join(","),s=(a,c)=>a.every((l,f)=>l===c[f]),o=a=>{for(const[c,l]of t)if(s(l,a)||s(a,l)){a.length>=l.length&&t.set(c,a);return}t.set(r(a),a)};return n.concat(e).forEach(o),Array.from(t.values())}function uniqueTag(n,e){const t=n.length,r=e.length;return t===r?n.every((o,a)=>o===e[a])?[n]:[n,e]:t>r&&n.every((o,a)=>o===e[a])?[n]:r>t&&e.every((o,a)=>o===n[a])?[e]:[n,e]}var hashtagRegex=new RegExp(`(?<=\\s|^)(#[^\\s!@#$%^&*()=+./,[{\\]};:'"?><]+)`,"g");function generateHashtags(n){const e=n.match(hashtagRegex),t=new Set,r=new Set;if(e)for(const s of e)t.has(s.slice(1))||(r.add(s.slice(1)),t.add(s.slice(1)));return Array.from(r)}async function generateContentTags(n,e=[]){const t=/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,r=[],s=a=>{e.find(c=>["q",a[0]].includes(c[0])&&c[1]===a[1])||e.push(a)};n=n.replace(t,a=>{try{const c=a.split(/(@|nostr:)/)[2],{type:l,data:f}=nip19_exports.decode(c);let h;switch(l){case"npub":h=["p",f];break;case"nprofile":h=["p",f.pubkey];break;case"note":r.push(new Promise(async u=>{s(["q",f,await maybeGetEventRelayUrl(c)]),u()}));break;case"nevent":r.push(new Promise(async u=>{const{id:p,author:y}=f;let{relays:b}=f;(!b||b.length===0)&&(b=[await maybeGetEventRelayUrl(c)]),s(["q",p,b[0]]),y&&s(["p",y]),u()}));break;case"naddr":r.push(new Promise(async u=>{const p=[f.kind,f.pubkey,f.identifier].join(":");let y=f.relays??[];y.length===0&&(y=[await maybeGetEventRelayUrl(c)]),s(["q",p,y[0]]),s(["p",f.pubkey]),u()}));break;default:return a}return h&&s(h),`nostr:${c}`}catch{return a}}),await Promise.all(r);const o=generateHashtags(n).map(a=>["t",a]);return e=mergeTags(e,o),{content:n,tags:e}}async function maybeGetEventRelayUrl(n){return""}async function encrypt(n,e,t="nip44"){let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||(()=>{const a=this.getMatchingTags("p");if(a.length!==1)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:a[0][1]})})();if(t==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.encrypt(o,this.content,"nip44")),(!r||t==="nip04")&&await isEncryptionEnabled(s,"nip04")&&(r=await s.encrypt(o,this.content,"nip04")),!r)throw new Error("Failed to encrypt event.");this.content=r}async function decrypt(n,e,t){var c,l,f,h;if((l=(c=this.ndk)==null?void 0:c.cacheAdapter)!=null&&l.getDecryptedEvent){let u=null;if(typeof this.ndk.cacheAdapter.getDecryptedEvent=="function"&&(u=this.ndk.cacheAdapter.getDecryptedEvent(this.id)),u){this.content=u.content;return}}let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||this.author;if(!o)throw new Error("No sender provided and no author available");const a=t||(this.content.match(/\\?iv=/)?"nip04":"nip44");if((a==="nip04"||this.kind===4)&&await isEncryptionEnabled(s,"nip04")&&this.content.search("\\?iv=")&&(r=await s.decrypt(o,this.content,"nip04")),!r&&a==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.decrypt(o,this.content,"nip44")),!r)throw new Error("Failed to decrypt event.");this.content=r,(h=(f=this.ndk)==null?void 0:f.cacheAdapter)!=null&&h.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function isEncryptionEnabled(n,e){return n.encryptionEnabled?e?!!await n.encryptionEnabled(e):!0:!1}function eventsBySameAuthor(n,e){const t=new Map;return t.set(n.id,n),e.forEach(r=>{r.pubkey===n.pubkey&&t.set(r.id,r)}),t}var hasMarkers=(n,e)=>n.getMatchingTags(e).some(t=>t[3]&&t[3]!=="");function eventIsReply(n,e,t=new Set,r){r??(r=n.tagType());const s=e.getMatchingTags(r);if(t.add(n.tagId()),t.has(e.tagId()))return!1;const a=(()=>{let l=!1;for(const f of s){if(f[3]==="reply")return t.has(f[1]);const h=f[3]===""||f[3]===void 0,u=f[3]==="root";f[1]===n.tagId()&&(h||u)&&(l=u?"root":!0)}if(!l)return!1;if(l==="root")return!0})();if(a!==void 0)return a;if(hasMarkers(e,r))return!1;const c=n.getMatchingTags("e").map(l=>l[1]);return c.push(n.id),e.getMatchingTags("e").every(l=>c.includes(l[1]))}function eventThreads(n,e){const t=eventsBySameAuthor(n,e);return e.filter(s=>eventIsPartOfThread(n,s,t)).sort((s,o)=>s.created_at-o.created_at)}function getEventReplyId(n){const e=getReplyTag(n);if(e)return e[1];const t=getRootTag(n);if(t)return t[1]}function isEventOriginalPost(n){return getEventReplyId(n)===void 0}function eventThreadIds(n,e){const t=new Map;return eventThreads(n,e).forEach(s=>t.set(s.id,s)),t}function eventReplies(n,e,t){return t??(t=new Set(eventThreadIds(n,e).keys())),e.filter(r=>eventIsReply(n,r,t))}function eventIsPartOfThread(n,e,t){return n.pubkey!==e.pubkey?!1:e.getMatchingTags("e").map(o=>o[1]).every(o=>t.has(o))}function eventHasETagMarkers(n){for(const e of n.tags)if(e[0]==="e"&&(e[3]??"").length>0)return!0;return!1}function getRootEventId(n,e){e??(e=n.tagType());const t=getRootTag(n,e);if(t)return t[1];const r=getReplyTag(n,e);return r==null?void 0:r[1]}function getRootTag(n,e){e??(e=n.tagType());const t=n.tags.find(isTagRootTag);if(!t){if(eventHasETagMarkers(n))return;const r=n.getMatchingTags(e);if(r.length<3)return r[0]}return t}var nip22RootTags=new Set(["A","E","I"]),nip22ReplyTags=new Set(["a","e","i"]);function getReplyTag(n,e){if(n.kind===1111){let s;for(const o of n.tags)if(nip22RootTags.has(o[0]))s=o;else if(nip22ReplyTags.has(o[0])){s=o;break}return s}e??(e=n.tagType());let t=!1,r;for(const s of n.tags)if(s[0]===e){if((s[3]??"").length>0&&(t=!0),t&&s[3]==="reply")return s;t&&s[3]==="root"&&(r=s),t||(r=s)}return r}function isTagRootTag(n){return n[0]==="E"||n[3]==="root"}async function fetchTaggedEvent(n,e){if(!this.ndk)throw new Error("NDK instance not found");const t=this.getMatchingTags(n,e);if(t.length===0)return;const[r,s,o]=t[0];let a=o!==""?this.ndk.pool.getRelay(o):void 0;return await this.ndk.fetchEvent(s,{},a)}async function fetchRootEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getRootTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}async function fetchReplyEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getReplyTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}function isReplaceable(){if(this.kind===void 0)throw new Error("Kind not set");return[0,3].includes(this.kind)||this.kind>=1e4&&this.kind<2e4||this.kind>=3e4&&this.kind<4e4}function isEphemeral(){if(this.kind===void 0)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(this.kind===void 0)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}var DEFAULT_RELAY_COUNT=2;function encode(n=DEFAULT_RELAY_COUNT){let e=[];return this.onRelays.length>0?e=this.onRelays.map(t=>t.url):this.relay&&(e=[this.relay.url]),e.length>n&&(e=e.slice(0,n)),this.isParamReplaceable()?nip19_exports.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:e}):e.length>0?nip19_exports.neventEncode({id:this.tagId(),relays:e,author:this.pubkey}):nip19_exports.noteEncode(this.tagId())}async function repost(n=!0,e){if(!e&&n){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),e=this.ndk.signer}const t=new NDKEvent(this.ndk,{kind:getKind(this)});return this.isProtected||(t.content=JSON.stringify(this.rawEvent())),t.tag(this),this.kind!==1&&t.tags.push(["k",`${this.kind}`]),e&&await t.sign(e),n&&await t.publish(),t}function getKind(n){return n.kind===1?6:16}function serialize(n=!1,e=!1){const t=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return n&&t.push(this.sig),e&&t.push(this.id),JSON.stringify(t)}function deserialize(n){const e=JSON.parse(n),t={pubkey:e[1],created_at:e[2],kind:e[3],tags:e[4],content:e[5]};if(e.length>=7){const r=e[6],s=e[7];r&&r.length===128?(t.sig=r,s&&s.length===64&&(t.id=s)):r&&r.length===64&&(t.id=r,s&&s.length===128&&(t.sig=s))}return t}var worker,processingQueue={};function signatureVerificationInit(n){worker=n,worker.onmessage=e=>{const[t,r]=e.data,s=processingQueue[t];if(!s){console.error("No record found for event",t);return}delete processingQueue[t];for(const o of s.resolves)o(r)}}async function verifySignatureAsync(n,e,t){const r=n.ndk,s=Date.now();let o;return r.signatureVerificationFunction?(console.log("[NDK-CORE] Using custom signature verification function async"),o=await r.signatureVerificationFunction(n),console.log("Custom signature verification result",n.id,{result:o})):(console.log("Using worker-based signature verification async"),o=await new Promise(a=>{const c=n.serialize();let l=!1;processingQueue[n.id]||(processingQueue[n.id]={event:n,resolves:[],relay:t},l=!0),processingQueue[n.id].resolves.push(a),l&&(worker==null||worker.postMessage({serialized:c,id:n.id,sig:n.sig,pubkey:n.pubkey}))})),r.signatureVerificationTimeMs+=Date.now()-s,o}var PUBKEY_REGEX=/^[a-f0-9]{64}$/;function validate(){if(typeof this.kind!="number"||typeof this.content!="string"||typeof this.created_at!="number"||typeof this.pubkey!="string"||!this.pubkey.match(PUBKEY_REGEX)||!Array.isArray(this.tags))return!1;for(let n=0;n<this.tags.length;n++){const e=this.tags[n];if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(typeof e[t]=="object")return!1}return!0}var verifiedSignatures=new dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function verifySignature(n){var t;if(typeof this.signatureVerified=="boolean")return this.signatureVerified;const e=verifiedSignatures.get(this.id);if(e!==null)return this.signatureVerified=!!e,this.signatureVerified;try{if((t=this.ndk)!=null&&t.asyncSigVerification)verifySignatureAsync(this,n,this.relay).then(r=>{var s,o;n&&(this.signatureVerified=r,r&&verifiedSignatures.set(this.id,this.sig)),r||(this.relay?(s=this.ndk)==null||s.reportInvalidSignature(this,this.relay):(o=this.ndk)==null||o.reportInvalidSignature(this),verifiedSignatures.set(this.id,!1))}).catch(r=>{console.error("signature verification error",this.id,r)});else{const r=sha256(new TextEncoder().encode(this.serialize())),s=schnorr.verify(this.sig,r,this.pubkey);return s?verifiedSignatures.set(this.id,this.sig):verifiedSignatures.set(this.id,!1),this.signatureVerified=s,s}}catch{return this.signatureVerified=!1,!1}}function getEventHash(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(n){const e=sha256(new TextEncoder().encode(n));return bytesToHex(e)}var skipClientTagOnKinds=new Set([0,4,1059,13,3,9734,5]),NDKEvent=class ie extends lib$1.EventEmitter{constructor(t,r){var s;super();g(this,"ndk");g(this,"created_at");g(this,"content","");g(this,"tags",[]);g(this,"kind");g(this,"id","");g(this,"sig");g(this,"pubkey","");g(this,"signatureVerified");g(this,"_author");g(this,"relay");g(this,"publishStatus","success");g(this,"publishError");g(this,"serialize",serialize.bind(this));g(this,"getEventHash",getEventHash.bind(this));g(this,"validate",validate.bind(this));g(this,"verifySignature",verifySignature.bind(this));g(this,"isReplaceable",isReplaceable.bind(this));g(this,"isEphemeral",isEphemeral.bind(this));g(this,"isDvm",()=>this.kind&&this.kind>=5e3&&this.kind<=7e3);g(this,"isParamReplaceable",isParamReplaceable.bind(this));g(this,"encode",encode.bind(this));g(this,"encrypt",encrypt.bind(this));g(this,"decrypt",decrypt.bind(this));g(this,"fetchTaggedEvent",fetchTaggedEvent.bind(this));g(this,"fetchRootEvent",fetchRootEvent.bind(this));g(this,"fetchReplyEvent",fetchReplyEvent.bind(this));g(this,"repost",repost.bind(this));this.ndk=t,this.created_at=r==null?void 0:r.created_at,this.content=(r==null?void 0:r.content)||"",this.tags=(r==null?void 0:r.tags)||[],this.id=(r==null?void 0:r.id)||"",this.sig=r==null?void 0:r.sig,this.pubkey=(r==null?void 0:r.pubkey)||"",this.kind=r==null?void 0:r.kind,r instanceof ie&&(this.relay&&(this.relay=r.relay,(s=this.ndk)==null||s.subManager.seenEvent(r.id,this.relay)),this.publishStatus=r.publishStatus,this.publishError=r.publishError)}get onRelays(){let t=[];return this.ndk?t=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&t.push(this.relay),t}static deserialize(t,r){return new ie(t,deserialize(r))}rawEvent(){return{created_at:this.created_at,content:this.content,tags:this.tags,kind:this.kind,pubkey:this.pubkey,id:this.id,sig:this.sig}}set author(t){var r;this.pubkey=t.pubkey,this._author=t,(r=this._author).ndk??(r.ndk=this.ndk)}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const t=this.ndk.getUser({pubkey:this.pubkey});return this._author=t,t}tagExternal(t,r,s){const o=["i"],a=["k"];switch(r){case"url":{const c=new URL(t);c.hash="",o.push(c.toString()),a.push(`${c.protocol}//${c.host}`);break}case"hashtag":o.push(`#${t.toLowerCase()}`),a.push("#");break;case"geohash":o.push(`geo:${t.toLowerCase()}`),a.push("geo");break;case"isbn":o.push(`isbn:${t.replace(/-/g,"")}`),a.push("isbn");break;case"podcast:guid":o.push(`podcast:guid:${t}`),a.push("podcast:guid");break;case"podcast:item:guid":o.push(`podcast:item:guid:${t}`),a.push("podcast:item:guid");break;case"podcast:publisher:guid":o.push(`podcast:publisher:guid:${t}`),a.push("podcast:publisher:guid");break;case"isan":o.push(`isan:${t.split("-").slice(0,4).join("-")}`),a.push("isan");break;case"doi":o.push(`doi:${t.toLowerCase()}`),a.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${r}`)}s&&o.push(s),this.tags.push(o),this.tags.push(a)}tag(t,r,s,o){let a=[];if(t.fetchProfile!==void 0){o??(o="p");const l=[o,t.pubkey];r&&l.push("",r),a.push(l)}else if(t instanceof ie){const l=t;s??(s=(l==null?void 0:l.pubkey)===this.pubkey),a=l.referenceTags(r,s,o);for(const f of l.getMatchingTags("p"))f[1]!==this.pubkey&&(this.tags.find(h=>h[0]==="p"&&h[1]===f[1])||this.tags.push(["p",f[1]]))}else if(Array.isArray(t))a=[t];else throw new Error("Invalid argument",t);this.tags=mergeTags(this.tags,a)}async toNostrEvent(t){var o,a;if(!t&&this.pubkey===""){const c=await((a=(o=this.ndk)==null?void 0:o.signer)==null?void 0:a.user());this.pubkey=(c==null?void 0:c.pubkey)||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:r,tags:s}=await this.generateTags();this.content=r||"",this.tags=s;try{this.id=this.getEventHash()}catch{}return this.rawEvent()}getMatchingTags(t,r){const s=this.tags.filter(o=>o[0]===t);return r===void 0?s:s.filter(o=>o[3]===r)}hasTag(t,r){return this.tags.some(s=>s[0]===t&&(!r||s[3]===r))}tagValue(t,r){const s=this.getMatchingTags(t,r);if(s.length!==0)return s[0][1]}get alt(){return this.tagValue("alt")}set alt(t){this.removeTag("alt"),t&&this.tags.push(["alt",t])}get dTag(){return this.tagValue("d")}set dTag(t){this.removeTag("d"),t&&this.tags.push(["d",t])}removeTag(t,r){const s=Array.isArray(t)?t:[t];this.tags=this.tags.filter(o=>{const a=s.includes(o[0]),c=r?o[3]===r:!0;return!(a&&c)})}replaceTag(t){this.removeTag(t[0]),this.tags.push(t)}async sign(t){var s,o;t?this.author=await t.user():((s=this.ndk)==null||s.assertSigner(),t=(o=this.ndk)==null?void 0:o.signer);const r=await this.toNostrEvent();return this.sig=await t.sign(r),this.sig}async publishReplaceable(t,r,s){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(t,r,s)}async publish(t,r,s){var c,l,f;if(s||(s=1),this.sig||await this.sign(),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if((!t||t.size===0)&&(t=this.ndk.devWriteRelaySet||await calculateRelaySetFromEvent(this.ndk,this,s)),this.kind===5&&((c=this.ndk.cacheAdapter)!=null&&c.deleteEventIds)){const h=this.getMatchingTags("e").map(u=>u[1]);this.ndk.cacheAdapter.deleteEventIds(h)}const o=this.rawEvent();if((l=this.ndk.cacheAdapter)!=null&&l.addUnpublishedEvent&&shouldTrackUnpublishedEvent(this))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,t.relayUrls)}catch(h){console.error("Error adding unpublished event to cache",h)}this.kind===5&&((f=this.ndk.cacheAdapter)!=null&&f.deleteEventIds)&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(h=>h[1])),this.ndk.subManager.dispatchEvent(o,void 0,!0);const a=await t.publish(this,r,s);return a.forEach(h=>{var u;return(u=this.ndk)==null?void 0:u.subManager.seenEvent(this.id,h)}),a}async generateTags(){var o,a,c;let t=[];const r=await generateContentTags(this.content,this.tags),s=r.content;if(t=r.tags,this.kind&&this.isParamReplaceable()&&!this.getMatchingTags("d")[0]){const f=this.tagValue("title");let u=[...Array(f?6:16)].map(()=>Math.random().toString(36)[2]).join("");f&&f.length>0&&(u=`${f.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${u}`),t.push(["d",u])}if(this.shouldAddClientTag){const l=["client",((o=this.ndk)==null?void 0:o.clientName)??""];(a=this.ndk)!=null&&a.clientNip89&&l.push((c=this.ndk)==null?void 0:c.clientNip89),t.push(l)}else this.shouldStripClientTag&&(t=t.filter(l=>l[0]!=="client"));return{content:s||"",tags:t}}get shouldAddClientTag(){var t,r;return!(!((t=this.ndk)!=null&&t.clientName)&&!((r=this.ndk)!=null&&r.clientNip89)||skipClientTagOnKinds.has(this.kind)||this.isEphemeral()||this.isReplaceable()&&!this.isParamReplaceable()||this.isDvm()||this.hasTag("client"))}get shouldStripClientTag(){return skipClientTagOnKinds.has(this.kind)}muted(){var o,a;const t=(o=this.ndk)==null?void 0:o.mutedIds.get(this.pubkey);if(t&&t==="p")return"author";const r=this.tagReference(),s=(a=this.ndk)==null?void 0:a.mutedIds.get(r[1]);return s&&s===r[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const t=this.getMatchingTags("d")[0];return t?t[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return this.kind===0||this.kind===3||this.kind&&this.kind>=1e4&&this.kind<2e4?`${this.kind}:${this.pubkey}`:this.tagId()}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}tagAddress(){if(this.isParamReplaceable()){const t=this.dTag??"";return`${this.kind}:${this.pubkey}:${t}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(t){let r;return this.isParamReplaceable()?r=["a",this.tagAddress()]:r=["e",this.tagId()],this.relay?r.push(this.relay.url):r.push(""),r.push(t??""),this.isParamReplaceable()||r.push(this.pubkey),r}referenceTags(t,r,s){let o=[];return this.isParamReplaceable()?o=[[s??"a",this.tagAddress()],[s??"e",this.id]]:o=[[s??"e",this.id]],o=o.map(a=>{var c,l,f;return a[0]==="e"||t?a.push(((c=this.relay)==null?void 0:c.url)??""):(l=this.relay)!=null&&l.url&&a.push((f=this.relay)==null?void 0:f.url),a}),o.forEach(a=>{a[0]==="e"?(a.push(t??""),a.push(this.pubkey)):t&&a.push(t)}),o=[...o,...this.getMatchingTags("h")],r||o.push(...this.author.referenceTags()),o}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(t,r=!0){var o;if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new ie(this.ndk,{kind:5,content:t||""});return s.tag(this,void 0,!0),s.tags.push(["k",(o=this.kind)==null?void 0:o.toString()]),r&&(this.emit("deleted"),await s.publish()),s}set isProtected(t){this.removeTag("-"),t&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}async react(t,r=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new ie(this.ndk,{kind:7,content:t});return s.tag(this),this.kind!==1&&s.tags.push(["k",`${this.kind}`]),r&&await s.publish(),s}get isValid(){return this.validate()}get inspect(){return JSON.stringify(this.rawEvent(),null,4)}dump(){console.debug(JSON.stringify(this.rawEvent(),null,4)),console.debug("Event on relays:",this.onRelays.map(t=>t.url).join(", "))}reply(t){var s,o;const r=new ie(this.ndk);if(this.kind===1&&!t)r.kind=1,this.hasTag("e")?r.tags=[...r.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply")]:r.tag(this,"root");else{r.kind=1111;const a=["A","E","I","P"],c=this.tags.filter(l=>a.includes(l[0]));if(c.length>0){const l=this.tagValue("K");r.tags.push(...c),l&&r.tags.push(["K",l]);const[f,h,u,...p]=this.tagReference(),y=[f,h,...p];r.tags.push(y)}else{const[l,f,h,u]=this.tagReference(),p=[l,f,u??""];l==="e"&&p.push(this.pubkey),r.tags.push(p);const y=[...p];y[0]=y[0].toUpperCase(),r.tags.push(y),r.tags.push(["K",(s=this.kind)==null?void 0:s.toString()]),r.tags.push(["P",this.pubkey])}r.tags.push(["k",(o=this.kind)==null?void 0:o.toString()]),r.tags.push(...this.getMatchingTags("p")),r.tags.push(["p",this.pubkey])}return r}},untrackedUnpublishedEvents=new Set([24133,13194,23194,23195]);function shouldTrackUnpublishedEvent(n){return!untrackedUnpublishedEvents.has(n.kind)}function isSignedEvent(n){return!!(n.sig&&n.id&&n.created_at&&n.created_at>0)}function isUnsignedEvent(n){return!isSignedEvent(n)}function assertSignedEvent(n){if(!isSignedEvent(n))throw new Error("Expected signed event but event is not signed")}function createSignedEvent(n){if(!isSignedEvent(n))throw new Error("Cannot create signed event from unsigned event");return Object.defineProperty(n,"signed",{value:!0,writable:!1,enumerable:!1}),n}var NDKPool=class extends lib$1.EventEmitter{constructor(e,t,r,{debug:s,name:o}={}){super();g(this,"_relays",new Map);g(this,"status","idle");g(this,"autoConnectRelays",new Set);g(this,"poolBlacklistRelayUrls",new Set);g(this,"debug");g(this,"temporaryRelayTimers",new Map);g(this,"flappingRelays",new Set);g(this,"backoffTimes",new Map);g(this,"ndk");g(this,"_name","unnamed");this.debug=s??r.debug.extend("pool"),o&&(this._name=o),this.ndk=r,this.relayUrls=e,this.poolBlacklistRelayUrls=new Set(t),this.ndk.pools.push(this)}get blacklistRelayUrls(){const e=new Set(this.ndk.blacklistRelayUrls);return this.poolBlacklistRelayUrls.forEach(t=>e.add(t)),e}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const r=new NDKRelay(t,void 0,this.ndk);r.connectivity.netDebug=this.ndk.netDebug,this.addRelay(r)}}get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,r){const s=this.relays.has(e.url);s||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,r));const o=this.temporaryRelayTimers.get(e.url);if(o&&clearTimeout(o),!s||o){const a=setTimeout(()=>{var c;(c=this.ndk.explicitRelayUrls)!=null&&c.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,a)}}addRelay(e,t=!0){var m,k;const r=this.relays.has(e.url),s=(m=this.blacklistRelayUrls)==null?void 0:m.has(e.url),o=e.url.includes("/npub1");let a=!0;const c=e.url;if(r)return;if(s){this.debug(`Refusing to add relay ${c}: blacklisted`);return}if(o){this.debug(`Refusing to add relay ${c}: is a filter relay`);return}if((k=this.ndk.cacheAdapter)!=null&&k.getRelayStatus){const R=this.ndk.cacheAdapter.getRelayStatus(c);if(R!=null&&R.dontConnectBefore){if(R.dontConnectBefore>Date.now()){const B=R.dontConnectBefore-Date.now();this.debug(`Refusing to add relay ${c}: delayed connect for ${B}ms`),setTimeout(()=>{this.addRelay(e,t)},B);return}a=!1}}const l=R=>this.emit("notice",e,R),f=()=>this.handleRelayConnect(c),h=()=>this.handleRelayReady(e),u=()=>this.emit("relay:disconnect",e),p=()=>this.handleFlapping(e),y=R=>this.emit("relay:auth",e,R),b=()=>this.emit("relay:authed",e);e.off("notice",l),e.off("connect",f),e.off("ready",h),e.off("disconnect",u),e.off("flapping",p),e.off("auth",y),e.off("authed",b),e.on("notice",l),e.on("connect",f),e.on("ready",h),e.on("disconnect",u),e.on("flapping",p),e.on("auth",y),e.on("authed",b),e.on("delayed-connect",R=>{var B;(B=this.ndk.cacheAdapter)!=null&&B.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+R})}),this._relays.set(c,e),t&&this.autoConnectRelays.add(c),t&&this.status==="active"&&(this.emit("relay:connecting",e),e.connect(void 0,a).catch(R=>{this.debug(`Failed to connect to relay ${c}`,R)}))}removeRelay(e){const t=this.relays.get(e);if(t)return t.disconnect(),this.relays.delete(e),this.autoConnectRelays.delete(e),this.emit("relay:disconnect",t),!0;const r=this.temporaryRelayTimers.get(e);return r&&(clearTimeout(r),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=normalizeRelayUrl(e),r=this.relays.get(t);return r?r.status===5:!1}getRelay(e,t=!0,r=!1,s){let o=this.relays.get(normalizeRelayUrl(e));return o||(o=new NDKRelay(e,void 0,this.ndk),o.connectivity.netDebug=this.ndk.netDebug,r?this.useTemporaryRelay(o,3e4,s):this.addRelay(o,t)),o}handleRelayConnect(e){const t=this.relays.get(e);if(!t){console.error("NDK BUG: relay not found in pool",{relayUrl:e});return}this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")}handleRelayReady(e){this.emit("relay:ready",e)}async connect(e){this.status="active",this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}ms`:""}...`);const t=Array.from(this.autoConnectRelays.keys()).map(a=>this.relays.get(a)).filter(a=>!!a);for(const a of t)a.status!==5&&a.status!==4&&(this.emit("relay:connecting",a),a.connect().catch(c=>{this.debug(`Failed to connect to relay ${a.url}: ${c??"No reason specified"}`)}));const r=()=>t.every(a=>a.status===5),s=new Promise(a=>{if(r()){a();return}const c=[];for(const l of t){const f=()=>{if(r()){for(let h=0;h<t.length;h++)t[h].off("connect",c[h]);a()}};c.push(f),l.on("connect",f)}}),o=typeof e=="number"?new Promise(a=>setTimeout(a,e)):new Promise(()=>{});await Promise.race([s,o])}checkOnFlappingRelays(){const e=this.flappingRelays.size,t=this.relays.size;if(e/t>=.8)for(const r of this.flappingRelays)this.backoffTimes.set(r,0)}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t=t*2,this.backoffTimes.set(e.url,t),this.debug(`Backoff time for ${e.url} is ${t}ms`),setTimeout(()=>{this.debug(`Attempting to reconnect to ${e.url}`),this.emit("relay:connecting",e),e.connect(),this.checkOnFlappingRelays()},t),e.disconnect(),this.emit("flapping",e)}size(){return this.relays.size}stats(){const e={total:0,connected:0,disconnected:0,connecting:0};for(const t of this.relays.values())e.total++,t.status===5?e.connected++:t.status===1?e.disconnected++:t.status===4&&e.connecting++;return e}connectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5)}permanentAndConnectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5&&!this.temporaryRelayTimers.has(e.url))}urls(){return Array.from(this.relays.keys())}},oe,NDKCashuMintList=(oe=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_p2pk");this.kind??(this.kind=10019)}static from(t){return new oe(t.ndk,t)}set relays(t){this.tags=this.tags.filter(r=>r[0]!=="relay");for(const r of t)this.tags.push(["relay",r])}get relays(){const t=[];for(const r of this.tags)r[0]==="relay"&&t.push(r[1]);return t}set mints(t){this.tags=this.tags.filter(r=>r[0]!=="mint");for(const r of t)this.tags.push(["mint",r])}get mints(){const t=[];for(const r of this.tags)r[0]==="mint"&&t.push(r[1]);return Array.from(new Set(t))}get p2pk(){return this._p2pk?this._p2pk:(this._p2pk=this.tagValue("pubkey")??this.pubkey,this._p2pk)}set p2pk(t){this._p2pk=t,this.removeTag("pubkey"),t&&this.tags.push(["pubkey",t])}get relaySet(){return NDKRelaySet.fromRelayUrls(this.relays,this.ndk)}},g(oe,"kind",10019),g(oe,"kinds",[10019]),oe),ae,NDKArticle=(ae=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=30023)}static from(e){return new ae(e.ndk,e)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}get summary(){return this.tagValue("summary")}set summary(e){this.removeTag("summary"),e&&this.tags.push(["summary",e])}get published_at(){const e=this.tagValue("published_at");if(e){let t=Number.parseInt(e);return t>1e12&&(t=Math.floor(t/1e3)),t}}set published_at(e){this.removeTag("published_at"),e!==void 0&&this.tags.push(["published_at",e.toString()])}async generateTags(){return super.generateTags(),this.published_at||(this.published_at=this.created_at),super.generateTags()}get url(){return this.tagValue("url")}set url(e){e?this.tags.push(["url",e]):this.removeTag("url")}},g(ae,"kind",30023),g(ae,"kinds",[30023]),ae);function proofsTotalBalance(n){return n.reduce((e,t)=>{if(t.amount<0)throw new Error("proof amount is negative");return e+t.amount},0)}var ce,NDKCashuToken=(ce=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_proofs",[]);g(this,"_mint");g(this,"_deletes",[]);g(this,"original");this.kind??(this.kind=7375)}static async from(t){const r=new ce(t.ndk,t);r.original=t;try{await r.decrypt()}catch{r.content=r.original.content}try{const s=JSON.parse(r.content);if(r.proofs=s.proofs,r.mint=s.mint??r.tagValue("mint"),r.deletedTokens=s.del??[],!Array.isArray(r.proofs))return}catch{return}return r}get proofs(){return this._proofs}set proofs(t){const r=new Set;this._proofs=t.filter(s=>r.has(s.C)?(console.warn("Passed in proofs had duplicates, ignoring",s.C),!1):s.amount<0?(console.warn("Invalid proof with negative amount",s),!1):(r.add(s.C),!0)).map(this.cleanProof)}cleanProof(t){return{id:t.id,amount:t.amount,C:t.C,secret:t.secret}}async toNostrEvent(t){if(!this.ndk)throw new Error("no ndk");if(!this.ndk.signer)throw new Error("no signer");const r={proofs:this.proofs.map(this.cleanProof),mint:this.mint,del:this.deletedTokens??[]};this.content=JSON.stringify(r);const s=await this.ndk.signer.user();return await this.encrypt(s,void 0,"nip44"),super.toNostrEvent(t)}set mint(t){this._mint=t}get mint(){return this._mint}get deletedTokens(){return this._deletes}set deletedTokens(t){this._deletes=t}get amount(){return proofsTotalBalance(this.proofs)}async publish(t,r,s){return this.original?this.original.publish(t,r,s):super.publish(t,r,s)}},g(ce,"kind",7375),g(ce,"kinds",[7375]),ce),le,NDKHighlight=(le=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_article");this.kind??(this.kind=9802)}static from(t){return new le(t.ndk,t)}get url(){return this.tagValue("r")}set context(t){t===void 0?this.tags=this.tags.filter(([r,s])=>r!=="context"):(this.tags=this.tags.filter(([r,s])=>r!=="context"),this.tags.push(["context",t]))}get context(){var t;return((t=this.tags.find(([r,s])=>r==="context"))==null?void 0:t[1])??void 0}get article(){return this._article}set article(t){this._article=t,typeof t=="string"?this.tags.push(["r",t]):this.tag(t)}getArticleTag(){return this.getMatchingTags("a")[0]||this.getMatchingTags("e")[0]||this.getMatchingTags("r")[0]}async getArticle(){var s;if(this._article!==void 0)return this._article;let t;const r=this.getArticleTag();if(r){switch(r[0]){case"a":{const[o,a,c]=r[1].split(":");t=nip19_exports.naddrEncode({kind:Number.parseInt(o),pubkey:a,identifier:c});break}case"e":t=nip19_exports.noteEncode(r[1]);break;case"r":this._article=r[1];break}if(t){let o=await((s=this.ndk)==null?void 0:s.fetchEvent(t));o&&(o.kind===30023&&(o=NDKArticle.from(o)),this._article=o)}return this._article}}},g(le,"kind",9802),g(le,"kinds",[9802]),le);function mapImetaTag(n){const e={};if(n.length===2){const r=n[1].split(" ");for(let s=0;s<r.length;s+=2){const o=r[s],a=r[s+1];o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}const t=n.slice(1);for(const r of t){const s=r.split(" "),o=s[0],a=s.slice(1).join(" ");o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}function imetaTagToTag(n){const e=["imeta"];for(const[t,r]of Object.entries(n))if(Array.isArray(r))for(const s of r)e.push(`${t} ${s}`);else r&&e.push(`${t} ${r}`);return e}var ue,NDKImage=(ue=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imetas");this.kind??(this.kind=20)}static from(t){return new ue(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag).filter(t=>!!t.url),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}},g(ue,"kind",20),g(ue,"kinds",[20]),ue),Re,NDKList=(Re=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_encryptedTags");g(this,"encryptedTagsLength");this.kind??(this.kind=30001)}static from(t){return new Re(t.ndk,t)}get title(){const t=this.tagValue("title")||this.tagValue("name");return t||(this.kind===3?"Contacts":this.kind===1e4?"Mute":this.kind===10001?"Pinned Notes":this.kind===10002?"Relay Metadata":this.kind===10003?"Bookmarks":this.kind===10004?"Communities":this.kind===10005?"Public Chats":this.kind===10006?"Blocked Relays":this.kind===10007?"Search Relays":this.kind===10050?"Direct Message Receive Relays":this.kind===10015?"Interests":this.kind===10030?"Emojis":this.tagValue("d"))}set title(t){this.removeTag(["title","name"]),t&&this.tags.push(["title",t])}get name(){return this.title}set name(t){this.title=t}get description(){return this.tagValue("description")}set description(t){this.removeTag("description"),t&&this.tags.push(["description",t])}get image(){return this.tagValue("image")}set image(t){this.removeTag("image"),t&&this.tags.push(["image",t])}isEncryptedTagsCacheValid(){return!!(this._encryptedTags&&this.encryptedTagsLength===this.content.length)}async encryptedTags(t=!0){if(t&&this.isEncryptedTagsCacheValid())return this._encryptedTags;if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const r=await this.ndk.signer.user();try{if(this.content.length>0)try{const s=await this.ndk.signer.decrypt(r,this.content),o=JSON.parse(s);return o!=null&&o[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=o):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch{}}catch{}return[]}validateTag(t){return!0}getItems(t){return this.tags.filter(r=>r[0]===t)}get items(){return this.tags.filter(t=>!["d","L","l","title","name","description","published_at","summary","image","thumb","alt","expiration","subject","client"].includes(t[0]))}async addItem(t,r=void 0,s=!1,o="bottom"){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let a;if(t instanceof NDKEvent)a=[t.tagReference(r)];else if(t instanceof NDKUser)a=t.referenceTags();else if(t instanceof NDKRelay)a=t.referenceTags();else if(Array.isArray(t))a=[t];else throw new Error("Invalid object type");if(r&&a[0].push(r),s){const c=await this.ndk.signer.user(),l=await this.encryptedTags();o==="top"?l.unshift(...a):l.push(...a),this._encryptedTags=l,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(l),await this.encrypt(c)}else o==="top"?this.tags.unshift(...a):this.tags.push(...a);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItemByValue(t,r=!0){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const s=this.tags.findIndex(l=>l[1]===t);s>=0&&this.tags.splice(s,1);const o=await this.ndk.signer.user(),a=await this.encryptedTags(),c=a.findIndex(l=>l[1]===t);if(c>=0&&(a.splice(c,1),this._encryptedTags=a,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(a),await this.encrypt(o)),r)return this.publishReplaceable();this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(t,r){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(r){const s=await this.ndk.signer.user(),o=await this.encryptedTags();o.splice(t,1),this._encryptedTags=o,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(o),await this.encrypt(s)}else this.tags.splice(t,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}has(t){return this.items.some(r=>r[1]===t)}filterForItems(){const t=new Set,r=new Map,s=[];for(const o of this.items)if(o[0]==="e"&&o[1])t.add(o[1]);else if(o[0]==="a"&&o[1]){const[a,c,l]=o[1].split(":");if(!a||!c)continue;const f=`${a}:${c}`,h=r.get(f)||[];h.push(l||""),r.set(f,h)}if(t.size>0&&s.push({ids:Array.from(t)}),r.size>0)for(const[o,a]of r.entries()){const[c,l]=o.split(":");s.push({kinds:[Number.parseInt(c)],authors:[l],"#d":a})}return s}},g(Re,"kinds",[10063,30001,10004,10050,10030,10015,10001,10002,10007,10006,10003]),Re),lists_default=NDKList,re,NDKNutzap=(re=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"debug");g(this,"_proofs",[]);g(this,"sender",this.author);this.kind??(this.kind=9321),this.debug=(t==null?void 0:t.debug.extend("nutzap"))??createDebug2("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const s=this.getMatchingTags("proof");s.length?this._proofs=s.map(o=>JSON.parse(o[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(t){const r=new re(t.ndk,t);if(!(!r._proofs||!r._proofs.length))return r}set comment(t){this.content=t??""}get comment(){const t=this.tagValue("comment");return t||this.content}set proofs(t){this._proofs=t,this.tags=this.tags.filter(r=>r[0]!=="proof");for(const r of t)this.tags.push(["proof",JSON.stringify(r)])}get proofs(){return this._proofs}get rawP2pk(){var r;const t=this.proofs[0];try{const s=JSON.parse(t.secret);let o;if(typeof s=="string"?(o=JSON.parse(s),this.debug("stringified payload",t.secret)):typeof s=="object"&&(o=s),Array.isArray(o)&&o[0]==="P2PK"&&o.length>1&&typeof o[1]=="object"&&o[1]!==null||typeof o=="object"&&o!==null&&typeof((r=o[1])==null?void 0:r.data)=="string")return o[1].data}catch(s){this.debug("error parsing p2pk pubkey",s,this.proofs[0])}}get p2pk(){const t=this.rawP2pk;if(t)return t.startsWith("02")?t.slice(2):t}get mint(){return this.tagValue("u")}set mint(t){this.replaceTag(["u",t])}get unit(){let t=this.tagValue("unit")??"sat";return t!=null&&t.startsWith("msat")&&(t="sat"),t}set unit(t){if(this.removeTag("unit"),t!=null&&t.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");t&&this.tag(["unit",t])}get amount(){return this.proofs.reduce((r,s)=>r+s.amount,0)}set target(t){this.tags=this.tags.filter(r=>r[0]!=="p"),t instanceof NDKEvent&&this.tags.push(t.tagReference())}set recipientPubkey(t){this.removeTag("p"),this.tag(["p",t])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const t=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:t}):new NDKUser({pubkey:t})}async toNostrEvent(){this.unit==="msat"&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const t=await super.toNostrEvent();return t.content=this.comment,t}get isValid(){let t=0,r=0,s=0;for(const o of this.tags)o[0]==="e"&&t++,o[0]==="p"&&r++,o[0]==="u"&&s++;return r===1&&s===1&&t<=1&&this.proofs.length>0}},g(re,"kind",9321),g(re,"kinds",[re.kind]),re);function proofP2pk(n){var e;try{const t=JSON.parse(n.secret);let r={};if(typeof t=="string"?r=JSON.parse(t):typeof t=="object"&&(r=t),r[0]==="P2PK"&&((e=r[1])==null?void 0:e.data))return r[1].data}catch(t){console.error("error parsing p2pk pubkey",t,n)}}function proofP2pkNostr(n){const e=proofP2pk(n);if(e)return e.startsWith("02")&&e.length===66?e.slice(2):e}function cashuPubkeyToNostrPubkey(n){if(n.startsWith("02")&&n.length===66)return n.slice(2)}var he,NDKSimpleGroupMemberList=(he=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"relaySet");g(this,"memberSet",new Set);this.kind??(this.kind=39002),this.memberSet=new Set(this.members)}static from(t){return new he(t.ndk,t)}get members(){return this.getMatchingTags("p").map(t=>t[1])}hasMember(t){return this.memberSet.has(t)}async publish(t,r,s){return t??(t=this.relaySet),super.publishReplaceable(t,r,s)}},g(he,"kind",39002),g(he,"kinds",[39002]),he),de,NDKSimpleGroupMetadata=(de=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=39e3)}static from(e){return new de(e.ndk,e)}get name(){return this.tagValue("name")}get picture(){return this.tagValue("picture")}get about(){return this.tagValue("about")}get scope(){if(this.getMatchingTags("public").length>0)return"public";if(this.getMatchingTags("public").length>0)return"private"}set scope(e){this.removeTag("public"),this.removeTag("private"),e==="public"?this.tags.push(["public",""]):e==="private"&&this.tags.push(["private",""])}get access(){if(this.getMatchingTags("open").length>0)return"open";if(this.getMatchingTags("closed").length>0)return"closed"}set access(e){this.removeTag("open"),this.removeTag("closed"),e==="open"?this.tags.push(["open",""]):e==="closed"&&this.tags.push(["closed",""])}},g(de,"kind",39e3),g(de,"kinds",[39e3]),de),NDKStoryStickerType=(n=>(n.Pubkey="pubkey",n.Event="event",n.Prompt="prompt",n.Text="text",n.Countdown="countdown",n))(NDKStoryStickerType||{});function strToPosition(n){const[e,t]=n.split(",").map(Number);return{x:e,y:t}}function strToDimension(n){const[e,t]=n.split("x").map(Number);return{width:e,height:t}}var X,NDKStorySticker=(X=class{constructor(e){g(this,"type");g(this,"value");g(this,"position");g(this,"dimension");g(this,"properties");g(this,"hasValidDimensions",()=>typeof this.dimension.width=="number"&&typeof this.dimension.height=="number"&&!Number.isNaN(this.dimension.width)&&!Number.isNaN(this.dimension.height));g(this,"hasValidPosition",()=>typeof this.position.x=="number"&&typeof this.position.y=="number"&&!Number.isNaN(this.position.x)&&!Number.isNaN(this.position.y));if(Array.isArray(e)){const t=e;if(t[0]!=="sticker"||t.length<5)throw new Error("Invalid sticker tag");this.type=t[1],this.value=t[2],this.position=strToPosition(t[3]),this.dimension=strToDimension(t[4]);const r={};for(let s=5;s<t.length;s++){const[o,...a]=t[s].split(" ");r[o]=a.join(" ")}Object.keys(r).length>0&&(this.properties=r)}else this.type=e,this.value=void 0,this.position={x:0,y:0},this.dimension={width:0,height:0}}static fromTag(e){try{return new X(e)}catch{return null}}get style(){var e;return(e=this.properties)==null?void 0:e.style}set style(e){var t;e?this.properties={...this.properties,style:e}:(t=this.properties)==null||delete t.style}get rotation(){var e;return(e=this.properties)!=null&&e.rot?Number.parseFloat(this.properties.rot):void 0}set rotation(e){var t;e!==void 0?this.properties={...this.properties,rot:e.toString()}:(t=this.properties)==null||delete t.rot}get isValid(){return this.hasValidDimensions()&&this.hasValidPosition()}toTag(){if(!this.isValid){const r=[this.hasValidDimensions()?void 0:"dimensions is invalid",this.hasValidPosition()?void 0:"position is invalid"].filter(Boolean);throw new Error(`Invalid sticker: ${r.join(", ")}`)}let e;switch(this.type){case"event":e=this.value.tagId();break;case"pubkey":e=this.value.pubkey;break;default:e=this.value}const t=["sticker",this.type,e,coordinates(this.position),dimension(this.dimension)];if(this.properties)for(const[r,s]of Object.entries(this.properties))t.push(`${r} ${s}`);return t}},g(X,"Text","text"),g(X,"Pubkey","pubkey"),g(X,"Event","event"),g(X,"Prompt","prompt"),g(X,"Countdown","countdown"),X),pe,NDKStory=(pe=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imeta");g(this,"_dimensions");if(this.kind??(this.kind=23),r)for(const s of r.tags)switch(s[0]){case"imeta":this._imeta=mapImetaTag(s);break;case"dim":this.dimensions=strToDimension(s[1]);break}}static from(t){return new pe(t.ndk,t)}get isValid(){return!!this.imeta}get imeta(){return this._imeta}set imeta(t){this._imeta=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),t&&this.tags.push(imetaTagToTag(t))}get dimensions(){const t=this.tagValue("dim");if(t)return strToDimension(t)}set dimensions(t){this.removeTag("dim"),t&&this.tags.push(["dim",`${t.width}x${t.height}`])}get duration(){const t=this.tagValue("dur");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("dur"),t!==void 0&&this.tags.push(["dur",t.toString()])}get stickers(){const t=[];for(const r of this.tags){if(r[0]!=="sticker"||r.length<5)continue;const s=NDKStorySticker.fromTag(r);s&&t.push(s)}return t}addSticker(t){let r;if(t instanceof NDKStorySticker)r=t;else{const s=["sticker",t.type,typeof t.value=="string"?t.value:"",coordinates(t.position),dimension(t.dimension)];if(t.properties)for(const[o,a]of Object.entries(t.properties))s.push(`${o} ${a}`);r=new NDKStorySticker(s),r.value=t.value}r.type==="pubkey"?this.tag(r.value):r.type==="event"&&this.tag(r.value),this.tags.push(r.toTag())}removeSticker(t){const r=this.stickers;if(t<0||t>=r.length)return;let s=0;for(let o=0;o<this.tags.length;o++)if(this.tags[o][0]==="sticker"){if(s===t){this.tags.splice(o,1);break}s++}}},g(pe,"kind",23),g(pe,"kinds",[23]),pe),coordinates=n=>`${n.x},${n.y}`,dimension=n=>`${n.width}x${n.height}`,possibleIntervalFrequencies=["daily","weekly","monthly","quarterly","yearly"];function calculateTermDurationInSeconds(n){switch(n){case"daily":return 24*60*60;case"weekly":return 7*24*60*60;case"monthly":return 30*24*60*60;case"quarterly":return 3*30*24*60*60;case"yearly":return 365*24*60*60}}function newAmount(n,e,t){return["amount",n.toString(),e,t]}function parseTagToSubscriptionAmount(n){const e=Number.parseInt(n[1]);if(Number.isNaN(e)||e===void 0||e===null||e<=0)return;const t=n[2];if(t===void 0||t==="")return;const r=n[3];if(r!==void 0&&possibleIntervalFrequencies.includes(r))return{amount:e,currency:t,term:r}}var ye,NDKSubscriptionTier=(ye=class extends NDKArticle{constructor(e,t){const r=(t==null?void 0:t.kind)??37001;super(e,t),this.kind=r}static from(e){return new ye(e.ndk,e)}get perks(){return this.getMatchingTags("perk").map(e=>e[1]).filter(e=>e!==void 0)}addPerk(e){this.tags.push(["perk",e])}get amounts(){return this.getMatchingTags("amount").map(e=>parseTagToSubscriptionAmount(e)).filter(e=>e!==void 0)}addAmount(e,t,r){this.tags.push(newAmount(e,t,r))}set relayUrl(e){this.tags.push(["r",e])}get relayUrls(){return this.getMatchingTags("r").map(e=>e[1]).filter(e=>e!==void 0)}get verifierPubkey(){return this.tagValue("p")}set verifierPubkey(e){this.removeTag("p"),e&&this.tags.push(["p",e])}get isValid(){return this.title!==void 0&&this.amounts.length>0}},g(ye,"kind",37001),g(ye,"kinds",[37001]),ye),me,NDKVideo=(me=class extends NDKEvent{constructor(){super(...arguments);g(this,"_imetas")}static from(t){return new me(t.ndk,t.rawEvent())}get title(){return this.tagValue("title")}set title(t){this.removeTag("title"),t&&this.tags.push(["title",t])}get thumbnail(){var r;let t;return this.imetas&&this.imetas.length>0&&(t=(r=this.imetas[0].image)==null?void 0:r[0]),t??this.tagValue("thumb")}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}get url(){return this.imetas&&this.imetas.length>0?this.imetas[0].url:this.tagValue("url")}get published_at(){const t=this.tagValue("published_at");if(t)return Number.parseInt(t)}async generateTags(){var t,r;if(super.generateTags(),!this.kind&&(r=(t=this.imetas)==null?void 0:t[0])!=null&&r.dim){const[s,o]=this.imetas[0].dim.split("x"),a=s&&o&&Number.parseInt(s)<Number.parseInt(o);this.duration&&this.duration<120&&a?this.kind=22:this.kind=21}return super.generateTags()}get duration(){const t=this.tagValue("duration");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("duration"),t!==void 0&&this.tags.push(["duration",Math.floor(t).toString()])}},g(me,"kind",21),g(me,"kinds",[34235,34236,22,21]),me),be,NDKWiki=(be=class extends NDKArticle{static from(e){return new be(e.ndk,e.rawEvent())}get isDefered(){return this.hasTag("a","defer")}get deferedId(){return this.tagValue("a","defer")}set defer(e){this.removeTag("a","defer"),this.tag(e,"defer")}},g(be,"kind",30818),g(be,"kinds",[30818]),be),we,NDKWikiMergeRequest=(we=class extends NDKEvent{static from(e){return new we(e.ndk,e.rawEvent())}get targetId(){return this.tagValue("a")}set target(e){this.tags=this.tags.filter(t=>{if(t[0]==="a"||t[0]==="e"&&t[3]!=="source")return!0}),this.tag(e)}get sourceId(){return this.tagValue("e","source")}set source(e){this.removeTag("e","source"),this.tag(e,"source",!1,"e")}},g(we,"kind",818),g(we,"kinds",[818]),we),$e,NDKBlossomList=($e=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=10063)}static from(e){return new $e(e.ndk,e.rawEvent())}get servers(){return this.tags.filter(e=>e[0]==="server").map(e=>e[1])}set servers(e){this.tags=this.tags.filter(t=>t[0]!=="server");for(const t of e)this.tags.push(["server",t])}get default(){const e=this.servers;return e.length>0?e[0]:void 0}set default(e){if(!e)return;const r=this.servers.filter(s=>s!==e);this.servers=[e,...r]}addServer(e){if(!e)return;const t=this.servers;t.includes(e)||(this.servers=[...t,e])}removeServer(e){if(!e)return;const t=this.servers;this.servers=t.filter(r=>r!==e)}},g($e,"kinds",[10063]),$e),Ee,NDKFollowPack=(Ee=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=39089)}static from(e){return new Ee(e.ndk,e)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get image(){const e=this.tags.find(t=>t[0]==="imeta");if(e){const t=mapImetaTag(e);if(t.url)return t.url}return this.tagValue("image")}set image(e){this.tags=this.tags.filter(t=>t[0]!=="imeta"&&t[0]!=="image"),typeof e=="string"?e!==void 0&&this.tags.push(["image",e]):e&&typeof e=="object"&&(this.tags.push(imetaTagToTag(e)),e.url&&this.tags.push(["image",e.url]))}get pubkeys(){return Array.from(new Set(this.tags.filter(e=>e[0]==="p").map(e=>e[1])))}set pubkeys(e){this.tags=this.tags.filter(t=>t[0]!=="p");for(const t of e)this.tags.push(["p",t])}get description(){return this.tagValue("description")}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}},g(Ee,"kind",39089),g(Ee,"kinds",[39089,39092]),Ee),signerRegistry=new Map;function registerSigner(n,e){signerRegistry.set(n,e)}var NDKPrivateKeySigner=class Ce{constructor(e,t){g(this,"_user");g(this,"_privateKey");g(this,"_pubkey");if(typeof e=="string")if(e.startsWith("nsec1")){const{type:r,data:s}=nip19_exports.decode(e);if(r==="nsec")this._privateKey=s;else throw new Error("Invalid private key provided.")}else if(e.length===64)this._privateKey=hexToBytes(e);else throw new Error("Invalid private key provided.");else this._privateKey=e;this._pubkey=getPublicKey(this._privateKey),t&&(this._user=t.getUser({pubkey:this._pubkey})),this._user??(this._user=new NDKUser({pubkey:this._pubkey}))}get privateKey(){if(!this._privateKey)throw new Error("Not ready");return bytesToHex(this._privateKey)}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}get nsec(){if(!this._privateKey)throw new Error("Not ready");return nip19_exports.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nip19_exports.npubEncode(this._pubkey)}static generate(){const e=generateSecretKey();return new Ce(e)}async blockUntilReady(){return this._user}async user(){return this._user}get userSync(){return this._user}async sign(e){if(!this._privateKey)throw Error("Attempted to sign without a private key");return finalizeEvent(e,this._privateKey).sig}async encryptionEnabled(e){const t=[];return(!e||e==="nip04")&&t.push("nip04"),(!e||e==="nip44")&&t.push("nip44"),t}async encrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.encrypt(t,o)}return await nip04_exports.encrypt(this._privateKey,s,t)}async decrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.decrypt(t,o)}return await nip04_exports.decrypt(this._privateKey,s,t)}toPayload(){if(!this._privateKey)throw new Error("Private key not available");const e={type:"private-key",payload:this.privateKey};return JSON.stringify(e)}static async fromPayload(e,t){const r=JSON.parse(e);if(r.type!=="private-key")throw new Error(`Invalid payload type: expected 'private-key', got ${r.type}`);if(!r.payload||typeof r.payload!="string")throw new Error("Invalid payload content for private-key signer");return new Ce(r.payload,t)}};registerSigner("private-key",NDKPrivateKeySigner);var se,NDKProject=(se=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_signer");this.kind=31933}static from(t){return new se(t.ndk,t.rawEvent())}set repo(t){this.removeTag("repo"),t&&this.tags.push(["repo",t])}set hashtags(t){this.removeTag("hashtags"),t.filter(r=>r.length>0).length&&this.tags.push(["hashtags",...t])}get hashtags(){const t=this.tags.find(r=>r[0]==="hashtags");return t?t.slice(1):[]}get repo(){return this.tagValue("repo")}get title(){return this.tagValue("title")}set title(t){this.removeTag("title"),t&&this.tags.push(["title",t])}get picture(){return this.tagValue("picture")}set picture(t){this.removeTag("picture"),t&&this.tags.push(["picture",t])}set description(t){this.content=t}get description(){return this.content}get slug(){return this.dTag??"empty-dtag"}async getSigner(){var r,s;if(this._signer)return this._signer;const t=this.tagValue("key");if(!t)this._signer=NDKPrivateKeySigner.generate(),await this.encryptAndSaveNsec();else{const o=await((s=(r=this.ndk)==null?void 0:r.signer)==null?void 0:s.decrypt(this.ndk.activeUser,t));if(!o)throw new Error("Failed to decrypt project key or missing signer context.");this._signer=new NDKPrivateKeySigner(o)}return this._signer}async getNsec(){return(await this.getSigner()).privateKey}async setNsec(t){this._signer=new NDKPrivateKeySigner(t),await this.encryptAndSaveNsec()}async encryptAndSaveNsec(){var s,o;if(!this._signer)throw new Error("Signer is not set.");const t=this._signer.privateKey,r=await((o=(s=this.ndk)==null?void 0:s.signer)==null?void 0:o.encrypt(this.ndk.activeUser,t));r&&(this.removeTag("key"),this.tags.push(["key",r]))}},g(se,"kind",31933),g(se,"kinds",[se.kind]),se),ve,NDKThread=(ve=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=11)}static from(e){return new ve(e.ndk,e)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}},g(ve,"kind",11),g(ve,"kinds",[11]),ve),ke,NDKDraft=(ke=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_event");g(this,"counterparty");this.kind??(this.kind=31234)}static from(t){return new ke(t.ndk,t)}set identifier(t){this.removeTag("d"),this.tags.push(["d",t])}get identifier(){return this.dTag}set event(t){t instanceof NDKEvent?this._event=t:this._event=new NDKEvent(void 0,t),this.prepareEvent()}set checkpoint(t){t?(this.tags.push(t.tagReference()),this.kind=1234):(this.removeTag("a"),this.kind=31234)}get isCheckpoint(){return this.kind===1234}get isProposal(){const t=this.tagValue("p");return!!t&&t!==this.pubkey}async getEvent(t){var r;if(this._event)return this._event;if(t??(t=(r=this.ndk)==null?void 0:r.signer),!t)throw new Error("No signer available");if(this.content&&this.content.length>0)try{const s=t.pubkey,a=[this.tagValue("p"),this.pubkey].filter(Boolean).find(f=>f!==s);let c;c=new NDKUser({pubkey:a??s}),await this.decrypt(c,t);const l=JSON.parse(this.content);return this._event=await wrapEvent(new NDKEvent(this.ndk,l)),this._event}catch(s){console.error(s);return}else return null}prepareEvent(){if(!this._event)throw new Error("No event has been provided");this.removeTag("k"),this._event.kind&&this.tags.push(["k",this._event.kind.toString()]),this.content=JSON.stringify(this._event.rawEvent())}async save({signer:t,publish:r,relaySet:s}){var a;if(t??(t=(a=this.ndk)==null?void 0:a.signer),!t)throw new Error("No signer available");const o=this.counterparty||await t.user();if(await this.encrypt(o,t),this.counterparty){const c=this.counterparty.pubkey;this.removeTag("p"),this.tags.push(["p",c])}if(r!==!1)return this.publishReplaceable(s)}},g(ke,"kind",31234),g(ke,"kinds",[31234,1234]),ke),_e,NDKTask=(_e=class extends NDKEvent{constructor(e,t){super(e,t),this.kind=1934}static from(e){return new _e(e.ndk,e.rawEvent())}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get title(){return this.tagValue("title")}set project(e){this.removeTag("a"),this.tags.push(e.tagReference())}get projectSlug(){var t;const e=this.getMatchingTags("a")[0];return e?(t=e[1].split(/:/))==null?void 0:t[2]:void 0}},g(_e,"kind",1934),g(_e,"kinds",[1934]),_e),xe,NDKProjectTemplate=(xe=class extends NDKEvent{constructor(e,t){super(e,t),this.kind=30717}static from(e){return new xe(e.ndk,e.rawEvent())}get templateId(){return this.dTag??""}set templateId(e){this.dTag=e}get name(){return this.tagValue("title")??""}set name(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get description(){return this.tagValue("description")??""}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}get repoUrl(){return this.tagValue("uri")??""}set repoUrl(e){this.removeTag("uri"),e&&this.tags.push(["uri",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}get command(){return this.tagValue("command")}set command(e){this.removeTag("command"),e&&this.tags.push(["command",e])}get agentConfig(){const e=this.tagValue("agent");if(e)try{return JSON.parse(e)}catch{return}}set agentConfig(e){this.removeTag("agent"),e&&this.tags.push(["agent",JSON.stringify(e)])}get templateTags(){return this.getMatchingTags("t").map(e=>e[1]).filter(Boolean)}set templateTags(e){this.tags=this.tags.filter(t=>t[0]!=="t"),e.forEach(t=>{t&&this.tags.push(["t",t])})}},g(xe,"kind",30717),g(xe,"kinds",[30717]),xe),registeredEventClasses=new Set;function registerEventClass(n){registeredEventClasses.add(n)}function unregisterEventClass(n){registeredEventClasses.delete(n)}function getRegisteredEventClasses(){return new Set(registeredEventClasses)}function wrapEvent(n){const e=new Map,r=[...[NDKImage,NDKVideo,NDKCashuMintList,NDKArticle,NDKHighlight,NDKDraft,NDKWiki,NDKNutzap,NDKProject,NDKTask,NDKProjectTemplate,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKSubscriptionTier,NDKCashuToken,NDKList,NDKStory,NDKBlossomList,NDKFollowPack,NDKThread],...registeredEventClasses];for(const o of r)for(const a of o.kinds)e.set(a,o);const s=e.get(n.kind);return s?s.from(n):n}var MAX_SUBID_LENGTH=20;function queryFullyFilled(n){return!!(filterIncludesIds(n.filter)&&resultHasAllRequestedIds(n))}function compareFilter(n,e){if(Object.keys(n).length!==Object.keys(e).length)return!1;for(const[t,r]of Object.entries(n)){const s=e[t];if(!s)return!1;if(Array.isArray(r)&&Array.isArray(s)){const o=r;for(const a of s){const c=a;if(!o.includes(c))return!1}}else if(s!==r)return!1}return!0}function filterIncludesIds(n){return!!n.ids}function resultHasAllRequestedIds(n){const e=n.filter.ids;return!!e&&e.length===n.eventFirstSeen.size}function generateSubId(n,e){var c;const t=n.map(l=>l.subId).filter(Boolean),r=[],s=new Set,o=new Set;if(t.length>0)r.push(Array.from(new Set(t)).join(","));else{for(const l of e)for(const f of Object.keys(l))f==="kinds"?(c=l.kinds)==null||c.forEach(h=>o.add(h)):s.add(f);o.size>0&&r.push(`kinds:${Array.from(o).join(",")}`),s.size>0&&r.push(Array.from(s).join(","))}let a=r.join("-");return a.length>MAX_SUBID_LENGTH&&(a=a.substring(0,MAX_SUBID_LENGTH)),a+=`-${Math.floor(Math.random()*999).toString()}`,a}function filterForEventsTaggingId(n){try{const e=nip19_exports.decode(n);switch(e.type){case"naddr":return{"#a":[`${e.data.kind}:${e.data.pubkey}:${e.data.identifier}`]};case"nevent":return{"#e":[e.data.id]};case"note":return{"#e":[e.data]};case"nprofile":return{"#p":[e.data.pubkey]};case"npub":return{"#p":[e.data]}}}catch{}}function filterAndRelaySetFromBech32(n,e){const t=filterFromId(n),r=relaysFromBech32(n,e);return r.length===0?{filter:t}:{filter:t,relaySet:new NDKRelaySet(new Set(r),e)}}function filterFromId(n){let e;if(n.match(NIP33_A_REGEX)){const[t,r,s]=n.split(":"),o={authors:[r],kinds:[Number.parseInt(t)]};return s&&(o["#d"]=[s]),o}if(n.match(BECH32_REGEX))try{switch(e=nip19_exports.decode(n),e.type){case"nevent":{const t={ids:[e.data.id]};return e.data.author&&(t.authors=[e.data.author]),e.data.kind&&(t.kinds=[e.data.kind]),t}case"note":return{ids:[e.data]};case"naddr":{const t={authors:[e.data.pubkey],kinds:[e.data.kind]};return e.data.identifier&&(t["#d"]=[e.data.identifier]),t}}}catch(t){console.error("Error decoding",n,t)}return{ids:[n]}}function isNip33AValue(n){return n.match(NIP33_A_REGEX)!==null}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/,BECH32_REGEX=/^n(event|ote|profile|pub|addr)1[\d\w]+$/;function relaysFromBech32(n,e){try{const t=nip19_exports.decode(n);if(["naddr","nevent"].includes(t==null?void 0:t.type)){const r=t.data;if(r!=null&&r.relays)return r.relays.map(s=>new NDKRelay(s,e.relayAuthDefaultPolicy,e))}}catch{}return[]}var NDKSubscriptionCacheUsage=(n=>(n.ONLY_CACHE="ONLY_CACHE",n.CACHE_FIRST="CACHE_FIRST",n.PARALLEL="PARALLEL",n.ONLY_RELAY="ONLY_RELAY",n))(NDKSubscriptionCacheUsage||{}),defaultOpts={closeOnEose:!1,cacheUsage:"CACHE_FIRST",dontSaveToCache:!1,groupable:!0,groupableDelay:100,groupableDelayType:"at-most",cacheUnconstrainFilter:["limit","since","until"]},NDKSubscription=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"subId");g(this,"filters");g(this,"opts");g(this,"pool");g(this,"skipVerification",!1);g(this,"skipValidation",!1);g(this,"relayFilters");g(this,"relaySet");g(this,"ndk");g(this,"debug");g(this,"eventFirstSeen",new Map);g(this,"eosesSeen",new Set);g(this,"lastEventReceivedAt");g(this,"mostRecentCacheEventTimestamp");g(this,"internalId");g(this,"closeOnEose");g(this,"poolMonitor");g(this,"skipOptimisticPublishEvent",!1);g(this,"cacheUnconstrainFilter");g(this,"onStopped");g(this,"eoseTimeout");g(this,"eosed",!1);this.ndk=e,this.opts={...defaultOpts,...r||{}},this.pool=this.opts.pool||e.pool,this.filters=Array.isArray(t)?t:[t],this.subId=s||this.opts.subId,this.internalId=Math.random().toString(36).substring(7),this.debug=e.debug.extend(`subscription[${this.opts.subId??this.internalId}]`),this.opts.relaySet?this.relaySet=this.opts.relaySet:this.opts.relayUrls&&(this.relaySet=NDKRelaySet.fromRelayUrls(this.opts.relayUrls,this.ndk)),this.skipVerification=this.opts.skipVerification||!1,this.skipValidation=this.opts.skipValidation||!1,this.closeOnEose=this.opts.closeOnEose||!1,this.skipOptimisticPublishEvent=this.opts.skipOptimisticPublishEvent||!1,this.cacheUnconstrainFilter=this.opts.cacheUnconstrainFilter}relaysMissingEose(){var t;return this.relayFilters?Array.from((t=this.relayFilters)==null?void 0:t.keys()).filter(r=>!this.eosesSeen.has(this.pool.getRelay(r,!1,!1))):[]}get filter(){return this.filters[0]}get groupableDelay(){var e;if(this.isGroupable())return(e=this.opts)==null?void 0:e.groupableDelay}get groupableDelayType(){var e;return((e=this.opts)==null?void 0:e.groupableDelayType)||"at-most"}isGroupable(){var e;return((e=this.opts)==null?void 0:e.groupable)||!1}shouldQueryCache(){var t;return this.opts.addSinceFromCache?!0:((t=this.opts)==null?void 0:t.cacheUsage)==="ONLY_RELAY"?!1:(this.filters.some(r=>{var s;return(s=r.kinds)==null?void 0:s.some(o=>kindIsEphemeral(o))}),!0)}shouldQueryRelays(){var e;return((e=this.opts)==null?void 0:e.cacheUsage)!=="ONLY_CACHE"}shouldWaitForCache(){var e;return this.opts.addSinceFromCache?!0:!!this.opts.closeOnEose&&!!((e=this.ndk.cacheAdapter)!=null&&e.locking)&&this.opts.cacheUsage!=="PARALLEL"}start(e=!0){let t;const r=o=>{if(e)for(const a of o)a.created_at&&(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),this.eventReceived(a,void 0,!0,!1);else{t=[];for(const a of o){a.created_at&&(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),a.ndk=this.ndk;const c=this.opts.wrap?wrapEvent(a):a;if(!c)break;if(c instanceof Promise){c.then(l=>{this.emitEvent(!1,l,void 0,!0,!1)});break}this.eventFirstSeen.set(c.id,Date.now()),t.push(c)}}},s=()=>{this.shouldQueryRelays()?(this.startWithRelays(),this.startPoolMonitor()):this.emit("eose",this)};return this.shouldQueryCache()?(t=this.startWithCache(),t instanceof Promise?this.shouldWaitForCache()?(t.then(o=>{if(r(o),queryFullyFilled(this)){this.emit("eose",this);return}s()}),null):(t.then(o=>{r(o)}),s(),null):(r(t),queryFullyFilled(this)?this.emit("eose",this):s(),t)):(s(),null)}startPoolMonitor(){this.debug.extend("pool-monitor"),this.poolMonitor=e=>{var r,s;if((r=this.relayFilters)!=null&&r.has(e.url))return;calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool).get(e.url)&&((s=this.relayFilters)==null||s.set(e.url,this.filters),e.subscribe(this,this.filters))},this.pool.on("relay:connect",this.poolMonitor)}stop(){var e;this.emit("close",this),this.poolMonitor&&this.pool.off("relay:connect",this.poolMonitor),(e=this.onStopped)==null||e.call(this)}hasAuthorsFilter(){return this.filters.some(e=>{var t;return(t=e.authors)==null?void 0:t.length})}startWithCache(){var e;return(e=this.ndk.cacheAdapter)!=null&&e.query?this.ndk.cacheAdapter.query(this):[]}startWithRelays(){let e=this.filters;if(this.opts.addSinceFromCache&&this.mostRecentCacheEventTimestamp){const t=this.mostRecentCacheEventTimestamp+1;e=e.map(r=>({...r,since:Math.max(r.since||0,t)}))}if(!this.relaySet||this.relaySet.relays.size===0)this.relayFilters=calculateRelaySetsFromFilters(this.ndk,e,this.pool);else{this.relayFilters=new Map;for(const t of this.relaySet.relays)this.relayFilters.set(t.url,e)}for(const[t,r]of this.relayFilters)this.pool.getRelay(t,!0,!0,r).subscribe(this,r)}eventReceived(e,t,r=!1,s=!1){var l;const o=e.id,a=this.eventFirstSeen.has(o);let c;if(e instanceof NDKEvent&&(c=e),a){const f=Date.now()-(this.eventFirstSeen.get(o)||0);if(this.emit("event:dup",e,t,f,this,r,s),t){const h=verifiedSignatures.get(o);if(h&&typeof h=="string")if(e.sig===h)t.addValidatedEvent();else{const u=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e);this.ndk.reportInvalidSignature(u,t)}}}else{if(c??(c=new NDKEvent(this.ndk,e)),c.ndk=this.ndk,c.relay=t,!r&&!s){if(!this.skipValidation&&!c.isValid){this.debug("Event failed validation %s from relay %s",o,t==null?void 0:t.url);return}if(t)if(t.shouldValidateEvent()&&!this.skipVerification){if(c.relay=t,!this.ndk.asyncSigVerification){if(!c.verifySignature(!0)){this.debug("Event failed signature validation",e),this.ndk.reportInvalidSignature(c,t);return}t.addValidatedEvent()}}else t.addNonValidatedEvent();this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(c,this.filters,t)}(!s||this.skipOptimisticPublishEvent!==!0)&&(this.emitEvent(((l=this.opts)==null?void 0:l.wrap)??!1,c,t,r,s),this.eventFirstSeen.set(o,Date.now()))}this.lastEventReceivedAt=Date.now()}emitEvent(e,t,r,s,o){const a=e?wrapEvent(t):t;a instanceof Promise?a.then(c=>this.emitEvent(!1,c,r,s,o)):a&&this.emit("event",a,r,this,s,o)}closedReceived(e,t){this.emit("closed",e,t)}eoseReceived(e){var a;this.debug("EOSE received from %s",e.url),this.eosesSeen.add(e);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const r=this.eosesSeen.size===((a=this.relayFilters)==null?void 0:a.size),s=queryFullyFilled(this),o=c=>{var l;this.debug("Performing EOSE: %s %d",c,this.eosed),!this.eosed&&(this.eoseTimeout&&clearTimeout(this.eoseTimeout),this.emit("eose",this),this.eosed=!0,(l=this.opts)!=null&&l.closeOnEose&&this.stop())};if(s||r)o("query filled or seen all");else if(this.relayFilters){let c=1e3;const l=new Set(this.pool.connectedRelays().map(u=>u.url)),f=Array.from(this.relayFilters.keys()).filter(u=>l.has(u));if(f.length===0){this.debug("No connected relays, waiting for all relays to connect",Array.from(this.relayFilters.keys()).join(", "));return}const h=this.eosesSeen.size/f.length;if(this.debug("Percentage of relays that have sent EOSE",{subId:this.subId,percentageOfRelaysThatHaveSentEose:h,seen:this.eosesSeen.size,total:f.length}),this.eosesSeen.size>=2&&h>=.5){if(c=c*(1-h),c===0){o("time to wait was 0");return}this.eoseTimeout&&clearTimeout(this.eoseTimeout);const u=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,t!==void 0&&t<20?this.eoseTimeout=setTimeout(u,c):o(`send eose timeout: ${c}`)};this.eoseTimeout=setTimeout(u,c)}}}},kindIsEphemeral=n=>n>=2e4&&n<3e4;async function follows(n,e,t=3){var s,o;if(!this.ndk)throw new Error("NDK not set");const r=await this.ndk.fetchEvent({kinds:[t],authors:[this.pubkey]},n||{groupable:!1});if(r){const a=new Set;return r.tags.forEach(c=>{c[0]==="p"&&a.add(c[1])}),e&&((o=(s=this.ndk)==null?void 0:s.outboxTracker)==null||o.trackUsers(Array.from(a))),[...a].reduce((c,l)=>{const f=new NDKUser({pubkey:l});return f.ndk=this.ndk,c.add(f),c},new Set)}return new Set}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(n,e,t=fetch,r={}){return await n.queuesNip05.add({id:e,func:async()=>{var l,f,h;if((l=n.cacheAdapter)!=null&&l.loadNip05){const u=await n.cacheAdapter.loadNip05(e);if(u!=="missing"){if(u){const p=new NDKUser({pubkey:u.pubkey,relayUrls:u.relays,nip46Urls:u.nip46});return p.ndk=n,p}if(r.cache!=="no-cache")return null}}const s=e.match(NIP05_REGEX);if(!s)return null;const[o,a="_",c]=s;try{const u=await t(`https://${c}/.well-known/nostr.json?name=${a}`,r),{names:p,relays:y,nip46:b}=parseNIP05Result(await u.json()),m=p[a.toLowerCase()];let k=null;return m&&(k={pubkey:m,relays:y==null?void 0:y[m],nip46:b==null?void 0:b[m]}),(f=n==null?void 0:n.cacheAdapter)!=null&&f.saveNip05&&n.cacheAdapter.saveNip05(e,k),k}catch(u){return(h=n==null?void 0:n.cacheAdapter)!=null&&h.saveNip05&&(n==null||n.cacheAdapter.saveNip05(e,null)),console.error("Failed to fetch NIP05 for",e,u),null}}})}function parseNIP05Result(n){const e={names:{}};for(const[t,r]of Object.entries(n.names))typeof t=="string"&&typeof r=="string"&&(e.names[t.toLowerCase()]=r);if(n.relays){e.relays={};for(const[t,r]of Object.entries(n.relays))typeof t=="string"&&Array.isArray(r)&&(e.relays[t]=r.filter(s=>typeof s=="string"))}if(n.nip46){e.nip46={};for(const[t,r]of Object.entries(n.nip46))typeof t=="string"&&Array.isArray(r)&&(e.nip46[t]=r.filter(s=>typeof s=="string"))}return e}function profileFromEvent(n){const e={};let t;try{t=JSON.parse(n.content)}catch(r){throw new Error(`Failed to parse profile event: ${r}`)}e.profileEvent=JSON.stringify(n.rawEvent());for(const r of Object.keys(t))switch(r){case"name":e.name=t.name;break;case"display_name":e.displayName=t.display_name;break;case"image":case"picture":e.picture=t.picture||t.image,e.image=e.picture;break;case"banner":e.banner=t.banner;break;case"bio":e.bio=t.bio;break;case"nip05":e.nip05=t.nip05;break;case"lud06":e.lud06=t.lud06;break;case"lud16":e.lud16=t.lud16;break;case"about":e.about=t.about;break;case"website":e.website=t.website;break;default:e[r]=t[r];break}return e.created_at=n.created_at,e}function serializeProfile(n){const e={};for(const[t,r]of Object.entries(n))switch(t){case"username":case"name":e.name=r;break;case"displayName":e.display_name=r;break;case"image":case"picture":e.picture=r;break;case"bio":case"about":e.about=r;break;default:e[t]=r;break}return JSON.stringify(e)}var NDKUser=class Be{constructor(e){g(this,"ndk");g(this,"profile");g(this,"profileEvent");g(this,"_npub");g(this,"_pubkey");g(this,"relayUrls",[]);g(this,"nip46Urls",[]);g(this,"follows",follows.bind(this));if(e.npub&&(this._npub=e.npub),e.hexpubkey&&(this._pubkey=e.hexpubkey),e.pubkey&&(this._pubkey=e.pubkey),e.relayUrls&&(this.relayUrls=e.relayUrls),e.nip46Urls&&(this.nip46Urls=e.nip46Urls),e.nprofile)try{const t=nip19_exports.decode(e.nprofile);t.type==="nprofile"&&(this._pubkey=t.data.pubkey,t.data.relays&&t.data.relays.length>0&&this.relayUrls.push(...t.data.relays))}catch(t){console.error("Failed to decode nprofile",t)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nip19_exports.npubEncode(this.pubkey)}return this._npub}get nprofile(){var t,r;const e=(r=(t=this.profileEvent)==null?void 0:t.onRelays)==null?void 0:r.map(s=>s.url);return nip19_exports.nprofileEncode({pubkey:this.pubkey,relays:e})}set npub(e){this._npub=e}get pubkey(){if(!this._pubkey){if(!this._npub)throw new Error("npub not set");this._pubkey=nip19_exports.decode(this.npub).data}return this._pubkey}set pubkey(e){this._pubkey=e}filter(){return{"#p":[this.pubkey]}}async getZapInfo(e){if(!this.ndk)throw new Error("No NDK instance found");const t=async a=>{if(!e)return a;let c;const l=new Promise((f,h)=>{c=setTimeout(()=>h(new Error("Timeout")),e)});try{const f=await Promise.race([a,l]);return c&&clearTimeout(c),f}catch(f){if(f instanceof Error&&f.message==="Timeout")try{return await a}catch{return}return}},[r,s]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),o=new Map;if(s){const a=NDKCashuMintList.from(s);a.mints.length>0&&o.set("nip61",{mints:a.mints,relays:a.relays,p2pk:a.p2pk})}if(r){const{lud06:a,lud16:c}=r;o.set("nip57",{lud06:a,lud16:c})}return o}static async fromNip05(e,t,r=!1){if(!t)throw new Error("No NDK instance found");const s={};r&&(s.cache="no-cache");const o=await getNip05For(t,e,t==null?void 0:t.httpFetch,s);if(o){const a=new Be({pubkey:o.pubkey,relayUrls:o.relays,nip46Urls:o.nip46});return a.ndk=t,a}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let r=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&(e==null?void 0:e.cacheUsage)!=="ONLY_RELAY"){let s=null;if(this.ndk.cacheAdapter.fetchProfileSync?s=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(s=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),s)return this.profile=s,s}return e??(e={}),e.cacheUsage??(e.cacheUsage="ONLY_RELAY"),e.closeOnEose??(e.closeOnEose=!0),e.groupable??(e.groupable=!0),e.groupableDelay??(e.groupableDelay=250),r||(r=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),r?(this.profile=profileFromEvent(r),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}async followSet(e,t,r=3){const s=await this.follows(e,t,r);return new Set(Array.from(s).map(o=>o.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e&&t[0].push("",e),t}async publish(){if(!this.ndk)throw new Error("No NDK instance found");if(!this.profile)throw new Error("No profile available");this.ndk.assertSigner(),await new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)}).publish()}async follow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r)),t.has(e))return!1;t.add(e);const s=new NDKEvent(this.ndk,{kind:r});for(const o of t)s.tag(o);return await s.publish(),!0}async unfollow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r));const s=new Set;let o=!1;for(const c of t)c.pubkey!==e.pubkey?s.add(c):o=!0;if(!o)return!1;const a=new NDKEvent(this.ndk,{kind:r});for(const c of s)a.tag(c);return await a.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return t===null?null:t.pubkey===this.pubkey}};async function pinEvent(n,e,t,r){if(!n.ndk)throw new Error("No NDK instance found");if(n.ndk.assertSigner(),!t){const o=await n.ndk.fetchEvents({kinds:[10001],authors:[n.pubkey]},{cacheUsage:"ONLY_RELAY"});o.size>0?t=lists_default.from(Array.from(o)[0]):t=new NDKEvent(n.ndk,{kind:10001})}return t.tag(e),r&&await t.publish(),t}var NDKClassified=class Pe extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=30402)}static from(e){return new Pe(e.ndk,e)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get summary(){return this.tagValue("summary")}set summary(e){this.removeTag("summary"),e&&this.tags.push(["summary",e])}get published_at(){const e=this.tagValue("published_at");if(e)return Number.parseInt(e)}set published_at(e){this.removeTag("published_at"),e!==void 0&&this.tags.push(["published_at",e.toString()])}get location(){return this.tagValue("location")}set location(e){this.removeTag("location"),e&&this.tags.push(["location",e])}get price(){const e=this.tags.find(t=>t[0]==="price");if(e)return{amount:Number.parseFloat(e[1]),currency:e[2],frequency:e[3]}}set price(e){if(typeof e=="string"&&(e={amount:Number.parseFloat(e)}),e!=null&&e.amount){const t=["price",e.amount.toString()];e.currency&&t.push(e.currency),e.frequency&&t.push(e.frequency),this.tags.push(t)}else this.removeTag("price")}async generateTags(){return super.generateTags(),this.published_at||(this.published_at=this.created_at),super.generateTags()}},NDKDvmJobFeedbackStatus=(n=>(n.Processing="processing",n.Success="success",n.Scheduled="scheduled",n.PayReq="payment_required",n))(NDKDvmJobFeedbackStatus||{}),NDKDVMJobFeedback=class Le extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=7e3)}static async from(e){const t=new Le(e.ndk,e.rawEvent());return t.encrypted&&await t.dvmDecrypt(),t}get status(){return this.tagValue("status")}set status(e){this.removeTag("status"),e!==void 0&&this.tags.push(["status",e])}get encrypted(){return!!this.getMatchingTags("encrypted")[0]}async dvmDecrypt(){await this.decrypt();const e=JSON.parse(this.content);this.tags.push(...e)}},NDKDVMRequest=class Ue extends NDKEvent{static from(e){return new Ue(e.ndk,e.rawEvent())}set bid(e){e===void 0?this.removeTag("bid"):this.tags.push(["bid",e.toString()])}get bid(){const e=this.tagValue("bid");if(e!==void 0)return Number.parseInt(e)}addInput(...e){this.tags.push(["i",...e])}addParam(...e){this.tags.push(["param",...e])}set output(e){e===void 0?this.removeTag("output"):(typeof e=="string"&&(e=[e]),this.tags.push(["output",...e]))}get output(){const e=this.getMatchingTags("output")[0];return e?e.slice(1):void 0}get params(){return this.getMatchingTags("param").map(t=>t.slice(1))}getParam(e){const t=this.getMatchingTags("param").find(r=>r[1]===e);return t?t[2]:void 0}createFeedback(e){const t=new NDKDVMJobFeedback(this.ndk);return t.tag(this,"job"),t.status=e,t}async encryption(e,t){const r=["i","param","output","relays","bid"],s=this.tags.filter(o=>r.includes(o[0]));this.tags=this.tags.filter(o=>!r.includes(o[0])),this.content=JSON.stringify(s),this.tag(e),this.tags.push(["encrypted"]),await this.encrypt(e,t)}set dvm(e){this.removeTag("p"),e&&this.tag(e)}},NDKTranscriptionDVM=class Me extends NDKDVMRequest{constructor(e,t){super(e,t),this.kind=5e3}static from(e){return new Me(e.ndk,e.rawEvent())}get url(){const e=this.getMatchingTags("i");if(e.length===1)return e[0][1]}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}},NDKDVMJobResult=class De extends NDKEvent{static from(e){return new De(e.ndk,e.rawEvent())}setAmount(e,t){this.removeTag("amount");const r=["amount",e.toString()];t&&r.push(t),this.tags.push(r)}set result(e){e===void 0?this.content="":this.content=e}get result(){if(this.content!=="")return this.content}set status(e){this.removeTag("status"),e!==void 0&&this.tags.push(["status",e])}get status(){return this.tagValue("status")}get jobRequestId(){for(const e of this.getMatchingTags("e"))if(e[2]==="job")return e[1];return this.jobRequest?this.jobRequest.id:this.tagValue("e")}set jobRequest(e){this.removeTag("request"),e&&(this.kind=e.kind+1e3,this.tags.push(["request",JSON.stringify(e.rawEvent())]),this.tag(e))}get jobRequest(){const e=this.tagValue("request");if(e!==void 0)return new NDKEvent(this.ndk,JSON.parse(e))}},MARKERS={REDEEMED:"redeemed",CREATED:"created",DESTROYED:"destroyed",RESERVED:"reserved"},ne,NDKCashuWalletTx=(ne=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=7376)}static async from(e){const t=new ne(e.ndk,e),r=t.content;try{await t.decrypt()}catch{t.content??(t.content=r)}try{const s=JSON.parse(t.content);t.tags=[...s,...t.tags]}catch{return}return t}set direction(e){this.removeTag("direction"),e&&this.tags.push(["direction",e])}get direction(){return this.tagValue("direction")}set amount(e){this.removeTag("amount"),this.tags.push(["amount",e.toString()])}get amount(){const e=this.tagValue("amount");if(e!==void 0)return Number(e)}set fee(e){this.removeTag("fee"),this.tags.push(["fee",e.toString()])}get fee(){const e=this.tagValue("fee");if(e!==void 0)return Number(e)}set unit(e){this.removeTag("unit"),e&&this.tags.push(["unit",e.toString()])}get unit(){return this.tagValue("unit")}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e.toString()])}get description(){return this.tagValue("description")}set mint(e){this.removeTag("mint"),e&&this.tags.push(["mint",e.toString()])}get mint(){return this.tagValue("mint")}set destroyedTokens(e){for(const t of e)this.tags.push(t.tagReference(MARKERS.DESTROYED))}set destroyedTokenIds(e){for(const t of e)this.tags.push(["e",t,"",MARKERS.DESTROYED])}set createdTokens(e){for(const t of e)this.tags.push(t.tagReference(MARKERS.CREATED))}set reservedTokens(e){for(const t of e)this.tags.push(t.tagReference(MARKERS.RESERVED))}addRedeemedNutzap(e){this.tag(e,MARKERS.REDEEMED)}async toNostrEvent(e){var o,a;const t=[],r=[];for(const c of this.tags)this.shouldEncryptTag(c)?t.push(c):r.push(c);this.tags=r.filter(c=>c[0]!=="client"),this.content=JSON.stringify(t);const s=await((a=(o=this.ndk)==null?void 0:o.signer)==null?void 0:a.user());if(s){const c=s.pubkey;this.tags=this.tags.filter(l=>l[0]!=="p"||l[1]!==c)}return await this.encrypt(s,void 0,"nip44"),super.toNostrEvent(e)}get hasNutzapRedemption(){return this.getMatchingTags("e",MARKERS.REDEEMED).length>0}shouldEncryptTag(e){return!(["client"].includes(e[0])||e[0]==="e"&&e[3]===MARKERS.REDEEMED||e[0]==="p")}},g(ne,"MARKERS",MARKERS),g(ne,"kind",7376),g(ne,"kinds",[7376]),ne),READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class Fe extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=10002)}static from(e){return new Fe(e.ndk,e.rawEvent())}get readRelayUrls(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").filter(e=>!e[2]||e[2]&&e[2]===READ_MARKER).map(e=>tryNormalizeRelayUrl(e[1])).filter(e=>!!e)}set readRelayUrls(e){for(const t of e)this.tags.push(["r",t,READ_MARKER])}get writeRelayUrls(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").filter(e=>!e[2]||e[2]&&e[2]===WRITE_MARKER).map(e=>tryNormalizeRelayUrl(e[1])).filter(e=>!!e)}set writeRelayUrls(e){for(const t of e)this.tags.push(["r",t,WRITE_MARKER])}get bothRelayUrls(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").filter(e=>!e[2]).map(e=>e[1])}set bothRelayUrls(e){for(const t of e)this.tags.push(["r",t])}get relays(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").map(e=>e[1])}get relaySet(){if(!this.ndk)throw new Error("NDKRelayList has no NDK instance");return new NDKRelaySet(new Set(this.relays.map(e=>{var t;return(t=this.ndk)==null?void 0:t.pool.getRelay(e)}).filter(e=>!!e)),this.ndk)}};function relayListFromKind3(n,e){try{const t=JSON.parse(e.content),r=new NDKRelayList(n),s=new Set,o=new Set;for(let[a,c]of Object.entries(t)){try{a=normalizeRelayUrl(a)}catch{continue}if(!c)s.add(a),o.add(a);else{const l=c;l.write&&o.add(a),l.read&&s.add(a)}}return r.readRelayUrls=Array.from(s),r.writeRelayUrls=Array.from(o),r}catch{}}var NDKAppHandlerEvent=class Oe extends NDKEvent{constructor(t,r){super(t,r);g(this,"profile");this.kind??(this.kind=31990)}static from(t){const r=new Oe(t.ndk,t.rawEvent());return r.isValid?r:null}get isValid(){const t=new Map,r=o=>[o[0],o[2]].join(":").toLowerCase(),s=["web","android","ios"];for(const o of this.tags)if(s.includes(o[0])){const a=r(o);if(t.has(a)&&t.get(a)!==o[1].toLowerCase())return!1;t.set(a,o[1].toLowerCase())}return!0}async fetchProfile(){if(this.profile===void 0&&this.content.length>0)try{const t=JSON.parse(this.content);if(t!=null&&t.name)return t;this.profile=null}catch{this.profile=null}return new Promise((t,r)=>{const s=this.author;s.fetchProfile().then(()=>{t(s.profile)}).catch(r)})}},NDKRepost=class He extends NDKEvent{constructor(){super(...arguments);g(this,"_repostedEvents")}static from(t){return new He(t.ndk,t.rawEvent())}async repostedEvents(t,r){const s=[];if(!this.ndk)throw new Error("NDK instance not set");if(this._repostedEvents!==void 0)return this._repostedEvents;for(const o of this.repostedEventIds()){const a=filterForId(o),c=await this.ndk.fetchEvent(a,r);c&&s.push(t?t.from(c):c)}return s}repostedEventIds(){return this.tags.filter(t=>t[0]==="e"||t[0]==="a").map(t=>t[1])}};function filterForId(n){if(n.match(/:/)){const[e,t,r]=n.split(":");return{kinds:[Number.parseInt(e)],authors:[t],"#d":[r]}}return{ids:[n]}}var NDKSubscriptionReceipt=class Ve extends NDKEvent{constructor(t,r){super(t,r);g(this,"debug");this.kind??(this.kind=7003),this.debug=(t==null?void 0:t.debug.extend("subscription-start"))??createDebug2("ndk:subscription-start")}static from(t){return new Ve(t.ndk,t.rawEvent())}get recipient(){var s;const t=(s=this.getMatchingTags("p"))==null?void 0:s[0];return t?new NDKUser({pubkey:t[1]}):void 0}set recipient(t){this.removeTag("p"),t&&this.tags.push(["p",t.pubkey])}get subscriber(){var s;const t=(s=this.getMatchingTags("P"))==null?void 0:s[0];return t?new NDKUser({pubkey:t[1]}):void 0}set subscriber(t){this.removeTag("P"),t&&this.tags.push(["P",t.pubkey])}set subscriptionStart(t){this.debug(`before setting subscription start: ${this.rawEvent}`),this.removeTag("e"),this.tag(t,"subscription",!0),this.debug(`after setting subscription start: ${this.rawEvent}`)}get tierName(){var r;const t=(r=this.getMatchingTags("tier"))==null?void 0:r[0];return t==null?void 0:t[1]}get isValid(){const t=this.validPeriod;if(!t||t.start>t.end)return!1;const r=this.getMatchingTags("p"),s=this.getMatchingTags("P");return!(r.length!==1||s.length!==1)}get validPeriod(){var r;const t=(r=this.getMatchingTags("valid"))==null?void 0:r[0];if(t)try{return{start:new Date(Number.parseInt(t[1])*1e3),end:new Date(Number.parseInt(t[2])*1e3)}}catch{return}}set validPeriod(t){this.removeTag("valid"),t&&this.tags.push(["valid",Math.floor(t.start.getTime()/1e3).toString(),Math.floor(t.end.getTime()/1e3).toString()])}get startPeriod(){var t;return(t=this.validPeriod)==null?void 0:t.start}get endPeriod(){var t;return(t=this.validPeriod)==null?void 0:t.end}isActive(t){t??(t=new Date);const r=this.validPeriod;return!(!r||t<r.start||t>r.end)}},NDKSubscriptionStart=class ze extends NDKEvent{constructor(t,r){super(t,r);g(this,"debug");this.kind??(this.kind=7001),this.debug=(t==null?void 0:t.debug.extend("subscription-start"))??createDebug2("ndk:subscription-start")}static from(t){return new ze(t.ndk,t.rawEvent())}get recipient(){var s;const t=(s=this.getMatchingTags("p"))==null?void 0:s[0];return t?new NDKUser({pubkey:t[1]}):void 0}set recipient(t){this.removeTag("p"),t&&this.tags.push(["p",t.pubkey])}get amount(){var r;const t=(r=this.getMatchingTags("amount"))==null?void 0:r[0];if(t)return parseTagToSubscriptionAmount(t)}set amount(t){this.removeTag("amount"),t&&this.tags.push(newAmount(t.amount,t.currency,t.term))}get tierId(){var s,o;const t=(s=this.getMatchingTags("e"))==null?void 0:s[0],r=(o=this.getMatchingTags("a"))==null?void 0:o[0];if(!(!t||!r))return t[1]??r[1]}set tier(t){this.removeTag("e"),this.removeTag("a"),this.removeTag("event"),t&&(this.tag(t),this.removeTag("p"),this.tags.push(["p",t.pubkey]),this.tags.push(["event",JSON.stringify(t.rawEvent())]))}async fetchTier(){var o;const t=this.tagValue("event");if(t)try{const a=JSON.parse(t);return new NDKSubscriptionTier(this.ndk,a)}catch{this.debug("Failed to parse event tag")}const r=this.tierId;if(!r)return;const s=await((o=this.ndk)==null?void 0:o.fetchEvent(r));if(s)return NDKSubscriptionTier.from(s)}get isValid(){return this.getMatchingTags("amount").length!==1?(this.debug("Invalid # of amount tag"),!1):this.amount?this.getMatchingTags("p").length!==1?(this.debug("Invalid # of p tag"),!1):this.recipient?!0:(this.debug("Invalid p tag"),!1):(this.debug("Invalid amount tag"),!1)}};async function giftWrap(n,e,t,r={}){let s=t;if(r.scheme??(r.scheme="nip44"),!s){if(!n.ndk)throw new Error("no signer available for giftWrap");s=n.ndk.signer}if(!s)throw new Error("no signer");if(!s.encryptionEnabled||!s.encryptionEnabled(r.scheme))throw new Error("signer is not able to giftWrap");const o=getRumorEvent(n,r==null?void 0:r.rumorKind),a=await getSealEvent(o,e,s,r.scheme),c=await getWrapEvent(a,e,r);return new NDKEvent(n.ndk,c)}async function giftUnwrap(n,e,t,r="nip44"){const s=e||new NDKUser({pubkey:n.pubkey});let o=t;if(!o){if(!n.ndk)throw new Error("no signer available for giftUnwrap");o=n.ndk.signer}if(!t)throw new Error("no signer");try{const a=JSON.parse(await t.decrypt(s,n.content,r));if(!a)throw new Error("Failed to decrypt wrapper");if(!new NDKEvent(void 0,a).verifySignature(!1))throw new Error("GiftSeal signature verification failed!");const c=new NDKUser({pubkey:a.pubkey}),l=JSON.parse(await t.decrypt(c,a.content,r));if(!l)throw new Error("Failed to decrypt seal");if(l.pubkey!==a.pubkey)throw new Error("Invalid GiftWrap, sender validation failed!");return new NDKEvent(n.ndk,l)}catch{return Promise.reject("Got error unwrapping event! See console log.")}}function getRumorEvent(n,e){const t=n.rawEvent();return t.kind=e||t.kind||14,t.sig=void 0,t.id=getEventHash$1(t),new NDKEvent(n.ndk,t)}async function getSealEvent(n,e,t,r="nip44"){const s=new NDKEvent(n.ndk);return s.kind=13,s.created_at=approximateNow(5),s.content=JSON.stringify(n.rawEvent()),await s.encrypt(e,t,r),await s.sign(t),s}async function getWrapEvent(n,e,t,r="nip44"){const s=NDKPrivateKeySigner.generate(),o=new NDKEvent(n.ndk);return o.kind=1059,o.created_at=approximateNow(5),t!=null&&t.wrapTags&&(o.tags=t.wrapTags),o.tag(e),o.content=JSON.stringify(n.rawEvent()),await o.encrypt(e,s,r),await o.sign(s),o}function approximateNow(n=0){return Math.round(Date.now()/1e3-Math.random()*10**n)}var NDKSimpleGroup=class qe{constructor(e,t,r){g(this,"ndk");g(this,"groupId");g(this,"relaySet");g(this,"fetchingMetadata");g(this,"metadata");g(this,"memberList");g(this,"adminList");this.ndk=e,this.groupId=r??randomId(24),this.relaySet=t}get id(){return this.groupId}relayUrls(){var e;return(e=this.relaySet)==null?void 0:e.relayUrls}get name(){var e;return(e=this.metadata)==null?void 0:e.name}get about(){var e;return(e=this.metadata)==null?void 0:e.about}get picture(){var e;return(e=this.metadata)==null?void 0:e.picture}get members(){var e;return((e=this.memberList)==null?void 0:e.members)??[]}get admins(){var e;return((e=this.adminList)==null?void 0:e.members)??[]}async getMetadata(){return await this.ensureMetadataEvent(),this.metadata}async createGroup(e){if(e??(e=this.ndk.signer),!e)throw new Error("No signer available");if(!await e.user())throw new Error("No user available");const r=new NDKEvent(this.ndk);return r.kind=9007,r.tags.push(["h",this.groupId]),await r.sign(e),r.publish(this.relaySet)}async setMetadata({name:e,about:t,picture:r}){const s=new NDKEvent(this.ndk);return s.kind=9002,s.tags.push(["h",this.groupId]),e&&s.tags.push(["name",e]),t&&s.tags.push(["about",t]),r&&s.tags.push(["picture",r]),await s.sign(),s.publish(this.relaySet)}async addUser(e){const t=qe.generateAddUserEvent(e.pubkey,this.groupId);return t.ndk=this.ndk,t}async getMemberListEvent(){const e=await this.ndk.fetchEvent({kinds:[39002],"#d":[this.groupId]},void 0,this.relaySet);return e?NDKSimpleGroupMemberList.from(e):null}async getMembers(){const e=[],t=new Set,r=await this.getMemberListEvent();if(!r)return[];for(const s of r.getMatchingTags("p")){const o=s[1];if(!t.has(o)){t.add(o);try{e.push(this.ndk.getUser({pubkey:o}))}catch{}}}return e}static generateUserListEvent(e){return new NDKEvent(void 0,{kind:39002,tags:[["h",e],["alt","Group Member List"]]})}static generateAddUserEvent(e,t){const r=new NDKEvent(void 0,{kind:9e3,tags:[["h",t]]});return r.tags.push(["p",e]),r}async requestToJoin(e,t){return new NDKEvent(this.ndk,{kind:9021,content:t??"",tags:[["h",this.groupId]]}).publish(this.relaySet)}async ensureMetadataEvent(){if(!this.metadata)return this.fetchingMetadata?this.fetchingMetadata:(this.fetchingMetadata=this.ndk.fetchEvent({kinds:[39e3],"#d":[this.groupId]},void 0,this.relaySet).then(e=>{e?this.metadata=NDKSimpleGroupMetadata.from(e):(this.metadata=new NDKSimpleGroupMetadata(this.ndk),this.metadata.dTag=this.groupId)}).finally(()=>{this.fetchingMetadata=void 0}).catch(()=>{throw new Error(`Failed to fetch metadata for group ${this.groupId}`)}),this.fetchingMetadata)}};function randomId(n){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length;let r="";for(let s=0;s<n;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}var NDKAppSettings=class je extends NDKEvent{constructor(t,r){super(t,r);g(this,"appName");g(this,"settings",{});if(this.kind??(this.kind=30078),this.dTag??(this.dTag=this.appName),this.content.length>0)try{this.settings=JSON.parse(this.content)}catch(s){console.error("Error parsing app settings",s)}}static from(t){return new je(t.ndk,t)}set(t,r){this.settings[t]=r}get(t){return this.settings[t]}async publishReplaceable(t,r,s){return this.content=JSON.stringify(this.settings),super.publishReplaceable(t,r,s)}};function disconnect(n,e){return e??(e=createDebug2("ndk:relay:auth-policies:disconnect")),async t=>{e==null||e(`Relay ${t.url} requested authentication, disconnecting`),n.removeRelay(t.url)}}async function signAndAuth(n,e,t,r,s,o){try{await n.sign(t),s(n)}catch(a){r==null||r(`Failed to publish auth event to relay ${e.url}`,a),o(n)}}function signIn({ndk:n,signer:e,debug:t}={}){return t??(t=createDebug2("ndk:auth-policies:signIn")),async(r,s)=>{t==null||t(`Relay ${r.url} requested authentication, signing in`);const o=new NDKEvent(n);return o.kind=22242,o.tags=[["relay",r.url],["challenge",s]],e??(e=n==null?void 0:n.signer),new Promise(async(a,c)=>{e?await signAndAuth(o,r,e,t,a,c):n==null||n.once("signer:ready",async l=>{await signAndAuth(o,r,l,t,a,c)})})}}var NDKRelayAuthPolicies={disconnect,signIn},NDKNip07Signer=class We{constructor(e=1e3,t){g(this,"_userPromise");g(this,"encryptionQueue",[]);g(this,"encryptionProcessing",!1);g(this,"debug");g(this,"waitTimeout");g(this,"_pubkey");g(this,"ndk");g(this,"_user");this.debug=createDebug2("ndk:nip07"),this.waitTimeout=e,this.ndk=t}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}async blockUntilReady(){var r;await this.waitForExtension();const e=await((r=window.nostr)==null?void 0:r.getPublicKey());if(!e)throw new Error("User rejected access");this._pubkey=e;let t;return this.ndk?t=this.ndk.getUser({pubkey:e}):t=new NDKUser({pubkey:e}),this._user=t,t}async user(){return this._userPromise||(this._userPromise=this.blockUntilReady()),this._userPromise}get userSync(){if(!this._user)throw new Error("User not ready");return this._user}async sign(e){var r;await this.waitForExtension();const t=await((r=window.nostr)==null?void 0:r.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){var s,o;await this.waitForExtension();const t=await((o=(s=window.nostr)==null?void 0:s.getRelays)==null?void 0:o.call(s))||{},r=[];for(const a of Object.keys(t))t[a].read&&t[a].write&&r.push(a);return r.map(a=>new NDKRelay(a,e==null?void 0:e.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){var r,s;const t=[];return(!e||e==="nip04")&&((r=window.nostr)!=null&&r.nip04)&&t.push("nip04"),(!e||e==="nip44")&&((s=window.nostr)!=null&&s.nip44)&&t.push("nip44"),t}async encrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"encrypt",s,t)}async decrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"decrypt",s,t)}async queueEncryption(e,t,r,s){return new Promise((o,a)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:r,value:s,resolve:o,reject:a}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){var h,u;if(!e&&this.encryptionQueue.length===0){this.encryptionProcessing=!1;return}this.encryptionProcessing=!0;const r=e||this.encryptionQueue.shift();if(!r){this.encryptionProcessing=!1;return}const{scheme:s,method:o,counterpartyHexpubkey:a,value:c,resolve:l,reject:f}=r;this.debug("Processing encryption queue item",{method:o,counterpartyHexpubkey:a,value:c});try{const p=await((u=(h=window.nostr)==null?void 0:h[s])==null?void 0:u[o](a,c));if(!p)throw new Error("Failed to encrypt/decrypt");l(p)}catch(p){const y=p instanceof Error?p.message:String(p);if(y.includes("call already executing")&&t<5){this.debug("Retrying encryption queue item",{method:o,counterpartyHexpubkey:a,value:c,retries:t}),setTimeout(()=>{this.processEncryptionQueue(r,t+1)},50*t);return}f(p instanceof Error?p:new Error(y))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr){e();return}let r;const s=setInterval(()=>{window.nostr&&(clearTimeout(r),clearInterval(s),e())},100);r=setTimeout(()=>{clearInterval(s),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(e,t){const r=JSON.parse(e);if(r.type!=="nip07")throw new Error(`Invalid payload type: expected 'nip07', got ${r.type}`);return new We(void 0,t)}};registerSigner("nip07",NDKNip07Signer);var NDKNostrRpc=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"ndk");g(this,"signer");g(this,"relaySet");g(this,"debug");g(this,"encryptionType","nip04");g(this,"pool");if(this.ndk=e,this.signer=t,s){this.pool=new NDKPool(s,[],e,{debug:r.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new NDKRelaySet(new Set,e,this.pool);for(const o of s){const a=this.pool.getRelay(o,!1,!1);a.authPolicy=NDKRelayAuthPolicies.signIn({ndk:e,signer:t,debug:r}),this.relaySet.addRelay(a),a.connect()}}this.debug=r.extend("rpc")}subscribe(e){const t=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1,cacheUsage:"ONLY_RELAY",pool:this.pool,relaySet:this.relaySet},!1);return t.on("event",async r=>{try{const s=await this.parseEvent(r);s.method?this.emit("request",s):(this.emit(`response-${s.id}`,s),this.emit("response",s))}catch(s){this.debug("error parsing event",s,r.rawEvent())}}),new Promise(r=>{t.on("eose",()=>{this.debug("eosed"),r(t)}),t.start()})}async parseEvent(e){this.encryptionType==="nip44"&&e.content.includes("?iv=")?this.encryptionType="nip04":this.encryptionType==="nip04"&&!e.content.includes("?iv=")&&(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});t.ndk=this.ndk;let r;try{r=await this.signer.decrypt(t,e.content,this.encryptionType)}catch{const u=this.encryptionType==="nip04"?"nip44":"nip04";r=await this.signer.decrypt(t,e.content,u),this.encryptionType=u}const s=JSON.parse(r),{id:o,method:a,params:c,result:l,error:f}=s;return a?{id:o,pubkey:e.pubkey,method:a,params:c,event:e}:{id:o,result:l,error:f,event:e}}async sendResponse(e,t,r,s=24133,o){const a={id:e,result:r};o&&(a.error=o);const c=await this.signer.user(),l=this.ndk.getUser({pubkey:t}),f=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(a),tags:[["p",t]],pubkey:c.pubkey});f.content=await this.signer.encrypt(l,f.content,this.encryptionType),await f.sign(this.signer),await f.publish(this.relaySet)}async sendRequest(e,t,r=[],s=24133,o){const a=Math.random().toString(36).substring(7),c=await this.signer.user(),l=this.ndk.getUser({pubkey:e}),f={id:a,method:t,params:r},h=new Promise(()=>{const p=y=>{y.result==="auth_url"?(this.once(`response-${a}`,p),this.emit("authUrl",y.error)):o&&o(y)};this.once(`response-${a}`,p)}),u=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(f),tags:[["p",e]],pubkey:c.pubkey});return u.content=await this.signer.encrypt(l,u.content,this.encryptionType),await u.sign(this.signer),await u.publish(this.relaySet),h}},ConnectEventHandlingStrategy=class{async handle(n,e,t,r){const[s,o]=r,a=n.debug.extend("connect");if(a(`connection request from ${t}`),o&&n.applyToken&&(a("applying token"),await n.applyToken(t,o)),await n.pubkeyAllowed({id:e,pubkey:t,method:"connect",params:o}))return a(`connection request from ${t} allowed`),"ack";a(`connection request from ${t} rejected`)}},GetPublicKeyHandlingStrategy=class{async handle(n,e,t,r){var s;return(s=n.localUser)==null?void 0:s.pubkey}},Nip04DecryptHandlingStrategy=class{async handle(n,e,t,r){const[s,o]=r,a=new NDKUser({pubkey:s});return await decrypt2(n,e,t,a,o)}};async function decrypt2(n,e,t,r,s){if(!await n.pubkeyAllowed({id:e,pubkey:t,method:"nip04_decrypt",params:s})){n.debug(`decrypt request from ${t} rejected`);return}return await n.signer.decrypt(r,s,"nip04")}var Nip04EncryptHandlingStrategy=class{async handle(n,e,t,r){const[s,o]=r,a=new NDKUser({pubkey:s});return await encrypt2(n,e,t,a,o)}};async function encrypt2(n,e,t,r,s){if(!await n.pubkeyAllowed({id:e,pubkey:t,method:"nip04_encrypt",params:s})){n.debug(`encrypt request from ${t} rejected`);return}return await n.signer.encrypt(r,s,"nip04")}var Nip04DecryptHandlingStrategy2=class{async handle(n,e,t,r){const[s,o]=r,a=new NDKUser({pubkey:s});return await decrypt3(n,e,t,a,o)}};async function decrypt3(n,e,t,r,s){if(!await n.pubkeyAllowed({id:e,pubkey:t,method:"nip44_decrypt",params:s})){n.debug(`decrypt request from ${t} rejected`);return}return await n.signer.decrypt(r,s,"nip44")}var Nip04EncryptHandlingStrategy2=class{async handle(n,e,t,r){const[s,o]=r,a=new NDKUser({pubkey:s});return await encrypt3(n,e,t,a,o)}};async function encrypt3(n,e,t,r,s){if(!await n.pubkeyAllowed({id:e,pubkey:t,method:"nip44_encrypt",params:s})){n.debug(`encrypt request from ${t} rejected`);return}return await n.signer.encrypt(r,s,"nip44")}var PingEventHandlingStrategy=class{async handle(n,e,t,r){const s=n.debug.extend("ping");if(s(`ping request from ${t}`),await n.pubkeyAllowed({id:e,pubkey:t,method:"ping"}))return s(`connection request from ${t} allowed`),"pong";s(`connection request from ${t} rejected`)}},SignEventHandlingStrategy=class{async handle(n,e,t,r){const s=await signEvent(n,e,t,r);if(s)return JSON.stringify(await s.toNostrEvent())}};async function signEvent(n,e,t,r){const[s]=r;n.debug(`sign event request from ${t}`);const o=new NDKEvent(n.ndk,JSON.parse(s));if(n.debug("event to sign",o.rawEvent()),!await n.pubkeyAllowed({id:e,pubkey:t,method:"sign_event",params:o})){n.debug(`sign event request from ${t} rejected`);return}return n.debug(`sign event request from ${t} allowed`),await o.sign(n.signer),o}var NDKNip46Backend=class{constructor(n,e,t,r){g(this,"ndk");g(this,"signer");g(this,"localUser");g(this,"debug");g(this,"rpc");g(this,"permitCallback");g(this,"relayUrls");g(this,"handlers",{connect:new ConnectEventHandlingStrategy,sign_event:new SignEventHandlingStrategy,nip04_encrypt:new Nip04EncryptHandlingStrategy,nip04_decrypt:new Nip04DecryptHandlingStrategy,nip44_encrypt:new Nip04EncryptHandlingStrategy2,nip44_decrypt:new Nip04DecryptHandlingStrategy2,get_public_key:new GetPublicKeyHandlingStrategy,ping:new PingEventHandlingStrategy});if(this.ndk=n,e instanceof Uint8Array)this.signer=new NDKPrivateKeySigner(e);else if(e instanceof String)this.signer=new NDKPrivateKeySigner(hexToBytes(e));else if(e instanceof NDKPrivateKeySigner)this.signer=e;else throw new Error("Invalid signer");this.debug=n.debug.extend("nip46:backend"),this.relayUrls=r??Array.from(n.pool.relays.keys()),this.rpc=new NDKNostrRpc(n,this.signer,this.debug,this.relayUrls),this.permitCallback=t}async start(){this.localUser=await this.signer.user(),this.ndk.subscribe({kinds:[24133],"#p":[this.localUser.pubkey]},{closeOnEose:!1}).on("event",e=>this.handleIncomingEvent(e))}setStrategy(n,e){this.handlers[n]=e}async applyToken(n,e){throw new Error("connection token not supported")}async handleIncomingEvent(n){const{id:e,method:t,params:r}=await this.rpc.parseEvent(n),s=n.pubkey;let o;if(this.debug("incoming event",{id:e,method:t,params:r}),!n.verifySignature(!1)){this.debug("invalid signature",n.rawEvent());return}const a=this.handlers[t];if(a)try{o=await a.handle(this,e,s,r)}catch(c){this.debug("error handling event",c,{id:e,method:t,params:r}),this.rpc.sendResponse(e,s,"error",void 0,c.message)}else this.debug("unsupported method",{method:t,params:r});o?(this.debug(`sending response to ${s}`,o),this.rpc.sendResponse(e,s,o)):this.rpc.sendResponse(e,s,"error",void 0,"Not authorized")}async pubkeyAllowed(n){return this.permitCallback(n)}};async function ndkSignerFromPayload(n,e){let t;try{t=JSON.parse(n)}catch(s){console.error("Failed to parse signer payload string",n,s);return}if(!t||typeof t.type!="string"){console.error("Failed to parse signer payload string",n,new Error("Missing type field"));return}const r=signerRegistry.get(t.type);if(!r)throw new Error(`Unknown signer type: ${t.type}`);try{return await r.fromPayload(n,e)}catch(s){const o=s instanceof Error?s.message:String(s);throw new Error(`Failed to deserialize signer type ${t.type}: ${o}`)}}function nostrConnectGenerateSecret(){return Math.random().toString(36).substring(2,15)}function generateNostrConnectUri(n,e,t,r){const s={name:r!=null&&r.name?encodeURIComponent(r.name):"",url:r!=null&&r.url?encodeURIComponent(r.url):"",image:r!=null&&r.image?encodeURIComponent(r.image):"",perms:r!=null&&r.perms?encodeURIComponent(r.perms):""};let o=`nostrconnect://${n}?image=${s.image}&url=${s.url}&name=${s.name}&perms=${s.perms}&secret=${encodeURIComponent(e)}`;return t&&(o+=`&relay=${encodeURIComponent(t)}`),o}var NDKNip46Signer=class Ae extends lib$1.EventEmitter{constructor(t,r,s,o,a){super();g(this,"ndk");g(this,"_user");g(this,"bunkerPubkey");g(this,"userPubkey");g(this,"secret");g(this,"localSigner");g(this,"nip05");g(this,"rpc");g(this,"debug");g(this,"relayUrls");g(this,"subscription");g(this,"nostrConnectUri");g(this,"nostrConnectSecret");this.ndk=t,this.debug=t.debug.extend("nip46:signer"),this.relayUrls=o,s?typeof s=="string"?this.localSigner=new NDKPrivateKeySigner(s):this.localSigner=s:this.localSigner=NDKPrivateKeySigner.generate(),r===!1||(r?r.startsWith("bunker://")?this.bunkerFlowInit(r):this.nip05Init(r):this.nostrconnectFlowInit(a)),this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls)}get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}static bunker(t,r,s){return new Ae(t,r,s)}static nostrconnect(t,r,s,o){return new Ae(t,void 0,s,[r],o)}nostrconnectFlowInit(t){var s;this.nostrConnectSecret=nostrConnectGenerateSecret();const r=this.localSigner.pubkey;this.nostrConnectUri=generateNostrConnectUri(r,this.nostrConnectSecret,(s=this.relayUrls)==null?void 0:s[0],t)}bunkerFlowInit(t){const r=new URL(t),s=r.hostname||r.pathname.replace(/^\/\//,""),o=r.searchParams.get("pubkey"),a=r.searchParams.getAll("relay"),c=r.searchParams.get("secret");this.bunkerPubkey=s,this.userPubkey=o,this.relayUrls=a,this.secret=c}nip05Init(t){this.nip05=t}async startListening(){if(this.subscription)return;const t=await this.localSigner.user();if(!t)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[t.pubkey]})}async user(){return this._user?this._user:this.blockUntilReady()}get userSync(){if(!this._user)throw new Error("Remote user not ready synchronously");return this._user}async blockUntilReadyNostrConnect(){return new Promise((t,r)=>{const s=o=>{o.result===this.nostrConnectSecret&&(this._user=o.event.author,this.userPubkey=o.event.pubkey,this.bunkerPubkey=o.event.pubkey,this.rpc.off("response",s),t(this._user))};this.startListening(),this.rpc.on("response",s)})}async blockUntilReady(){if(!this.bunkerPubkey&&!this.nostrConnectSecret&&!this.nip05)throw new Error("Bunker pubkey not set");if(this.nostrConnectSecret)return this.blockUntilReadyNostrConnect();if(this.nip05&&!this.userPubkey){const t=await NDKUser.fromNip05(this.nip05,this.ndk);t&&(this._user=t,this.userPubkey=t.pubkey,this.relayUrls=t.nip46Urls,this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls))}if(!this.bunkerPubkey&&this.userPubkey)this.bunkerPubkey=this.userPubkey;else if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");return await this.startListening(),this.rpc.on("authUrl",(...t)=>{this.emit("authUrl",...t)}),new Promise((t,r)=>{const s=[this.userPubkey??""];if(this.secret&&s.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",s,24133,o=>{o.result==="ack"?this.getPublicKey().then(a=>{this.userPubkey=a,this._user=this.ndk.getUser({pubkey:a}),t(this._user)}):r(o.error)})})}stop(){var t;(t=this.subscription)==null||t.stop(),this.subscription=void 0}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((t,r)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,s=>{t(s.result)})})}async encryptionEnabled(t){return t?[t]:Promise.resolve(["nip04","nip44"])}async encrypt(t,r,s="nip04"){return this.encryption(t,r,s,"encrypt")}async decrypt(t,r,s="nip04"){return this.encryption(t,r,s,"decrypt")}async encryption(t,r,s,o){return new Promise((c,l)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${s}_${o}`,[t.pubkey,r],24133,f=>{f.error?l(f.error):c(f.result)})})}async sign(t){return new Promise((s,o)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(t)],24133,a=>{if(a.error)o(a.error);else{const c=JSON.parse(a.result);s(c.sig)}})})}async createAccount(t,r,s){await this.startListening();const o=[];return t&&o.push(t),r&&o.push(r),s&&o.push(s),new Promise((a,c)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",o,24133,l=>{if(l.error)c(l.error);else{const f=l.result;a(f)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const t={type:"nip46",payload:{bunkerPubkey:this.bunkerPubkey,userPubkey:this.userPubkey,relayUrls:this.relayUrls,secret:this.secret,localSignerPayload:this.localSigner.toPayload(),nip05:this.nip05||null}};return JSON.stringify(t)}static async fromPayload(t,r){if(!r)throw new Error("NDK instance is required to deserialize NIP-46 signer");const s=JSON.parse(t);if(s.type!=="nip46")throw new Error(`Invalid payload type: expected 'nip46', got ${s.type}`);const o=s.payload;if(!o||typeof o!="object"||!o.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const a=await ndkSignerFromPayload(o.localSignerPayload,r);if(!a)throw new Error("Failed to deserialize local signer for NIP-46");if(!(a instanceof NDKPrivateKeySigner))throw new Error("Local signer must be an instance of NDKPrivateKeySigner");let c;return c=new Ae(r,!1,a,o.relayUrls),c.userPubkey=o.userPubkey,c.bunkerPubkey=o.bunkerPubkey,c.relayUrls=o.relayUrls,c.secret=o.secret,o.userPubkey&&(c._user=new NDKUser({pubkey:o.userPubkey}),c._user&&(c._user.ndk=r)),c}};registerSigner("nip46",NDKNip46Signer);function addRelays(n,e){var r;const t=[];if(!e||e.length===0){const s=(r=n.ndk)==null?void 0:r.pool.relays;e=s?Object.keys(s):void 0}return e&&e.length>0&&t.push(["relays",...e]),t}async function dvmSchedule(n,e,t,r=!0,s){Array.isArray(n)||(n=[n]);const o=n[0].ndk;if(!o)throw new Error("NDK not set");for(const h of n){if(!h.sig)throw new Error("Event not signed");if(!h.created_at)throw new Error("Event has no date");if(!e)throw new Error("No DVM specified");if(h.created_at<=Date.now()/1e3)throw new Error("Event needs to be in the future")}const a=new NDKDVMRequest(o,{kind:5905});for(const h of n)a.addInput(JSON.stringify(h.rawEvent()),"text");a.tags.push(...addRelays(n[0],t)),r?await a.encryption(e):a.dvm=e,await a.sign();let c;s&&(c=o.subscribe({kinds:[5905+1e3,7e3],...a.filter()},{groupable:!1,closeOnEose:!1}));const l=new Promise(h=>{setTimeout(()=>{c==null||c.stop(),h("Timeout waiting for an answer from the DVM")},s)}),f=new Promise((h,u)=>{s&&(c==null||c.on("event",async p=>{if(c==null||c.stop(),p.kind===7e3){const y=await NDKDVMJobFeedback.from(p);if(y.status==="error"){const b=y.getMatchingTags("status");u((b==null?void 0:b[2])??y)}else h(y)}h(p)})),a.publish().then(()=>{s||h(void 0)})});return new Promise((h,u)=>{s?Promise.race([l,f]).then(p=>{h(p)}).catch(u):f.then(h)})}function dedup(n,e){return n.created_at>e.created_at?n:e}async function getRelayListForUser(n,e){return(await getRelayListForUsers([n],e)).get(n)}async function getRelayListForUsers(n,e,t=!1,r=1e3){var u;const s=e.outboxPool||e.pool,o=new Set;for(const p of s.relays.values())o.add(p);const a=new Map,c=new Map,l=new NDKRelaySet(o,e);if((u=e.cacheAdapter)!=null&&u.locking&&!t){const p=await e.fetchEvents({kinds:[3,10002],authors:Array.from(new Set(n))},{cacheUsage:"ONLY_CACHE",subId:"ndk-relay-list-fetch"});for(const y of p)y.kind===10002&&a.set(y.pubkey,NDKRelayList.from(y));for(const y of p)if(y.kind===3){if(a.has(y.pubkey))continue;const b=relayListFromKind3(e,y);b&&c.set(y.pubkey,b)}n=n.filter(y=>!a.has(y)&&!c.has(y))}if(n.length===0)return a;const f=new Map,h=new Map;return new Promise(p=>{(async()=>{const b={closeOnEose:!0,pool:s,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:l};l&&(b.relaySet=l),e.subscribe({kinds:[3,10002],authors:n},b,{onEvent:m=>{if(m.kind===10002){const k=f.get(m.pubkey);if(k&&k.created_at>m.created_at)return;f.set(m.pubkey,m)}else if(m.kind===3){const k=h.get(m.pubkey);if(k&&k.created_at>m.created_at)return;h.set(m.pubkey,m)}},onEose:()=>{for(const m of f.values())a.set(m.pubkey,NDKRelayList.from(m));for(const m of n){if(a.has(m))continue;const k=h.get(m);if(!k)continue;const R=relayListFromKind3(e,k);R&&a.set(m,R)}p(a)}}),setTimeout(()=>{p(a)},r)})()})}var OutboxItem=class{constructor(n){g(this,"type");g(this,"relayUrlScores");g(this,"readRelays");g(this,"writeRelays");this.type=n,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{constructor(e){super();g(this,"data");g(this,"ndk");g(this,"debug");this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:2*60*1e3})}async trackUsers(e,t=!1){const r=[];for(let s=0;s<e.length;s+=400){const a=e.slice(s,s+400).map(c=>getKeyFromItem(c)).filter(c=>!this.data.has(c));if(a.length!==0){for(const c of a)this.data.set(c,new OutboxItem("user"));r.push(new Promise(c=>{getRelayListForUsers(a,this.ndk,t).then(l=>{for(const[f,h]of l){let u=this.data.get(f);if(u??(u=new OutboxItem("user")),h){u.readRelays=new Set(normalize(h.readRelayUrls)),u.writeRelays=new Set(normalize(h.writeRelayUrls));for(const p of u.readRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&u.readRelays.delete(p);for(const p of u.writeRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&u.writeRelays.delete(p);this.data.set(f,u)}}}).finally(c)}))}}return Promise.all(r)}track(e,t,r=!0){const s=getKeyFromItem(e);t??(t=getTypeFromItem(e));let o=this.data.get(s);return o||(o=new OutboxItem(t),e instanceof NDKUser&&this.trackUsers([e])),o}};function getKeyFromItem(n){return n instanceof NDKUser?n.pubkey:n}function getTypeFromItem(n){return n instanceof NDKUser?"user":"kind"}function correctRelaySet(n,e){const t=e.connectedRelays();if(!Array.from(n.relays).some(s=>t.map(o=>o.url).includes(s.url)))for(const s of t)n.addRelay(s);if(t.length===0)for(const s of e.relays.values())n.addRelay(s);return n}var NDKSubscriptionManager=class{constructor(){g(this,"subscriptions");g(this,"seenEvents",new Map);this.subscriptions=new Map}add(n){this.subscriptions.set(n.internalId,n),n.onStopped,n.onStopped=()=>{this.subscriptions.delete(n.internalId)},n.on("close",()=>{this.subscriptions.delete(n.internalId)})}seenEvent(n,e){const t=this.seenEvents.get(n)||[];t.push(e),this.seenEvents.set(n,t)}dispatchEvent(n,e,t=!1){e&&this.seenEvent(n.id,e);const r=this.subscriptions.values(),s=[];for(const o of r)matchFilters(o.filters,n)&&s.push(o);for(const o of s)o.eventReceived(n,e,!1,t)}},debug7=createDebug2("ndk:active-user");async function getUserRelayList(n){if(!this.autoConnectUserRelays)return;const e=await getRelayListForUser(n.pubkey,this);if(e){for(const t of e.relays){let r=this.pool.relays.get(t);r||(r=new NDKRelay(t,this.relayAuthDefaultPolicy,this),this.pool.addRelay(r))}return e}}async function setActiveUser(n){const e=this.outboxPool||this.pool;e.connectedRelays.length>0?setActiveUserConnected.call(this,n):e.once("connect",()=>{setActiveUserConnected.call(this,n)})}async function setActiveUserConnected(n){var o;const e=await getUserRelayList.call(this,n),t=[{kinds:[10006],authors:[n.pubkey]}];this.autoFetchUserMutelist&&((o=t[0].kinds)==null||o.push(1e4));const r=new Map,s=e?e.relaySet:void 0;this.subscribe(t,{subId:"active-user-settings",closeOnEose:!0,relaySet:s},{onEvent:a=>{const c=r.get(a.kind);c&&c.created_at>=a.created_at||r.set(a.kind,a)},onEose:()=>{for(const a of r.values())processEvent.call(this,a)}})}async function processEvent(n){n.kind===10006?processBlockRelayList.call(this,n):n.kind===1e4&&processMuteList.call(this,n)}function processBlockRelayList(n){const e=lists_default.from(n);for(const t of e.items)this.pool.blacklistRelayUrls.add(t[0]);debug7("Added %d relays to relay blacklist",e.items.length)}function processMuteList(n){const e=lists_default.from(n);for(const t of e.items)this.mutedIds.set(t[1],t[0]);debug7("Added %d users to mute list",e.items.length)}function getEntity(n){try{const e=nip19_exports.decode(n);return e.type==="npub"?npub(this,e.data):e.type==="nprofile"?nprofile(this,e.data):e}catch{return null}}function npub(n,e){return n.getUser({pubkey:e})}function nprofile(n,e){const t=n.getUser({pubkey:e.pubkey});return e.relays&&(t.relayUrls=e.relays),t}function isValidHint(n){if(!n||n==="")return!1;try{return new URL(n),!0}catch{return!1}}async function fetchEventFromTag(n,e,t,r={type:"timeout"}){const s=this.debug.extend("fetch-event-from-tag"),[o,a,c]=n;t={},s("fetching event from tag",n,t,r);const l=getRelaysForSync(this,e.pubkey);if(l&&l.size>0){s("fetching event from author relays %o",Array.from(l));const m=NDKRelaySet.fromRelayUrls(Array.from(l),this),k=await this.fetchEvent(a,t,m);if(k)return k}else s("no author relays found for %s",e.pubkey,e);const f=calculateRelaySetsFromFilters(this,[{ids:[a]}],this.pool);s("fetching event without relay hint",f);const h=await this.fetchEvent(a,t);if(h)return h;if(c&&c!==""){const m=await this.fetchEvent(a,t,this.pool.getRelay(c,!0,!0,[{ids:[a]}]));if(m)return m}let u;const p=isValidHint(c)?this.pool.getRelay(c,!1,!0,[{ids:[a]}]):void 0,y=new Promise(m=>{this.fetchEvent(a,t,p).then(m)});if(!isValidHint(c)||r.type==="none")return y;const b=new Promise(async m=>{const k=r.relaySet,R=r.timeout??1500,B=new Promise(D=>setTimeout(D,R));if(r.type==="timeout"&&await B,u)m(u);else{s("fallback fetch triggered");const D=await this.fetchEvent(a,t,k);m(D)}});switch(r.type){case"timeout":return Promise.race([y,b]);case"eose":return u=await y,u||b}}var Queue=class{constructor(n,e){g(this,"queue",[]);g(this,"maxConcurrency");g(this,"processing",new Set);g(this,"promises",new Map);this.maxConcurrency=e}add(n){if(this.promises.has(n.id))return this.promises.get(n.id);const e=new Promise((t,r)=>{this.queue.push({...n,func:()=>n.func().then(s=>(t(s),s),s=>{throw r(s),s})}),this.process()});return this.promises.set(n.id,e),e.finally(()=>{this.promises.delete(n.id),this.processing.delete(n.id),this.process()}),e}process(){if(this.processing.size>=this.maxConcurrency||this.queue.length===0)return;const n=this.queue.shift();!n||this.processing.has(n.id)||(this.processing.add(n.id),n.func())}clear(){this.queue=[]}clearProcessing(){this.processing.clear()}clearAll(){this.clear(),this.clearProcessing()}length(){return this.queue.length}},DEFAULT_OUTBOX_RELAYS=["wss://purplepag.es/","wss://nos.lol/"],DEFAULT_BLACKLISTED_RELAYS=["wss://brb.io/","wss://nostr.mutinywallet.com/"],NDK=class extends lib$1.EventEmitter{constructor(e={}){super();g(this,"_explicitRelayUrls");g(this,"blacklistRelayUrls");g(this,"pool");g(this,"outboxPool");g(this,"_signer");g(this,"_activeUser");g(this,"cacheAdapter");g(this,"debug");g(this,"devWriteRelaySet");g(this,"outboxTracker");g(this,"mutedIds");g(this,"clientName");g(this,"clientNip89");g(this,"queuesZapConfig");g(this,"queuesNip05");g(this,"asyncSigVerification",!1);g(this,"initialValidationRatio",1);g(this,"lowestValidationRatio",.1);g(this,"validationRatioFn");g(this,"autoBlacklistInvalidRelays",!1);g(this,"subManager");g(this,"_signatureVerificationFunction");g(this,"_signatureVerificationWorker");g(this,"signatureVerificationTimeMs",0);g(this,"publishingFailureHandled",!1);g(this,"pools",[]);g(this,"relayAuthDefaultPolicy");g(this,"httpFetch");g(this,"netDebug");g(this,"autoConnectUserRelays",!0);g(this,"autoFetchUserMutelist",!0);g(this,"walletConfig");g(this,"fetchEventFromTag",fetchEventFromTag.bind(this));g(this,"getEntity",getEntity.bind(this));this.debug=e.debug||createDebug2("ndk"),this.netDebug=e.netDebug,this._explicitRelayUrls=e.explicitRelayUrls||[],this.blacklistRelayUrls=e.blacklistRelayUrls||DEFAULT_BLACKLISTED_RELAYS,this.subManager=new NDKSubscriptionManager,this.pool=new NDKPool(e.explicitRelayUrls||[],[],this),this.pool.name="Main",this.pool.on("relay:auth",async(t,r)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(t,r)}),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.autoFetchUserMutelist=e.autoFetchUserMutelist??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,e.enableOutboxModel&&(this.outboxPool=new NDKPool(e.outboxRelayUrls||DEFAULT_OUTBOX_RELAYS,[],this,{debug:this.debug.extend("outbox-pool"),name:"Outbox Pool"}),this.outboxTracker=new OutboxTracker(this)),this.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.mutedIds=e.mutedIds||new Map,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this)),this.queuesZapConfig=new Queue("zaps",3),this.queuesNip05=new Queue("nip05",10),e.signatureVerificationWorker&&(this.signatureVerificationWorker=e.signatureVerificationWorker),e.signatureVerificationFunction&&(this.signatureVerificationFunction=e.signatureVerificationFunction),this.initialValidationRatio=e.initialValidationRatio||1,this.lowestValidationRatio=e.lowestValidationRatio||.1,this.autoBlacklistInvalidRelays=e.autoBlacklistInvalidRelays||!1,this.validationRatioFn=e.validationRatioFn||this.defaultValidationRatioFn;try{this.httpFetch=fetch}catch{}}set explicitRelayUrls(e){this._explicitRelayUrls=e.map(normalizeRelayUrl),this.pool.relayUrls=e}get explicitRelayUrls(){return this._explicitRelayUrls||[]}set signatureVerificationWorker(e){this._signatureVerificationWorker=e,e?(signatureVerificationInit(e),this.asyncSigVerification=!0):this.asyncSigVerification=!1}set signatureVerificationFunction(e){this._signatureVerificationFunction=e,this.asyncSigVerification=!!e}get signatureVerificationFunction(){return this._signatureVerificationFunction}addExplicitRelay(e,t,r=!0){var o;let s;return typeof e=="string"?s=new NDKRelay(e,t,this):s=e,this.pool.addRelay(s,r),(o=this.explicitRelayUrls)==null||o.push(s.url),s}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){var r;const t=((r=this._activeUser)==null?void 0:r.pubkey)!==(e==null?void 0:e.pubkey);this._activeUser=e,e&&t?setActiveUser.call(this,e):e||(this.mutedIds=new Map)}get signer(){return this._signer}set signer(e){this._signer=e,e&&this.emit("signer:ready",e),e==null||e.user().then(t=>{t.ndk=this,this.activeUser=t})}async connect(e){var r,s;this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer %o",await((s=(r=this._signer).relays)==null?void 0:s.call(r,this))),this._signer.relays&&(await this._signer.relays(this)).forEach(a=>this.pool.addRelay(a)));const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),Promise.allSettled(t).then(()=>{})}reportInvalidSignature(e,t){this.debug(`Invalid signature detected for event ${e.id}${t?` from relay ${t.url}`:""}`),this.emit("event:invalid-sig",e,t),this.autoBlacklistInvalidRelays&&t&&this.blacklistRelay(t.url)}blacklistRelay(e){if(this.blacklistRelayUrls||(this.blacklistRelayUrls=[]),!this.blacklistRelayUrls.includes(e)){this.blacklistRelayUrls.push(e),this.debug(`Added relay to blacklist: ${e}`);const t=this.pool.getRelay(e,!1,!1);t&&(t.disconnect(),this.debug(`Disconnected from blacklisted relay: ${e}`))}}defaultValidationRatioFn(e,t,r){if(t<10)return this.initialValidationRatio;const s=Math.min(t/100,1),o=this.initialValidationRatio*(1-s)+this.lowestValidationRatio*s;return Math.max(o,this.lowestValidationRatio)}getUser(e){const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}subscribe(e,t,r=!0,s=!0){var f;let o=t==null?void 0:t.relaySet,a=s;r instanceof NDKRelaySet?(console.warn("relaySet is deprecated, use opts.relaySet instead. This will be removed in version v2.14.0"),o=r,a=s):(typeof r=="boolean"||typeof r=="object")&&(a=r);const c=new NDKSubscription(this,e,{relaySet:o,...t});this.subManager.add(c);const l=c.pool;if(c.relaySet)for(const h of c.relaySet.relays)l.useTemporaryRelay(h,void 0,c.filters);if(this.outboxPool&&c.hasAuthorsFilter()){const h=c.filters.filter(u=>{var p;return u.authors&&((p=u.authors)==null?void 0:p.length)>0}).flatMap(u=>u.authors);(f=this.outboxTracker)==null||f.trackUsers(h)}if(a){let h;typeof a=="object"&&(a.onEvent&&c.on("event",a.onEvent),a.onEose&&c.on("eose",a.onEose),a.onEvents&&(h=a.onEvents)),setTimeout(()=>{const u=c.start(!h);u&&u.length>0&&h&&h(u)},0)}return c}fetchEventSync(e){if(!this.cacheAdapter)throw new Error("Cache adapter not set");let t;typeof e=="string"?t=[filterFromId(e)]:t=e;const r=new NDKSubscription(this,t),s=this.cacheAdapter.query(r);if(s instanceof Promise)throw new Error("Cache adapter is async");return s.map(o=>(o.ndk=this,o))}async fetchEvent(e,t,r){let s,o;if(r instanceof NDKRelay?o=new NDKRelaySet(new Set([r]),this):r instanceof NDKRelaySet&&(o=r),!r&&typeof e=="string"&&!isNip33AValue(e)){const a=relaysFromBech32(e,this);a.length>0&&(o=new NDKRelaySet(new Set(a),this),o=correctRelaySet(o,this.pool))}if(typeof e=="string"?s=[filterFromId(e)]:Array.isArray(e)?s=e:s=[e],s.length===0)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise(a=>{let c=null;const l={...t||{},closeOnEose:!0};o&&(l.relaySet=o);const f=this.subscribe(s,l,!1),h=setTimeout(()=>{f.stop(),a(c)},1e4);f.on("event",u=>{u.ndk=this,u.isReplaceable()?(!c||c.created_at<u.created_at)&&(c=u):(clearTimeout(h),a(u))}),f.on("eose",()=>{clearTimeout(h),a(c)}),f.start()})}async fetchEvents(e,t,r){return new Promise(s=>{const o=new Map,a={...t||{},closeOnEose:!0};r&&(a.relaySet=r);const c=this.subscribe(e,a,!1),l=f=>{let h;f instanceof NDKEvent?h=f:h=new NDKEvent(void 0,f);const u=h.deduplicationKey(),p=o.get(u);p&&(h=dedup(p,h)),h.ndk=this,o.set(u,h)};c.on("event",l),c.on("eose",()=>{s(new Set(o.values()))}),c.start()})}assertSigner(){if(!this.signer)throw this.emit("signer:required"),new Error("Signer required")}set wallet(e){var t,r;if(!e){this.walletConfig=void 0;return}this.walletConfig??(this.walletConfig={}),this.walletConfig.lnPay=(t=e==null?void 0:e.lnPay)==null?void 0:t.bind(e),this.walletConfig.cashuPay=(r=e==null?void 0:e.cashuPay)==null?void 0:r.bind(e)}};function zapInvoiceFromEvent(n){const e=n.getMatchingTags("description")[0],t=n.getMatchingTags("bolt11")[0];let r,s;if(!e||!t||!t[1])return null;try{let b=e[1];if(b.startsWith("%")&&(b=decodeURIComponent(b)),b==="")return null;s=JSON.parse(b),r=bolt11.decode(t[1])}catch{return null}const o=r.sections.find(b=>b.name==="amount");if(!o)return null;const a=Number.parseInt(o.value);if(!a)return null;const c=s.content,l=s.pubkey,h=n.getMatchingTags("p")[0][1];let u=n.getMatchingTags("e")[0];u||(u=n.getMatchingTags("a")[0]);const p=u?u[1]:void 0;return{id:n.id,zapper:n.pubkey,zappee:l,zapped:h,zappedEvent:p,amount:a,comment:c}}var d2=createDebug2("ndk:zapper:ln");async function getNip57ZapSpecFromLud({lud06:n,lud16:e},t){let r;if(e&&!e.startsWith("LNURL")){const[s,o]=e.split("@");r=`https://${o}/.well-known/lnurlp/${s}`}else if(n){const{words:s}=bech32.decode(n,1e3),o=bech32.fromWords(s);r=new TextDecoder("utf-8").decode(o)}if(!r)throw d2("No zap endpoint found %o",{lud06:n,lud16:e}),new Error("No zap endpoint found");try{const o=await(t.httpFetch||fetch)(r);if(o.status!==200){const a=await o.text();throw new Error(`Unable to fetch zap endpoint ${r}: ${a}`)}return await o.json()}catch(s){throw new Error(`Unable to fetch zap endpoint ${r}: ${s}`)}}async function generateZapRequest(n,e,t,r,s,o,a,c,l){const f=t.callback,h=nip57_exports.makeZapRequest({profile:r,event:null,amount:s,comment:a||"",relays:o.slice(0,4)});if(n instanceof NDKEvent){const m=n.referenceTags().filter(k=>k[0]!=="p");h.tags.push(...m)}h.tags.push(["lnurl",f]);const u=new NDKEvent(e,h);c&&(u.tags=u.tags.concat(c));const p=new Set,y=new Set;for(const b of u.tags)b[0]==="e"?p.add(b[1]):b[0]==="a"&&y.add(b[1]);if(p.size>1)throw new Error("Only one e-tag is allowed");if(y.size>1)throw new Error("Only one a-tag is allowed");return u.tags=u.tags.filter(b=>b[0]!=="p"),u.tags.push(["p",r]),await u.sign(l),u}var d3=createDebug2("ndk:zapper"),NDKZapper=class extends lib$1.EventEmitter{constructor(e,t,r="msat",s={}){var o,a,c;super();g(this,"target");g(this,"ndk");g(this,"comment");g(this,"amount");g(this,"unit");g(this,"tags");g(this,"signer");g(this,"zapMethod");g(this,"nutzapAsFallback");g(this,"lnPay");g(this,"cashuPay");g(this,"onComplete");g(this,"maxRelays",3);if(this.target=e,this.ndk=s.ndk||e.ndk,!this.ndk)throw new Error("No NDK instance provided");this.amount=t,this.comment=s.comment,this.unit=r,this.tags=s.tags,this.signer=s.signer,this.nutzapAsFallback=s.nutzapAsFallback??!1,this.lnPay=s.lnPay||((o=this.ndk.walletConfig)==null?void 0:o.lnPay),this.cashuPay=s.cashuPay||((a=this.ndk.walletConfig)==null?void 0:a.cashuPay),this.onComplete=s.onComplete||((c=this.ndk.walletConfig)==null?void 0:c.onPaymentComplete)}async zap(e){const t=this.getZapSplits(),r=new Map;return await Promise.all(t.map(async s=>{let o;try{o=await this.zapSplit(s,e)}catch(a){o=new Error(a.message)}this.emit("split:complete",s,o),r.set(s,o)})),this.emit("complete",r),this.onComplete&&this.onComplete(r),r}async zapNip57(e,t){if(!this.lnPay)throw new Error("No lnPay function available");const r=await getNip57ZapSpecFromLud(t,this.ndk);if(!r)throw new Error("No zap spec available for recipient");const s=await this.relays(e.pubkey),o=await generateZapRequest(this.target,this.ndk,r,e.pubkey,e.amount,s,this.comment,this.tags,this.signer);if(!o)throw d3("Unable to generate zap request"),new Error("Unable to generate zap request");const a=await this.getLnInvoice(o,e.amount,r);if(!a)throw d3("Unable to get payment request"),new Error("Unable to get payment request");this.emit("ln_invoice",{amount:e.amount,recipientPubkey:e.pubkey,unit:this.unit,nip57ZapRequest:o,pr:a,type:"nip57"});const c=await this.lnPay({target:this.target,recipientPubkey:e.pubkey,paymentDescription:"NIP-57 Zap",pr:a,amount:e.amount,unit:this.unit,nip57ZapRequest:o});return c!=null&&c.preimage&&this.emit("ln_payment",{preimage:c.preimage,amount:e.amount,recipientPubkey:e.pubkey,pr:a,unit:this.unit,nip57ZapRequest:o,type:"nip57"}),c}async zapNip61(e,t){if(!this.cashuPay)throw new Error("No cashuPay function available");let r;if(r=await this.cashuPay({target:this.target,recipientPubkey:e.pubkey,paymentDescription:"NIP-61 Zap",amount:e.amount,unit:this.unit,...t??{}},s=>{this.emit("ln_invoice",{pr:s,amount:e.amount,recipientPubkey:e.pubkey,unit:this.unit,type:"nip61"})}),d3("NIP-61 Zap result: %o",r),r instanceof Error)return r;if(r){const{proofs:s,mint:o}=r;if(!s||!o)throw new Error(`Invalid zap confirmation: missing proofs or mint: ${r}`);const a=await this.relays(e.pubkey),c=NDKRelaySet.fromRelayUrls(a,this.ndk),l=new NDKNutzap(this.ndk);return l.tags=[...l.tags,...this.tags||[]],l.proofs=s,l.mint=o,l.target=this.target,l.comment=this.comment,l.unit="sat",l.recipientPubkey=e.pubkey,await l.sign(this.signer),l.publish(c),l}}async zapSplit(e,t){const s=await this.ndk.getUser({pubkey:e.pubkey}).getZapInfo(2500);let o;const a=this.nutzapAsFallback&&this.cashuPay;if(s.size===0&&!a)throw new Error("No zap method available for recipient and NIP-61 fallback is disabled");const c=async()=>{var b;if(!this.nutzapAsFallback)return;let y=(b=(await getRelayListForUsers([e.pubkey],this.ndk)).get(e.pubkey))==null?void 0:b.readRelayUrls;return y=this.ndk.pool.connectedRelays().map(m=>m.url),await this.zapNip61(e,{relays:y,p2pk:e.pubkey,allowIntramintFallback:!!a})},l=!t||t.includes("nip61"),f=!t||t.includes("nip57"),h=s.get("nip61");if(h&&l)try{if(o=await this.zapNip61(e,h),o instanceof NDKNutzap)return o}catch(p){this.emit("notice",`NIP-61 attempt failed: ${p.message}`)}const u=s.get("nip57");if(u&&f)try{if(o=await this.zapNip57(e,u),!(o instanceof Error))return o}catch(p){this.emit("notice",`NIP-57 attempt failed: ${p.message}`)}if(a){if(o=await c(),o instanceof Error)throw o;return o}if(this.emit("notice","Zap methods exhausted and there was no fallback to NIP-61"),o instanceof Error)throw o;return o}async getLnInvoice(e,t,r){const s=r.callback,o=JSON.stringify(e.rawEvent());d3(`Fetching invoice from ${s}?${new URLSearchParams({amount:t.toString(),nostr:o})}`);const a=new URL(s);a.searchParams.append("amount",t.toString()),a.searchParams.append("nostr",o),d3(`Fetching invoice from ${a.toString()}`);const c=await fetch(a.toString());if(d3(`Got response from zap endpoint: ${s}`,{status:c.status}),c.status!==200){d3(`Received non-200 status from zap endpoint: ${s}`,{status:c.status,amount:t,nostr:o});const f=await c.text();throw new Error(`Unable to fetch zap endpoint ${s}: ${f}`)}return(await c.json()).pr}getZapSplits(){if(this.target instanceof NDKUser)return[{pubkey:this.target.pubkey,amount:this.amount}];const e=this.target.getMatchingTags("zap");if(e.length===0)return[{pubkey:this.target.pubkey,amount:this.amount}];const t=[],r=e.reduce((s,o)=>s+Number.parseInt(o[2]),0);for(const s of e){const o=s[1],a=Math.floor(Number.parseInt(s[2])/r*this.amount);t.push({pubkey:o,amount:a})}return t}async getZapMethods(e,t,r=2500){return await e.getUser({pubkey:t}).getZapInfo(r)}async relays(e){var r,s,o;let t=[];if((r=this.ndk)!=null&&r.activeUser){const a=await getRelayListForUsers([this.ndk.activeUser.pubkey,e],this.ndk),c=new Map;for(const l of a.values())for(const f of l.readRelayUrls){const h=c.get(f)||0;c.set(f,h+1)}t=Array.from(c.entries()).sort((l,f)=>f[1]-l[1]).map(([l])=>l).slice(0,this.maxRelays)}return(o=(s=this.ndk)==null?void 0:s.pool)!=null&&o.permanentAndConnectedRelays().length&&(t=this.ndk.pool.permanentAndConnectedRelays().map(a=>a.url)),t.length||(t=[]),t}};function matchFilter(n,e){var t;if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(const r in n)if(r[0]==="#"){const s=r.slice(1);if(s==="t"){const o=(t=n[`#${s}`])==null?void 0:t.map(a=>a.toLowerCase());if(o&&!e.tags.find(([a,c])=>a===s&&(o==null?void 0:o.indexOf(c.toLowerCase()))!==-1))return!1}else{const o=n[`#${s}`];if(o&&!e.tags.find(([a,c])=>a===s&&(o==null?void 0:o.indexOf(c))!==-1))return!1}}return!(n.since&&e.created_at<n.since||n.until&&e.created_at>n.until)}const index=Object.freeze(Object.defineProperty({__proto__:null,BECH32_REGEX,NDKAppHandlerEvent,NDKAppSettings,NDKArticle,NDKBlossomList,NDKCashuMintList,NDKCashuToken,NDKCashuWalletTx,NDKClassified,NDKDVMJobFeedback,NDKDVMJobResult,NDKDVMRequest,NDKDraft,NDKDvmJobFeedbackStatus,NDKEvent,NDKFollowPack,NDKHighlight,NDKImage,NDKKind,NDKList,NDKListKinds,NDKNip07Signer,NDKNip46Backend,NDKNip46Signer,NDKNostrRpc,NDKNutzap,NDKPool,NDKPrivateKeySigner,NDKProject,NDKProjectTemplate,NDKPublishError,NDKRelay,NDKRelayAuthPolicies,NDKRelayList,NDKRelaySet,NDKRelayStatus,NDKRepost,NDKSimpleGroup,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKStory,NDKStorySticker,NDKStoryStickerType,NDKSubscription,NDKSubscriptionCacheUsage,NDKSubscriptionReceipt,NDKSubscriptionStart,NDKSubscriptionTier,NDKTask,NDKThread,NDKTranscriptionDVM,NDKUser,NDKVideo,NDKWiki,NDKWikiMergeRequest,NDKZapper,NIP33_A_REGEX,NdkNutzapStatus,SignatureVerificationStats,assertSignedEvent,calculateRelaySetFromEvent,calculateTermDurationInSeconds,cashuPubkeyToNostrPubkey,compareFilter,createSignedEvent,default:NDK,defaultOpts,deserialize,dvmSchedule,eventHasETagMarkers,eventIsPartOfThread,eventIsReply,eventReplies,eventThreadIds,eventThreads,eventsBySameAuthor,filterAndRelaySetFromBech32,filterFingerprint,filterForEventsTaggingId,filterFromId,generateContentTags,generateHashtags,generateSubId,generateZapRequest,getEventReplyId,getNip57ZapSpecFromLud,getRegisteredEventClasses,getRelayListForUser,getRelayListForUsers,getReplyTag,getRootEventId,getRootTag,giftUnwrap,giftWrap,imetaTagToTag,isEventOriginalPost,isNip33AValue,isSignedEvent,isUnsignedEvent,mapImetaTag,matchFilter,mergeFilters,mergeTags,ndkSignerFromPayload,newAmount,normalize,normalizeRelayUrl,normalizeUrl,parseTagToSubscriptionAmount,pinEvent,possibleIntervalFrequencies,profileFromEvent,proofP2pk,proofP2pkNostr,proofsTotalBalance,queryFullyFilled,registerEventClass,registerSigner,relayListFromKind3,relaysFromBech32,serialize,serializeProfile,startSignatureVerificationStats,strToDimension,strToPosition,tryNormalizeRelayUrl,uniqueTag,unregisterEventClass,wrapEvent,zapInvoiceFromEvent},Symbol.toStringTag,{value:"Module"}));export{NDKEvent as N,createDebug2 as a,dist as b,commonjsGlobal as c,deserialize as d,NDK as e,getPublicKey as f,getDefaultExportFromCjs as g,NDKPrivateKeySigner as h,generateSecretKey as i,index as j,matchFilter$1 as m,nip19_exports as n,profileFromEvent as p};