Files
next.orly.dev/app/web/dist/bundle.js
mleku 384b6113bc
Some checks failed
Go / build (push) Has been cancelled
Go / release (push) Has been cancelled
fixes memory problem with many pubkeys in query
2025-10-20 22:20:21 +01:00

24 lines
489 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
var app=function(){"use strict";function noop(){}function run(e){return e()}function blank_object(){return Object.create(null)}function run_all(e){e.forEach(run)}function is_function(e){return"function"==typeof e}function safe_not_equal(e,t){return e!=e?t==t:e!==t||e&&"object"==typeof e||"function"==typeof e}let src_url_equal_anchor;function src_url_equal(e,t){return src_url_equal_anchor||(src_url_equal_anchor=document.createElement("a")),src_url_equal_anchor.href=t,e===src_url_equal_anchor.href}function is_empty(e){return 0===Object.keys(e).length}const globals="undefined"!=typeof window?window:"undefined"!=typeof globalThis?globalThis:global;function append(e,t){e.appendChild(t)}function insert(e,t,n){e.insertBefore(t,n||null)}function detach(e){e.parentNode&&e.parentNode.removeChild(e)}function destroy_each(e,t){for(let n=0;n<e.length;n+=1)e[n]&&e[n].d(t)}function element(e){return document.createElement(e)}function text(e){return document.createTextNode(e)}function space(){return text(" ")}function empty(){return text("")}function listen(e,t,n,s){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}function stop_propagation(e){return function(t){return t.stopPropagation(),e.call(this,t)}}function attr(e,t,n){null==n?e.removeAttribute(t):e.getAttribute(t)!==n&&e.setAttribute(t,n)}function to_number(e){return""===e?null:+e}function children(e){return Array.from(e.childNodes)}function set_data(e,t){t=""+t,e.data!==t&&(e.data=t)}function set_input_value(e,t){e.value=null==t?"":t}function select_option(e,t,n){for(let n=0;n<e.options.length;n+=1){const s=e.options[n];if(s.__value===t)return void(s.selected=!0)}n&&void 0===t||(e.selectedIndex=-1)}function select_value(e){const t=e.querySelector(":checked");return t&&t.__value}function toggle_class(e,t,n){e.classList[n?"add":"remove"](t)}function custom_event(e,t,{bubbles:n=!1,cancelable:s=!1}={}){const r=document.createEvent("CustomEvent");return r.initCustomEvent(e,n,s,t),r}let current_component;function set_current_component(e){current_component=e}function get_current_component(){if(!current_component)throw new Error("Function called outside component initialization");return current_component}function onMount(e){get_current_component().$$.on_mount.push(e)}function createEventDispatcher(){const e=get_current_component();return(t,n,{cancelable:s=!1}={})=>{const r=e.$$.callbacks[t];if(r){const i=custom_event(t,n,{cancelable:s});return r.slice().forEach(t=>{t.call(e,i)}),!i.defaultPrevented}return!0}}function bubble(e,t){const n=e.$$.callbacks[t.type];n&&n.slice().forEach(e=>e.call(this,t))}const dirty_components=[],binding_callbacks=[];let render_callbacks=[];const flush_callbacks=[],resolved_promise=Promise.resolve();let update_scheduled=!1;function schedule_update(){update_scheduled||(update_scheduled=!0,resolved_promise.then(flush))}function add_render_callback(e){render_callbacks.push(e)}function add_flush_callback(e){flush_callbacks.push(e)}const seen_callbacks=new Set;let flushidx=0;function flush(){if(0!==flushidx)return;const e=current_component;do{try{for(;flushidx<dirty_components.length;){const e=dirty_components[flushidx];flushidx++,set_current_component(e),update(e.$$)}}catch(e){throw dirty_components.length=0,flushidx=0,e}for(set_current_component(null),dirty_components.length=0,flushidx=0;binding_callbacks.length;)binding_callbacks.pop()();for(let e=0;e<render_callbacks.length;e+=1){const t=render_callbacks[e];seen_callbacks.has(t)||(seen_callbacks.add(t),t())}render_callbacks.length=0}while(dirty_components.length);for(;flush_callbacks.length;)flush_callbacks.pop()();update_scheduled=!1,seen_callbacks.clear(),set_current_component(e)}function update(e){if(null!==e.fragment){e.update(),run_all(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(add_render_callback)}}function flush_render_callbacks(e){const t=[],n=[];render_callbacks.forEach(s=>-1===e.indexOf(s)?t.push(s):n.push(s)),n.forEach(e=>e()),render_callbacks=t}const outroing=new Set;let outros;function group_outros(){outros={r:0,c:[],p:outros}}function check_outros(){outros.r||run_all(outros.c),outros=outros.p}function transition_in(e,t){e&&e.i&&(outroing.delete(e),e.i(t))}function transition_out(e,t,n,s){if(e&&e.o){if(outroing.has(e))return;outroing.add(e),outros.c.push(()=>{outroing.delete(e),s&&(n&&e.d(1),s())}),e.o(t)}else s&&s()}function bind(e,t,n){const s=e.$$.props[t];void 0!==s&&(e.$$.bound[s]=n,n(e.$$.ctx[s]))}function create_component(e){e&&e.c()}function mount_component(e,t,n,s){const{fragment:r,after_update:i}=e.$$;r&&r.m(t,n),s||add_render_callback(()=>{const t=e.$$.on_mount.map(run).filter(is_function);e.$$.on_destroy?e.$$.on_destroy.push(...t):run_all(t),e.$$.on_mount=[]}),i.forEach(add_render_callback)}function destroy_component(e,t){const n=e.$$;null!==n.fragment&&(flush_render_callbacks(n.after_update),run_all(n.on_destroy),n.fragment&&n.fragment.d(t),n.on_destroy=n.fragment=null,n.ctx=[])}function make_dirty(e,t){-1===e.$$.dirty[0]&&(dirty_components.push(e),schedule_update(),e.$$.dirty.fill(0)),e.$$.dirty[t/31|0]|=1<<t%31}function init(e,t,n,s,r,i,o,a=[-1]){const c=current_component;set_current_component(e);const l=e.$$={fragment:null,ctx:[],props:i,update:noop,not_equal:r,bound:blank_object(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(t.context||(c?c.$$.context:[])),callbacks:blank_object(),dirty:a,skip_bound:!1,root:t.target||c.$$.root};o&&o(l.root);let u=!1;if(l.ctx=n?n(e,t.props||{},(t,n,...s)=>{const i=s.length?s[0]:n;return l.ctx&&r(l.ctx[t],l.ctx[t]=i)&&(!l.skip_bound&&l.bound[t]&&l.bound[t](i),u&&make_dirty(e,t)),n}):[],l.update(),u=!0,run_all(l.before_update),l.fragment=!!s&&s(l.ctx),t.target){if(t.hydrate){const e=children(t.target);l.fragment&&l.fragment.l(e),e.forEach(detach)}else l.fragment&&l.fragment.c();t.intro&&transition_in(e.$$.fragment),mount_component(e,t.target,t.anchor,t.customElement),flush()}set_current_component(c)}class SvelteComponent{$destroy(){destroy_component(this,1),this.$destroy=noop}$on(e,t){if(!is_function(t))return noop;const n=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return n.push(t),()=>{const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}$set(e){this.$$set&&!is_empty(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var lib$1={},types={};Object.defineProperty(types,"__esModule",{value:!0});var ee={},taskCollection$1={},taskCollection={},utils$1={};function _fast_remove_single(e,t){-1!==t&&(0===t?e.shift():t===e.length-1?e.length=e.length-1:e.splice(t,1))}Object.defineProperty(utils$1,"__esModule",{value:!0}),utils$1._fast_remove_single=void 0,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(e){var t="";if(0===e)return t;for(var n=0;n<e-1;++n)t+="arg"+String(n)+", ";return t+="arg"+String(e-1)}function generateBodyPartsCode(e,t){for(var n="",s="",r=0;r<t;++r)n+="var f".concat(r," = collection[").concat(r,"];\n"),s+="f".concat(r,"(").concat(e,")\n");return{funcDefCode:n,funcCallCode:s}}function generateBodyPartsVariadicCode(e){for(var t="",n="",s=0;s<e;++s)t+="var f".concat(s," = collection[").concat(s,"];\n"),n+="f".concat(s,".apply(undefined, arguments)\n");return{funcDefCode:t,funcCallCode:n}}function bakeCollection(collection,fixedArgsNum){if(0===collection.length)return exports.BAKED_EMPTY_FUNC;if(1===collection.length)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) {\n ".concat(funcDefCode,"\n collection = undefined;\n return (function(").concat(argsDefCode,") {\n ").concat(funcCallCode,"\n });\n })")}else{var argsDefCode=generateArgsDefCode(fixedArgsNum);funcFactoryCode=collection.length%10==0?"(function(collection) {\n return (function(".concat(argsDefCode,") {\n for (var i = 0; i < collection.length; i += 10) {\n collection[i](").concat(argsDefCode,");\n collection[i+1](").concat(argsDefCode,");\n collection[i+2](").concat(argsDefCode,");\n collection[i+3](").concat(argsDefCode,");\n collection[i+4](").concat(argsDefCode,");\n collection[i+5](").concat(argsDefCode,");\n collection[i+6](").concat(argsDefCode,");\n collection[i+7](").concat(argsDefCode,");\n collection[i+8](").concat(argsDefCode,");\n collection[i+9](").concat(argsDefCode,");\n }\n });\n })"):collection.length%4==0?"(function(collection) {\n return (function(".concat(argsDefCode,") {\n for (var i = 0; i < collection.length; i += 4) {\n collection[i](").concat(argsDefCode,");\n collection[i+1](").concat(argsDefCode,");\n collection[i+2](").concat(argsDefCode,");\n collection[i+3](").concat(argsDefCode,");\n }\n });\n })"):collection.length%3==0?"(function(collection) {\n return (function(".concat(argsDefCode,") {\n for (var i = 0; i < collection.length; i += 3) {\n collection[i](").concat(argsDefCode,");\n collection[i+1](").concat(argsDefCode,");\n collection[i+2](").concat(argsDefCode,");\n }\n });\n })"):"(function(collection) {\n return (function(".concat(argsDefCode,") {\n for (var i = 0; i < collection.length; ++i) {\n collection[i](").concat(argsDefCode,");\n }\n });\n })")}var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}function bakeCollectionAwait(collection,fixedArgsNum){if(0===collection.length)return exports.BAKED_EMPTY_FUNC;if(1===collection.length)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) {\n ".concat(funcDefCode,"\n collection = undefined;\n return (function(").concat(argsDefCode,") {\n return Promise.all([ ").concat(funcCallCode," ]);\n });\n })")}else{var argsDefCode=generateArgsDefCode(fixedArgsNum);funcFactoryCode="(function(collection) {\n return (function(".concat(argsDefCode,") {\n var promises = Array(collection.length);\n for (var i = 0; i < collection.length; ++i) {\n promises[i] = collection[i](").concat(argsDefCode,");\n }\n return Promise.all(promises);\n });\n })")}var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}function bakeCollectionVariadic(collection){if(0===collection.length)return exports.BAKED_EMPTY_FUNC;if(1===collection.length)return collection[0];var funcFactoryCode;if(collection.length<FORLOOP_FALLBACK){var _a=generateBodyPartsVariadicCode(collection.length),funcDefCode=_a.funcDefCode,funcCallCode=_a.funcCallCode;funcFactoryCode="(function(collection) {\n ".concat(funcDefCode,"\n collection = undefined;\n return (function() {\n ").concat(funcCallCode,"\n });\n })")}else funcFactoryCode="(function(collection) {\n return (function() {\n for (var i = 0; i < collection.length; ++i) {\n collection[i].apply(undefined, arguments);\n }\n });\n })";var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}exports.bakeCollection=bakeCollection,exports.bakeCollectionAwait=bakeCollectionAwait,exports.bakeCollectionVariadic=bakeCollectionVariadic})(bakeCollection);var __spreadArray$1=commonjsGlobal&&commonjsGlobal.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var s,r=0,i=t.length;r<i;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))};Object.defineProperty(taskCollection,"__esModule",{value:!0}),taskCollection.TaskCollection=void 0;var utils_1$1=utils$1,bake_collection_1=bakeCollection;function push_norebuild(e,t){var n,s=this.length;if(s>1)t?((n=this._tasks).push.apply(n,arguments),this.length+=arguments.length):(this._tasks.push(e),this.length++);else if(t){var r;if(1===s)(r=Array(1+arguments.length)).push(r),r.push.apply(r,arguments),this._tasks=r;else(r=Array(arguments.length)).push.apply(r,arguments),this._tasks=r;this.length+=arguments.length}else this._tasks=1===s?[this._tasks,e]:e,this.length++}function push_rebuild(e,t){var n,s=this.length;if(s>1)t?((n=this._tasks).push.apply(n,arguments),this.length+=arguments.length):(this._tasks.push(e),this.length++);else if(t){var r;if(1===s)(r=Array(1+arguments.length)).push(r),r.push.apply(r,arguments),this._tasks=r;else(r=Array(arguments.length)).push.apply(r,arguments),this._tasks=r;this.length+=arguments.length}else this._tasks=1===s?[this._tasks,e]:e,this.length++;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function removeLast_norebuild(e){0!==this.length&&(1===this.length?this._tasks===e&&(this.length=0):((0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(e)),1===this._tasks.length?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length))}function removeLast_rebuild(e){if(0!==this.length){if(1===this.length)return this._tasks===e&&(this.length=0),this.firstEmitBuildStrategy?void(this.call=bake_collection_1.BAKED_EMPTY_FUNC):void this.rebuild();(0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(e)),1===this._tasks.length?(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(e){for(var t,n=[],s=1;s<arguments.length;s++)n[s-1]=arguments[s];0===this.length?(this._tasks=n,this.length=1):1===this.length?(n.unshift(this._tasks),this._tasks=n,this.length=this._tasks.length):((t=this._tasks).splice.apply(t,__spreadArray$1([e,0],n,!1)),this.length=this._tasks.length)}function insert_rebuild(e){for(var t,n=[],s=1;s<arguments.length;s++)n[s-1]=arguments[s];0===this.length?(this._tasks=n,this.length=1):1===this.length?(n.unshift(this._tasks),this._tasks=n,this.length=this._tasks.length):((t=this._tasks).splice.apply(t,__spreadArray$1([e,0],n,!1)),this.length=this._tasks.length),this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function rebuild_noawait(){0===this.length?this.call=bake_collection_1.BAKED_EMPTY_FUNC:1===this.length?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollection)(this._tasks,this.argsNum)}function rebuild_await(){0===this.length?this.call=bake_collection_1.BAKED_EMPTY_FUNC:1===this.length?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(e,t,n,s){void 0===t&&(t=!0),void 0===n&&(n=null),void 0===s&&(s=!1),this.awaitTasks=s,this.call=bake_collection_1.BAKED_EMPTY_FUNC,this.argsNum=e,this.firstEmitBuildStrategy=!0,this.rebuild=s?rebuild_await.bind(this):rebuild_noawait.bind(this),this.setAutoRebuild(t),n?"function"==typeof n?(this._tasks=n,this.length=1):(this._tasks=n,this.length=n.length):(this._tasks=null,this.length=0),t&&this.rebuild()},exports,__createBinding,__exportStar;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(e){this.argsNum<e&&(this.argsNum=e,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}function setAutoRebuild(e){e?(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 0===this.length?[]:1===this.length?[this._tasks]:this._tasks}function setTasks(e){0===e.length?(this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC):1===e.length?(this.length=1,this.call=e[0],this._tasks=e[0]):(this.length=e.length,this._tasks=e,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}taskCollection.TaskCollection=TaskCollection,TaskCollection.prototype.fastClear=fastClear,TaskCollection.prototype.clear=clear,TaskCollection.prototype.growArgsNum=growArgsNum,TaskCollection.prototype.setAutoRebuild=setAutoRebuild,TaskCollection.prototype.tasksAsArray=tasksAsArray,TaskCollection.prototype.setTasks=setTasks,exports=taskCollection$1,__createBinding=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,r)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),__exportStar=commonjsGlobal&&commonjsGlobal.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||__createBinding(t,e,n)},Object.defineProperty(exports,"__esModule",{value:!0}),__exportStar(taskCollection,exports);var utils={};function nullObj(){var e={__proto__:null};return e}Object.defineProperty(utils,"__esModule",{value:!0}),utils.nullObj=void 0,utils.nullObj=nullObj;var __spreadArray=commonjsGlobal&&commonjsGlobal.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var s,r=0,i=t.length;r<i;r++)!s&&r in t||(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))};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(e,t,n,s,r,i){var o=this.events[e];if(o){if(0===o.length)return!1;if(o.argsNum<6)o.call(t,n,s,r,i);else{for(var a=new Array(o.argsNum),c=0,l=a.length;c<l;++c)a[c]=arguments[c+1];o.call.apply(void 0,a)}return!0}return!1}function emitHasOnce(e,t,n,s,r,i){var o,a=this.events[e];if(void 0!==a){if(0===a.length)return!1;if(a.argsNum<6)a.call(t,n,s,r,i);else{for(var c=0,l=(o=new Array(a.argsNum)).length;c<l;++c)o[c]=arguments[c+1];a.call.apply(void 0,o)}}var u=this.onceEvents[e];if(u){if("function"==typeof u)if(this.onceEvents[e]=void 0,arguments.length<6)u(t,n,s,r,i);else{if(void 0===o)for(c=0,l=(o=new Array(arguments.length-1)).length;c<l;++c)o[c]=arguments[c+1];u.apply(void 0,o)}else{var d=u;if(this.onceEvents[e]=void 0,arguments.length<6)for(c=0;c<d.length;++c)d[c](t,n,s,r,i);else{if(void 0===o)for(c=0,l=(o=new Array(arguments.length-1)).length;c<l;++c)o[c]=arguments[c+1];for(c=0;c<d.length;++c)d[c].apply(void 0,o)}}return!0}return void 0!==a}var EventEmitter=function(){function e(){this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set,this.maxListeners=1/0}return Object.defineProperty(e.prototype,"_eventsCount",{get:function(){return this.eventNames().length},enumerable:!1,configurable:!0}),e}();function once(e,t){switch(this.emit===emit&&(this.emit=emitHasOnce),typeof this.onceEvents[e]){case"undefined":this.onceEvents[e]=t,"symbol"==typeof e&&this._symbolKeys.add(e);break;case"function":this.onceEvents[e]=[this.onceEvents[e],t];break;case"object":this.onceEvents[e].push(t)}return this}function addListener(e,t,n){if(void 0===n&&(n=t.length),"function"!=typeof t)throw new TypeError("The listener must be a function");var s=this.events[e];return s?(s.push(t),s.growArgsNum(n),this.maxListeners!==1/0&&this.maxListeners<=s.length&&console.warn('Maximum event listeners for "'.concat(String(e),'" event!'))):(this.events[e]=new task_collection_1.TaskCollection(n,!0,t,!1),"symbol"==typeof e&&this._symbolKeys.add(e)),this}function removeListener(e,t){var n=this.events[e];n&&n.removeLast(t);var s=this.onceEvents[e];return s&&("function"==typeof s?this.onceEvents[e]=void 0:"object"==typeof s&&(1===s.length&&s[0]===t?this.onceEvents[e]=void 0:(0,utils_1._fast_remove_single)(s,s.lastIndexOf(t)))),this}function addListenerBound(e,t,n,s){void 0===n&&(n=this),void 0===s&&(s=t.length),this.boundFuncs||(this.boundFuncs=new Map);var r=t.bind(n);return this.boundFuncs.set(t,r),this.addListener(e,r,s)}function removeListenerBound(e,t){var n,s,r=null===(n=this.boundFuncs)||void 0===n?void 0:n.get(t);return null===(s=this.boundFuncs)||void 0===s||s.delete(t),this.removeListener(e,r)}function hasListeners(e){return this.events[e]&&!!this.events[e].length}function prependListener(e,t,n){if(void 0===n&&(n=t.length),"function"!=typeof t)throw new TypeError("The listener must be a function");var s=this.events[e];return s&&s instanceof task_collection_1.TaskCollection?(s.insert(0,t),s.growArgsNum(n),this.maxListeners!==1/0&&this.maxListeners<=s.length&&console.warn('Maximum event listeners for "'.concat(String(e),'" event!'))):(s=this.events[e]=new task_collection_1.TaskCollection(n,!0,t,!1),"symbol"==typeof e&&this._symbolKeys.add(e)),this}function prependOnceListener(e,t){this.emit===emit&&(this.emit=emitHasOnce);var n=this.onceEvents[e];return n?"object"!=typeof n?(this.onceEvents[e]=[t,n],"symbol"==typeof e&&this._symbolKeys.add(e)):(n.unshift(t),this.maxListeners!==1/0&&this.maxListeners<=n.length&&console.warn('Maximum event listeners for "'.concat(String(e),'" once event!'))):(this.onceEvents[e]=[t],"symbol"==typeof e&&this._symbolKeys.add(e)),this}function removeAllListeners(e){return void 0===e?(this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set):(this.events[e]=void 0,this.onceEvents[e]=void 0,"symbol"==typeof e&&this._symbolKeys.delete(e)),this}function setMaxListeners(e){return this.maxListeners=e,this}function getMaxListeners(){return this.maxListeners}function listeners(e){return this.emit===emit?this.events[e]?this.events[e].tasksAsArray().slice():[]:this.events[e]&&this.onceEvents[e]?__spreadArray(__spreadArray([],this.events[e].tasksAsArray(),!0),"function"==typeof this.onceEvents[e]?[this.onceEvents[e]]:this.onceEvents[e],!0):this.events[e]?this.events[e].tasksAsArray():this.onceEvents[e]?"function"==typeof this.onceEvents[e]?[this.onceEvents[e]]:this.onceEvents[e]:[]}function eventNames(){var e=this;if(this.emit===emit){var t=Object.keys(this.events);return __spreadArray(__spreadArray([],t,!0),Array.from(this._symbolKeys),!0).filter(function(t){return t in e.events&&e.events[t]&&e.events[t].length})}t=Object.keys(this.events).filter(function(t){return e.events[t]&&e.events[t].length});var n=Object.keys(this.onceEvents).filter(function(t){return e.onceEvents[t]&&e.onceEvents[t].length});return __spreadArray(__spreadArray(__spreadArray([],t,!0),n,!0),Array.from(this._symbolKeys).filter(function(t){return t in e.events&&e.events[t]&&e.events[t].length||t in e.onceEvents&&e.onceEvents[t]&&e.onceEvents[t].length}),!0)}function listenerCount(e){return this.emit===emit?this.events[e]&&this.events[e].length||0:(this.events[e]&&this.events[e].length||0)+(this.onceEvents[e]&&this.onceEvents[e].length||0)}ee.EventEmitter=EventEmitter,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(e){var t=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,r)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),n=commonjsGlobal&&commonjsGlobal.__exportStar||function(e,n){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(n,s)||t(n,e,s)};Object.defineProperty(e,"__esModule",{value:!0}),n(types,e),n(ee,e)}(lib$1);var browser={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var e=1e3,t=60*e,n=60*t,s=24*n,r=7*s,i=365.25*s;function o(e,t,n,s){var r=t>=1.5*n;return Math.round(e/n)+" "+s+(r?"s":"")}return ms=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(o){if((o=String(o)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(o);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*i;case"weeks":case"week":case"w":return c*r;case"days":case"day":case"d":return c*s;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(r){var i=Math.abs(r);if(i>=s)return o(r,i,s,"day");if(i>=n)return o(r,i,n,"hour");if(i>=t)return o(r,i,t,"minute");if(i>=e)return o(r,i,e,"second");return r+" ms"}(a):function(r){var i=Math.abs(r);if(i>=s)return Math.round(r/s)+"d";if(i>=n)return Math.round(r/n)+"h";if(i>=t)return Math.round(r/t)+"m";if(i>=e)return Math.round(r/e)+"s";return r+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}function setup(e){function t(e){let s,r,i,o=null;function a(...e){if(!a.enabled)return;const n=a,r=Number(new Date),i=r-(s||r);n.diff=i,n.prev=s,n.curr=r,s=r,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(s,r)=>{if("%%"===s)return"%";o++;const i=t.formatters[r];if("function"==typeof i){const t=e[o];s=i.call(n,t),e.splice(o,1),o--}return s}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(r!==t.namespaces&&(r=t.namespaces,i=t.enabled(e)),i),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const s=t(this.namespace+(void 0===n?":":n)+e);return s.log=this.log,s}function s(e,t){let n=0,s=0,r=-1,i=0;for(;n<e.length;)if(s<t.length&&(t[s]===e[n]||"*"===t[s]))"*"===t[s]?(r=s,i=n,s++):(n++,s++);else{if(-1===r)return!1;s=r+1,i++,n=i}for(;s<t.length&&"*"===t[s];)s++;return s===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of n)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const n of t.skips)if(s(e,n))return!1;for(const n of t.names)if(s(e,n))return!0;return!1},t.humanize=requireMs(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}var common=setup;!function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,r=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(s++,"%c"===e&&(r=s))}),t.splice(r,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=common(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(browser,browser.exports);var browserExports=browser.exports,createDebug5=getDefaultExportFromCjs(browserExports);function number$2(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bytes$2(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash$1(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(e.outputLen),number$2(e.blockLen)}function exists$2(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output$2(e,t){bytes$2(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const crypto$2="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,u8a$2=e=>e instanceof Uint8Array,createView$3=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr$2=(e,t)=>e<<32-t|e>>>t,isLE$2=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!isLE$2)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$4(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes$3(e){if("string"==typeof e&&(e=utf8ToBytes$4(e)),!u8a$2(e))throw new Error("expected Uint8Array, got "+typeof e);return e}function concatBytes$3(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;return e.forEach(e=>{if(!u8a$2(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t}let Hash$2=class{clone(){return this._cloneInto()}};function wrapConstructor$1(e){const t=t=>e().update(toBytes$3(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function randomBytes$2(e=32){if(crypto$2&&"function"==typeof crypto$2.getRandomValues)return crypto$2.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$3(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),o=Number(n>>r&i),a=Number(n&i),c=s?4:0,l=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+l,a,s)}let SHA2$1=class extends Hash$2{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$3(this.buffer)}update(e){exists$2(this);const{view:t,buffer:n,blockLen:s}=this,r=(e=toBytes$3(e)).length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);if(o===s){const t=createView$3(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){exists$2(this),output$2(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let e=i;e<s;e++)t[e]=0;setBigUint64$3(n,s-8,BigInt(8*this.length),r),this.process(n,0);const o=createView$3(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:i,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=i,s%t&&e.buffer.set(n),e}};const Chi$2=(e,t,n)=>e&t^~e&n,Maj$2=(e,t,n)=>e&t^e&n^t&n,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=0|IV$1[0],this.B=0|IV$1[1],this.C=0|IV$1[2],this.D=0|IV$1[3],this.E=0|IV$1[4],this.F=0|IV$1[5],this.G=0|IV$1[6],this.H=0|IV$1[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:i,G:o,H:a}=this;return[e,t,n,s,r,i,o,a]}set(e,t,n,s,r,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|r,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W$2[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=SHA256_W$2[e-15],n=SHA256_W$2[e-2],s=rotr$2(t,7)^rotr$2(t,18)^t>>>3,r=rotr$2(n,17)^rotr$2(n,19)^n>>>10;SHA256_W$2[e]=r+SHA256_W$2[e-7]+s+SHA256_W$2[e-16]|0}let{A:n,B:s,C:r,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(rotr$2(o,6)^rotr$2(o,11)^rotr$2(o,25))+Chi$2(o,a,c)+SHA256_K$2[e]+SHA256_W$2[e]|0,u=(rotr$2(n,2)^rotr$2(n,13)^rotr$2(n,22))+Maj$2(n,s,r)|0;l=c,c=a,a=o,o=i+t|0,i=r,r=s,s=n,n=t+u|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,r,i,o,a,c,l)}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),_0n$9=BigInt(0),_1n$9=BigInt(1),_2n$5=BigInt(2),u8a$1=e=>e instanceof Uint8Array,hexes$2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bytesToHex$2(e){if(!u8a$1(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=hexes$2[e[n]];return t}function numberToHexUnpadded$1(e){const t=e.toString(16);return 1&t.length?`0${t}`:t}function hexToNumber$1(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return BigInt(""===e?"0":`0x${e}`)}function hexToBytes$2(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){const s=2*t,r=e.slice(s,s+2),i=Number.parseInt(r,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[t]=i}return n}function bytesToNumberBE$1(e){return hexToNumber$1(bytesToHex$2(e))}function bytesToNumberLE$1(e){if(!u8a$1(e))throw new Error("Uint8Array expected");return hexToNumber$1(bytesToHex$2(Uint8Array.from(e).reverse()))}function numberToBytesBE$1(e,t){return hexToBytes$2(e.toString(16).padStart(2*t,"0"))}function numberToBytesLE$1(e,t){return numberToBytesBE$1(e,t).reverse()}function numberToVarBytesBE(e){return hexToBytes$2(numberToHexUnpadded$1(e))}function ensureBytes$1(e,t,n){let s;if("string"==typeof t)try{s=hexToBytes$2(t)}catch(n){throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${n}`)}else{if(!u8a$1(t))throw new Error(`${e} must be hex string or Uint8Array`);s=Uint8Array.from(t)}const r=s.length;if("number"==typeof n&&r!==n)throw new Error(`${e} expected ${n} bytes, got ${r}`);return s}function concatBytes$2(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;return e.forEach(e=>{if(!u8a$1(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t}function equalBytes$1(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function utf8ToBytes$3(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function bitLen$1(e){let t;for(t=0;e>_0n$9;e>>=_1n$9,t+=1);return t}function bitGet(e,t){return e>>BigInt(t)&_1n$9}const bitSet=(e,t,n)=>e|(n?_1n$9:_0n$9)<<BigInt(t),bitMask$1=e=>(_2n$5<<BigInt(e-1))-_1n$9,u8n=e=>new Uint8Array(e),u8fr=e=>Uint8Array.from(e);function createHmacDrbg$1(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let s=u8n(e),r=u8n(e),i=0;const o=()=>{s.fill(1),r.fill(0),i=0},a=(...e)=>n(r,s,...e),c=(e=u8n())=>{r=a(u8fr([0]),e),s=a(),0!==e.length&&(r=a(u8fr([1]),e),s=a())},l=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){s=a();const t=s.slice();n.push(t),e+=s.length}return concatBytes$2(...n)};return(e,t)=>{let n;for(o(),c(e);!(n=t(l()));)c();return o(),n}}const validatorFns={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||e instanceof Uint8Array,isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function validateObject(e,t,n={}){const s=(t,n,s)=>{const r=validatorFns[n];if("function"!=typeof r)throw new Error(`Invalid validator "${n}", expected function`);const i=e[t];if(!(s&&void 0===i||r(i,e)))throw new Error(`Invalid param ${String(t)}=${i} (${typeof i}), expected ${n}`)};for(const[e,n]of Object.entries(t))s(e,n,!1);for(const[e,t]of Object.entries(n))s(e,t,!0);return e}var ut=Object.freeze({__proto__:null,bitGet:bitGet,bitLen:bitLen$1,bitMask:bitMask$1,bitSet: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:numberToVarBytesBE,utf8ToBytes:utf8ToBytes$3,validateObject:validateObject});
/*! 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);function mod$1(e,t){const n=e%t;return n>=_0n$8?n:t+n}function pow(e,t,n){if(n<=_0n$8||t<_0n$8)throw new Error("Expected power/modulo > 0");if(n===_1n$8)return _0n$8;let s=_1n$8;for(;t>_0n$8;)t&_1n$8&&(s=s*e%n),e=e*e%n,t>>=_1n$8;return s}function pow2$1(e,t,n){let s=e;for(;t-- >_0n$8;)s*=s,s%=n;return s}function invert$1(e,t){if(e===_0n$8||t<=_0n$8)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let n=mod$1(e,t),s=t,r=_0n$8,i=_1n$8;for(;n!==_0n$8;){const e=s%n,t=r-i*(s/n);s=n,n=e,r=i,i=t}if(s!==_1n$8)throw new Error("invert: does not exist");return mod$1(r,t)}function tonelliShanks$1(e){const t=(e-_1n$8)/_2n$4;let n,s,r;for(n=e-_1n$8,s=0;n%_2n$4===_0n$8;n/=_2n$4,s++);for(r=_2n$4;r<e&&pow(r,t,e)!==e-_1n$8;r++);if(1===s){const t=(e+_1n$8)/_4n$2;return function(e,n){const s=e.pow(n,t);if(!e.eql(e.sqr(s),n))throw new Error("Cannot find square root");return s}}const i=(n+_1n$8)/_2n$4;return function(e,o){if(e.pow(o,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=s,c=e.pow(e.mul(e.ONE,r),n),l=e.pow(o,i),u=e.pow(o,n);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let n=e.sqr(u);t<a&&!e.eql(n,e.ONE);t++)n=e.sqr(n);const n=e.pow(c,_1n$8<<BigInt(a-t-1));c=e.sqr(n),l=e.mul(l,n),u=e.mul(u,c),a=t}return l}}function FpSqrt$1(e){if(e%_4n$2===_3n$3){const t=(e+_1n$8)/_4n$2;return function(e,n){const s=e.pow(n,t);if(!e.eql(e.sqr(s),n))throw new Error("Cannot find square root");return s}}if(e%_8n$1===_5n$1){const t=(e-_5n$1)/_8n$1;return function(e,n){const s=e.mul(n,_2n$4),r=e.pow(s,t),i=e.mul(n,r),o=e.mul(e.mul(i,_2n$4),r),a=e.mul(i,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),n))throw new Error("Cannot find square root");return a}}return tonelliShanks$1(e)}BigInt(9),BigInt(16);const FIELD_FIELDS$1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField$1(e){return validateObject(e,FIELD_FIELDS$1.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}))}function FpPow$1(e,t,n){if(n<_0n$8)throw new Error("Expected power > 0");if(n===_0n$8)return e.ONE;if(n===_1n$8)return t;let s=e.ONE,r=t;for(;n>_0n$8;)n&_1n$8&&(s=e.mul(s,r)),r=e.sqr(r),n>>=_1n$8;return s}function FpInvertBatch$1(e,t){const n=new Array(t.length),s=t.reduce((t,s,r)=>e.is0(s)?t:(n[r]=t,e.mul(t,s)),e.ONE),r=e.inv(s);return t.reduceRight((t,s,r)=>e.is0(s)?t:(n[r]=e.mul(t,n[r]),e.mul(t,s)),r),n}function nLength$1(e,t){const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Field$1(e,t,n=!1,s={}){if(e<=_0n$8)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:r,nByteLength:i}=nLength$1(e,t);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const o=FpSqrt$1(e),a=Object.freeze({ORDER:e,BITS:r,BYTES:i,MASK:bitMask$1(r),ZERO:_0n$8,ONE:_1n$8,create:t=>mod$1(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return _0n$8<=t&&t<e},is0:e=>e===_0n$8,isOdd:e=>(e&_1n$8)===_1n$8,neg:t=>mod$1(-t,e),eql:(e,t)=>e===t,sqr:t=>mod$1(t*t,e),add:(t,n)=>mod$1(t+n,e),sub:(t,n)=>mod$1(t-n,e),mul:(t,n)=>mod$1(t*n,e),pow:(e,t)=>FpPow$1(a,e,t),div:(t,n)=>mod$1(t*invert$1(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>invert$1(t,e),sqrt:s.sqrt||(e=>o(a,e)),invertBatch:e=>FpInvertBatch$1(a,e),cmov:(e,t,n)=>n?t:e,toBytes:e=>n?numberToBytesLE$1(e,i):numberToBytesBE$1(e,i),fromBytes:e=>{if(e.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${e.length}`);return n?bytesToNumberLE$1(e):bytesToNumberBE$1(e)}});return Object.freeze(a)}function getFieldBytesLength$1(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength$1(e){const t=getFieldBytesLength$1(e);return t+Math.ceil(t/2)}function mapHashToField$1(e,t,n=!1){const s=e.length,r=getFieldBytesLength$1(t),i=getMinHashLength$1(t);if(s<16||s<i||s>1024)throw new Error(`expected ${i}-1024 bytes of input, got ${s}`);const o=mod$1(n?bytesToNumberBE$1(e):bytesToNumberLE$1(e),t-_1n$8)+_1n$8;return n?numberToBytesLE$1(o,r):numberToBytesBE$1(o,r)}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$7=BigInt(0),_1n$7=BigInt(1);function wNAF$1(e,t){const n=(e,t)=>{const n=t.negate();return e?n:t},s=e=>({windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:n,unsafeLadder(t,n){let s=e.ZERO,r=t;for(;n>_0n$7;)n&_1n$7&&(s=s.add(r)),r=r.double(),n>>=_1n$7;return s},precomputeWindow(e,t){const{windows:n,windowSize:r}=s(t),i=[];let o=e,a=o;for(let e=0;e<n;e++){a=o,i.push(a);for(let e=1;e<r;e++)a=a.add(o),i.push(a);o=a.double()}return i},wNAF(t,r,i){const{windows:o,windowSize:a}=s(t);let c=e.ZERO,l=e.BASE;const u=BigInt(2**t-1),d=2**t,h=BigInt(t);for(let e=0;e<o;e++){const t=e*a;let s=Number(i&u);i>>=h,s>a&&(s-=d,i+=_1n$7);const o=t,p=t+Math.abs(s)-1,f=e%2!=0,g=s<0;0===s?l=l.add(n(f,r[o])):c=c.add(n(g,r[p]))}return{p:c,f:l}},wNAFCached(e,t,n,s){const r=e._WINDOW_SIZE||1;let i=t.get(e);return i||(i=this.precomputeWindow(e,r),1!==r&&t.set(e,s(i))),this.wNAF(r,i,n)}}}function validateBasic(e){return validateField$1(e.Fp),validateObject(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength$1(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts(e){const t=validateBasic(e);validateObject(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:s,a:r}=t;if(n){if(!s.eql(r,s.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut,DER$1={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(e){const{Err:t}=DER$1;if(e.length<2||2!==e[0])throw new t("Invalid signature integer tag");const n=e[1],s=e.subarray(2,n+2);if(!n||s.length!==n)throw new t("Invalid signature integer: wrong length");if(128&s[0])throw new t("Invalid signature integer: negative");if(0===s[0]&&!(128&s[1]))throw new t("Invalid signature integer: unnecessary leading zero");return{d:b2n(s),l:e.subarray(n+2)}},toSig(e){const{Err:t}=DER$1,n="string"==typeof e?h2b(e):e;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let s=n.length;if(s<2||48!=n[0])throw new t("Invalid signature tag");if(n[1]!==s-2)throw new t("Invalid signature: incorrect length");const{d:r,l:i}=DER$1._parseInt(n.subarray(2)),{d:o,l:a}=DER$1._parseInt(i);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:r,s:o}},hexFromSig(e){const t=e=>8&Number.parseInt(e[0],16)?"00"+e:e,n=e=>{const t=e.toString(16);return 1&t.length?`0${t}`:t},s=t(n(e.s)),r=t(n(e.r)),i=s.length/2,o=r.length/2,a=n(i),c=n(o);return`30${n(o+i+4)}02${c}${r}02${a}${s}`}},_0n$6=BigInt(0),_1n$6=BigInt(1);BigInt(2);const _3n$2=BigInt(3);function weierstrassPoints(e){const t=validatePointOpts(e),{Fp:n}=t,s=t.toBytes||((e,t,s)=>{const r=t.toAffine();return concatBytes$2(Uint8Array.from([4]),n.toBytes(r.x),n.toBytes(r.y))}),r=t.fromBytes||(e=>{const t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function i(e){const{a:s,b:r}=t,i=n.sqr(e),o=n.mul(i,e);return n.add(n.add(o,n.mul(e,s)),r)}if(!n.eql(n.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function o(e){return"bigint"==typeof e&&_0n$6<e&&e<t.n}function a(e){if(!o(e))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(e){const{allowedPrivateKeyLengths:n,nByteLength:s,wrapPrivateKey:r,n:i}=t;if(n&&"bigint"!=typeof e){if(e instanceof Uint8Array&&(e=bytesToHex$2(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*s,"0")}let o;try{o="bigint"==typeof e?e:bytesToNumberBE$1(ensureBytes$1("private key",e,s))}catch(t){throw new Error(`private key must be ${s} bytes, hex or bigint, not ${typeof e}`)}return r&&(o=mod$1(o,i)),a(o),o}const l=new Map;function u(e){if(!(e instanceof d))throw new Error("ProjectivePoint expected")}class d{constructor(e,t,s){if(this.px=e,this.py=t,this.pz=s,null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t))throw new Error("y required");if(null==s||!n.isValid(s))throw new Error("z required")}static fromAffine(e){const{x:t,y:s}=e||{};if(!e||!n.isValid(t)||!n.isValid(s))throw new Error("invalid affine point");if(e instanceof d)throw new Error("projective point not allowed");const r=e=>n.eql(e,n.ZERO);return r(t)&&r(s)?d.ZERO:new d(t,s,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=n.invertBatch(e.map(e=>e.pz));return e.map((e,n)=>e.toAffine(t[n])).map(d.fromAffine)}static fromHex(e){const t=d.fromAffine(r(ensureBytes$1("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return d.BASE.multiply(c(e))}_setWindowSize(e){this._WINDOW_SIZE=e,l.delete(this)}assertValidity(){if(this.is0()){if(t.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:e,y:s}=this.toAffine();if(!n.isValid(e)||!n.isValid(s))throw new Error("bad point: x or y not FE");const r=n.sqr(s),o=i(e);if(!n.eql(r,o))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){u(e);const{px:t,py:s,pz:r}=this,{px:i,py:o,pz:a}=e,c=n.eql(n.mul(t,a),n.mul(i,r)),l=n.eql(n.mul(s,a),n.mul(o,r));return c&&l}negate(){return new d(this.px,n.neg(this.py),this.pz)}double(){const{a:e,b:s}=t,r=n.mul(s,_3n$2),{px:i,py:o,pz:a}=this;let c=n.ZERO,l=n.ZERO,u=n.ZERO,h=n.mul(i,i),p=n.mul(o,o),f=n.mul(a,a),g=n.mul(i,o);return g=n.add(g,g),u=n.mul(i,a),u=n.add(u,u),c=n.mul(e,u),l=n.mul(r,f),l=n.add(c,l),c=n.sub(p,l),l=n.add(p,l),l=n.mul(c,l),c=n.mul(g,c),u=n.mul(r,u),f=n.mul(e,f),g=n.sub(h,f),g=n.mul(e,g),g=n.add(g,u),u=n.add(h,h),h=n.add(u,h),h=n.add(h,f),h=n.mul(h,g),l=n.add(l,h),f=n.mul(o,a),f=n.add(f,f),h=n.mul(f,g),c=n.sub(c,h),u=n.mul(f,p),u=n.add(u,u),u=n.add(u,u),new d(c,l,u)}add(e){u(e);const{px:s,py:r,pz:i}=this,{px:o,py:a,pz:c}=e;let l=n.ZERO,h=n.ZERO,p=n.ZERO;const f=t.a,g=n.mul(t.b,_3n$2);let y=n.mul(s,o),m=n.mul(r,a),b=n.mul(i,c),v=n.add(s,r),_=n.add(o,a);v=n.mul(v,_),_=n.add(y,m),v=n.sub(v,_),_=n.add(s,i);let w=n.add(o,c);return _=n.mul(_,w),w=n.add(y,b),_=n.sub(_,w),w=n.add(r,i),l=n.add(a,c),w=n.mul(w,l),l=n.add(m,b),w=n.sub(w,l),p=n.mul(f,_),l=n.mul(g,b),p=n.add(l,p),l=n.sub(m,p),p=n.add(m,p),h=n.mul(l,p),m=n.add(y,y),m=n.add(m,y),b=n.mul(f,b),_=n.mul(g,_),m=n.add(m,b),b=n.sub(y,b),b=n.mul(f,b),_=n.add(_,b),y=n.mul(m,_),h=n.add(h,y),y=n.mul(w,_),l=n.mul(v,l),l=n.sub(l,y),y=n.mul(v,m),p=n.mul(w,p),p=n.add(p,y),new d(l,h,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(d.ZERO)}wNAF(e){return p.wNAFCached(this,l,e,e=>{const t=n.invertBatch(e.map(e=>e.pz));return e.map((e,n)=>e.toAffine(t[n])).map(d.fromAffine)})}multiplyUnsafe(e){const s=d.ZERO;if(e===_0n$6)return s;if(a(e),e===_1n$6)return this;const{endo:r}=t;if(!r)return p.unsafeLadder(this,e);let{k1neg:i,k1:o,k2neg:c,k2:l}=r.splitScalar(e),u=s,h=s,f=this;for(;o>_0n$6||l>_0n$6;)o&_1n$6&&(u=u.add(f)),l&_1n$6&&(h=h.add(f)),f=f.double(),o>>=_1n$6,l>>=_1n$6;return i&&(u=u.negate()),c&&(h=h.negate()),h=new d(n.mul(h.px,r.beta),h.py,h.pz),u.add(h)}multiply(e){a(e);let s,r,i=e;const{endo:o}=t;if(o){const{k1neg:e,k1:t,k2neg:a,k2:c}=o.splitScalar(i);let{p:l,f:u}=this.wNAF(t),{p:h,f:f}=this.wNAF(c);l=p.constTimeNegate(e,l),h=p.constTimeNegate(a,h),h=new d(n.mul(h.px,o.beta),h.py,h.pz),s=l.add(h),r=u.add(f)}else{const{p:e,f:t}=this.wNAF(i);s=e,r=t}return d.normalizeZ([s,r])[0]}multiplyAndAddUnsafe(e,t,n){const s=d.BASE,r=(e,t)=>t!==_0n$6&&t!==_1n$6&&e.equals(s)?e.multiply(t):e.multiplyUnsafe(t),i=r(this,t).add(r(e,n));return i.is0()?void 0:i}toAffine(e){const{px:t,py:s,pz:r}=this,i=this.is0();null==e&&(e=i?n.ONE:n.inv(r));const o=n.mul(t,e),a=n.mul(s,e),c=n.mul(r,e);if(i)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:o,y:a}}isTorsionFree(){const{h:e,isTorsionFree:n}=t;if(e===_1n$6)return!0;if(n)return n(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:n}=t;return e===_1n$6?this:n?n(d,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return this.assertValidity(),s(d,this,e)}toHex(e=!0){return bytesToHex$2(this.toRawBytes(e))}}d.BASE=new d(t.Gx,t.Gy,n.ONE),d.ZERO=new d(n.ZERO,n.ONE,n.ZERO);const h=t.nBitLength,p=wNAF$1(d,t.endo?Math.ceil(h/2):h);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:o}}function validateOpts(e){const t=validateBasic(e);return validateObject(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function weierstrass$1(e){const t=validateOpts(e),{Fp:n,n:s}=t,r=n.BYTES+1,i=2*n.BYTES+1;function o(e){return mod$1(e,s)}function a(e){return invert$1(e,s)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:d}=weierstrassPoints({...t,toBytes(e,t,s){const r=t.toAffine(),i=n.toBytes(r.x),o=concatBytes$2;return s?o(Uint8Array.from([t.hasEvenY()?2:3]),i):o(Uint8Array.from([4]),i,n.toBytes(r.y))},fromBytes(e){const t=e.length,s=e[0],o=e.subarray(1);if(t!==r||2!==s&&3!==s){if(t===i&&4===s){return{x:n.fromBytes(o.subarray(0,n.BYTES)),y:n.fromBytes(o.subarray(n.BYTES,2*n.BYTES))}}throw new Error(`Point of length ${t} was invalid. Expected ${r} compressed bytes or ${i} uncompressed bytes`)}{const e=bytesToNumberBE$1(o);if(!function(e){return _0n$6<e&&e<n.ORDER}(e))throw new Error("Point is not on curve");const t=u(e);let r=n.sqrt(t);return!(1&~s)!==((r&_1n$6)===_1n$6)&&(r=n.neg(r)),{x:e,y:r}}}}),h=e=>bytesToHex$2(numberToBytesBE$1(e,t.nByteLength));function p(e){return e>s>>_1n$6}const f=(e,t,n)=>bytesToNumberBE$1(e.slice(t,n));class g{constructor(e,t,n){this.r=e,this.s=t,this.recovery=n,this.assertValidity()}static fromCompact(e){const n=t.nByteLength;return e=ensureBytes$1("compactSignature",e,2*n),new g(f(e,0,n),f(e,n,2*n))}static fromDER(e){const{r:t,s:n}=DER$1.toSig(ensureBytes$1("DER",e));return new g(t,n)}assertValidity(){if(!d(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!d(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:s,s:r,recovery:i}=this,l=v(ensureBytes$1("msgHash",e));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const u=2===i||3===i?s+t.n:s;if(u>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const d=1&i?"03":"02",p=c.fromHex(d+h(u)),f=a(u),g=o(-l*f),y=o(r*f),m=c.BASE.multiplyAndAddUnsafe(p,g,y);if(!m)throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-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 h(this.r)+h(this.s)}}const y={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=getMinHashLength$1(t.n);return mapHashToField$1(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){const t=e instanceof Uint8Array,n="string"==typeof e,s=(t||n)&&e.length;return t?s===r||s===i:n?s===2*r||s===2*i:e instanceof c}const b=t.bits2int||function(e){const n=bytesToNumberBE$1(e),s=8*e.length-t.nBitLength;return s>0?n>>BigInt(s):n},v=t.bits2int_modN||function(e){return o(b(e))},_=bitMask$1(t.nBitLength);function w(e){if("bigint"!=typeof e)throw new Error("bigint expected");if(!(_0n$6<=e&&e<_))throw new Error(`bigint expected < 2^${t.nBitLength}`);return numberToBytesBE$1(e,t.nByteLength)}function k(e,s,r=E){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:u}=t;let{lowS:h,prehash:f,extraEntropy:y}=r;null==h&&(h=!0),e=ensureBytes$1("msgHash",e),f&&(e=ensureBytes$1("prehashed msgHash",i(e)));const m=v(e),_=l(s),k=[w(_),w(m)];if(null!=y){const e=!0===y?u(n.BYTES):y;k.push(ensureBytes$1("extraEntropy",e))}const x=concatBytes$2(...k),$=m;return{seed:x,k2sig:function(e){const t=b(e);if(!d(t))return;const n=a(t),s=c.BASE.multiply(t).toAffine(),r=o(s.x);if(r===_0n$6)return;const i=o(n*o($+r*_));if(i===_0n$6)return;let l=(s.x===r?0:2)|Number(s.y&_1n$6),u=i;return h&&p(i)&&(u=function(e){return p(e)?o(-e):e}(i),l^=1),new g(r,u,l)}}}const E={lowS:t.lowS,prehash:!1},x={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,n=!0){if(m(e))throw new Error("first arg must be private key");if(!m(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(n)},sign:function(e,n,s=E){const{seed:r,k2sig:i}=k(e,n,s),o=t;return createHmacDrbg$1(o.hash.outputLen,o.nByteLength,o.hmac)(r,i)},verify:function(e,n,s,r=x){const i=e;if(n=ensureBytes$1("msgHash",n),s=ensureBytes$1("publicKey",s),"strict"in r)throw new Error("options.strict was renamed to lowS");const{lowS:l,prehash:u}=r;let d,h;try{if("string"==typeof i||i instanceof Uint8Array)try{d=g.fromDER(i)}catch(e){if(!(e instanceof DER$1.Err))throw e;d=g.fromCompact(i)}else{if("object"!=typeof i||"bigint"!=typeof i.r||"bigint"!=typeof i.s)throw new Error("PARSE");{const{r:e,s:t}=i;d=new g(e,t)}}h=c.fromHex(s)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(l&&d.hasHighS())return!1;u&&(n=t.hash(n));const{r:p,s:f}=d,y=v(n),m=a(f),b=o(y*m),_=o(p*m),w=c.BASE.multiplyAndAddUnsafe(h,b,_)?.toAffine();return!!w&&o(w.x)===p},ProjectivePoint:c,Signature:g,utils:y}}BigInt(4);let HMAC$2=class extends Hash$2{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hash$1(e);const n=toBytes$3(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(n.length>s?e.create().update(n).digest():n);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),r.fill(0)}update(e){return exists$2(this),this.iHash.update(e),this}digestInto(e){exists$2(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:n,finished:s,destroyed:r,blockLen:i,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$2=(e,t,n)=>new HMAC$2(e,t).update(n).digest();
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function getHash(e){return{hash:e,hmac:(t,...n)=>hmac$2(e,t,concatBytes$3(...n)),randomBytes:randomBytes$2}}function createCurve$1(e,t){const n=t=>weierstrass$1({...e,...getHash(t)});return Object.freeze({...n(t),create:n})}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */hmac$2.create=(e,t)=>new HMAC$2(e,t);const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$5=BigInt(1),_2n$3=BigInt(2),divNearest$1=(e,t)=>(e+t/_2n$3)/t;function sqrtMod$1(e){const t=secp256k1P,n=BigInt(3),s=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=pow2$1(u,n,t)*u%t,h=pow2$1(d,n,t)*u%t,p=pow2$1(h,_2n$3,t)*l%t,f=pow2$1(p,r,t)*p%t,g=pow2$1(f,i,t)*f%t,y=pow2$1(g,a,t)*g%t,m=pow2$1(y,c,t)*y%t,b=pow2$1(m,a,t)*g%t,v=pow2$1(b,n,t)*u%t,_=pow2$1(v,o,t)*f%t,w=pow2$1(_,s,t)*l%t,k=pow2$1(w,_2n$3,t);if(!Fp.eql(Fp.sqr(k),e))throw new Error("Cannot find square root");return k}const Fp=Field$1(secp256k1P,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1$1=createCurve$1({a:BigInt(0),b:BigInt(7),Fp:Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=secp256k1N,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),s=-_1n$5*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),r=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=divNearest$1(i*e,t),c=divNearest$1(-s*e,t);let l=mod$1(e-a*n-c*r,t),u=mod$1(-a*s-c*i,t);const d=l>o,h=u>o;if(d&&(l=t-l),h&&(u=t-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}}},sha256$3),_0n$5=BigInt(0),fe=e=>"bigint"==typeof e&&_0n$5<e&&e<secp256k1P,ge=e=>"bigint"==typeof e&&_0n$5<e&&e<secp256k1N,TAGGED_HASH_PREFIXES$1={};function taggedHash$1(e,...t){let n=TAGGED_HASH_PREFIXES$1[e];if(void 0===n){const t=sha256$3(Uint8Array.from(e,e=>e.charCodeAt(0)));n=concatBytes$2(t,t),TAGGED_HASH_PREFIXES$1[e]=n}return sha256$3(concatBytes$2(n,...t))}const pointToBytes$1=e=>e.toRawBytes(!0).slice(1),numTo32b=e=>numberToBytesBE$1(e,32),modP=e=>mod$1(e,secp256k1P),modN=e=>mod$1(e,secp256k1N),Point=secp256k1$1.ProjectivePoint,GmulAdd=(e,t,n)=>Point.BASE.multiplyAndAddUnsafe(e,t,n);function schnorrGetExtPubKey$1(e){let t=secp256k1$1.utils.normPrivateKeyToScalar(e),n=Point.fromPrivateKey(t);return{scalar:n.hasEvenY()?t:modN(-t),bytes:pointToBytes$1(n)}}function lift_x$1(e){if(!fe(e))throw new Error("bad x: need 0 < x < p");const t=modP(e*e);let n=sqrtMod$1(modP(t*e+BigInt(7)));n%_2n$3!==_0n$5&&(n=modP(-n));const s=new Point(e,n,_1n$5);return s.assertValidity(),s}function challenge$1(...e){return modN(bytesToNumberBE$1(taggedHash$1("BIP0340/challenge",...e)))}function schnorrGetPublicKey$1(e){return schnorrGetExtPubKey$1(e).bytes}function schnorrSign$1(e,t,n=randomBytes$2(32)){const s=ensureBytes$1("message",e),{bytes:r,scalar:i}=schnorrGetExtPubKey$1(t),o=ensureBytes$1("auxRand",n,32),a=numTo32b(i^bytesToNumberBE$1(taggedHash$1("BIP0340/aux",o))),c=taggedHash$1("BIP0340/nonce",a,r,s),l=modN(bytesToNumberBE$1(c));if(l===_0n$5)throw new Error("sign failed: k is zero");const{bytes:u,scalar:d}=schnorrGetExtPubKey$1(l),h=challenge$1(u,r,s),p=new Uint8Array(64);if(p.set(u,0),p.set(numTo32b(modN(d+h*i)),32),!schnorrVerify$1(p,s,r))throw new Error("sign: Invalid signature produced");return p}function schnorrVerify$1(e,t,n){const s=ensureBytes$1("signature",e,64),r=ensureBytes$1("message",t),i=ensureBytes$1("publicKey",n,32);try{const e=lift_x$1(bytesToNumberBE$1(i)),t=bytesToNumberBE$1(s.subarray(0,32));if(!fe(t))return!1;const n=bytesToNumberBE$1(s.subarray(32,64));if(!ge(n))return!1;const o=challenge$1(numTo32b(t),pointToBytes$1(e),r),a=GmulAdd(e,n,modN(-o));return!(!a||!a.hasEvenY()||a.toAffine().x!==t)}catch(e){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="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,u8a=e=>e instanceof Uint8Array,u32$1=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView$2=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr$1=(e,t)=>e<<32-t|e>>>t,isLE$1=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE$1)throw new Error("Non little-endian hardware is not supported");const hexes$1=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex$1(e){if(!u8a(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=hexes$1[e[n]];return t}function hexToBytes$1(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(t/2);for(let t=0;t<n.length;t++){const s=2*t,r=e.slice(s,s+2),i=Number.parseInt(r,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[t]=i}return n}function utf8ToBytes$2(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes$2(e){if("string"==typeof e&&(e=utf8ToBytes$2(e)),!u8a(e))throw new Error("expected Uint8Array, got "+typeof e);return e}function concatBytes$1(...e){const t=new Uint8Array(e.reduce((e,t)=>e+t.length,0));let n=0;return e.forEach(e=>{if(!u8a(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t}let Hash$1=class{clone(){return this._cloneInto()}};const isPlainObject=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function checkOpts$1(e,t){if(void 0!==t&&("object"!=typeof t||!isPlainObject(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}function wrapConstructor(e){const t=t=>e().update(toBytes$2(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function randomBytes$1(e=32){if(crypto$1&&"function"==typeof crypto$1.getRandomValues)return crypto$1.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}function number$1(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool$1(e){if("boolean"!=typeof e)throw new Error(`Expected boolean, not ${e}`)}function bytes$1(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}function hash(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");number$1(e.outputLen),number$1(e.blockLen)}function exists$1(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output$1(e,t){bytes$1(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}const assert={number:number$1,bool:bool$1,bytes:bytes$1,hash:hash,exists:exists$1,output:output$1};function setBigUint64$2(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),o=Number(n>>r&i),a=Number(n&i),c=s?4:0,l=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+l,a,s)}class SHA2 extends Hash$1{constructor(e,t,n,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,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){assert.exists(this);const{view:t,buffer:n,blockLen:s}=this,r=(e=toBytes$2(e)).length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);if(o===s){const t=createView$2(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,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:n,blockLen:s,isLE:r}=this;let{pos:i}=this;t[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>s-i&&(this.process(n,0),i=0);for(let e=i;e<s;e++)t[e]=0;setBigUint64$2(n,s-8,BigInt(8*this.length),r),this.process(n,0);const o=createView$2(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:i,pos:o}=this;return e.length=s,e.pos=o,e.finished=r,e.destroyed=i,s%t&&e.buffer.set(n),e}}const Chi$1=(e,t,n)=>e&t^~e&n,Maj$1=(e,t,n)=>e&t^e&n^t&n,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=0|IV[0],this.B=0|IV[1],this.C=0|IV[2],this.D=0|IV[3],this.E=0|IV[4],this.F=0|IV[5],this.G=0|IV[6],this.H=0|IV[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:i,G:o,H:a}=this;return[e,t,n,s,r,i,o,a]}set(e,t,n,s,r,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|r,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W$1[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=SHA256_W$1[e-15],n=SHA256_W$1[e-2],s=rotr$1(t,7)^rotr$1(t,18)^t>>>3,r=rotr$1(n,17)^rotr$1(n,19)^n>>>10;SHA256_W$1[e]=r+SHA256_W$1[e-7]+s+SHA256_W$1[e-16]|0}let{A:n,B:s,C:r,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(rotr$1(o,6)^rotr$1(o,11)^rotr$1(o,25))+Chi$1(o,a,c)+SHA256_K$1[e]+SHA256_W$1[e]|0,u=(rotr$1(n,2)^rotr$1(n,13)^rotr$1(n,22))+Maj$1(n,s,r)|0;l=c,c=a,a=o,o=i+t|0,i=r,r=s,s=n,n=t+u|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,r,i,o,a,c,l)}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);
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
function assertNumber(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function chain(...e){const t=(e,t)=>n=>e(t(n)),n=Array.from(e).reverse().reduce((e,n)=>e?t(e,n.encode):n.encode,void 0),s=e.reduce((e,n)=>e?t(e,n.decode):n.decode,void 0);return{encode:n,decode:s}}function alphabet(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map(t=>{if(assertNumber(t),t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const n=e.indexOf(t);if(-1===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n})}}}function join(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function padding(e,t="="){if(assertNumber(e),"string"!=typeof t)throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let e of n)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;n.length*e%8;)n.push(t);return n},decode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let e of n)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let s=n.length;if(s*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;s>0&&n[s-1]===t;s--)if(!((s-1)*e%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,s)}}}function normalize$1(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function convertRadix(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let s=0;const r=[],i=Array.from(e);for(i.forEach(e=>{if(assertNumber(e),e<0||e>=t)throw new Error(`Wrong integer: ${e}`)});;){let e=0,o=!0;for(let r=s;r<i.length;r++){const a=i[r],c=t*e+a;if(!Number.isSafeInteger(c)||t*e/t!==e||c-a!==t*e)throw new Error("convertRadix: carry overflow");if(e=c%n,i[r]=Math.floor(c/n),!Number.isSafeInteger(i[r])||i[r]*n+e!==c)throw new Error("convertRadix: carry overflow");o&&(i[r]?o=!1:s=r)}if(r.push(e),o)break}for(let t=0;t<e.length-1&&0===e[t];t++)r.push(0);return r.reverse()}wrapConstructor(()=>new SHA224);const gcd=(e,t)=>t?gcd(t,e%t):e,radix2carry=(e,t)=>e+(t-gcd(e,t));function convertRadix2(e,t,n,s){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(radix2carry(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${radix2carry(t,n)}`);let r=0,i=0;const o=2**n-1,a=[];for(const s of e){if(assertNumber(s),s>=2**t)throw new Error(`convertRadix2: invalid data word=${s} from=${t}`);if(r=r<<t|s,i+t>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${t}`);for(i+=t;i>=n;i-=n)a.push((r>>i-n&o)>>>0);r&=2**i-1}if(r=r<<n-i&o,!s&&i>=t)throw new Error("Excess padding");if(!s&&r)throw new Error(`Non-zero padding: ${r}`);return s&&i>0&&a.push(r>>>0),a}function radix(e){return assertNumber(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(t,e,256))}}}function radix2(e,t=!1){if(assertNumber(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,e)>32||radix2carry(e,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return convertRadix2(Array.from(n),8,e,!t)},decode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2(n,e,8,t))}}}function unsafeWrapper(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}const base16=chain(radix2(4),alphabet("0123456789ABCDEF"),join("")),base32=chain(radix2(5),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join(""));chain(radix2(5),alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join("")),chain(radix2(5),alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join(""),normalize$1(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),base64url=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join("")),genBase58=e=>chain(radix(58),alphabet(e),join("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11],base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const s=e.subarray(n,n+8);t+=base58.encode(s).padStart(XMR_BLOCK_LEN[s.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const s=e.slice(n,n+11),r=XMR_BLOCK_LEN.indexOf(s.length),i=base58.decode(s);for(let e=0;e<i.length-r;e++)if(0!==i[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(i.slice(i.length-r)))}return Uint8Array.from(t)}},BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<POLYMOD_GENERATORS.length;e++)1==(t>>e&1)&&(n^=POLYMOD_GENERATORS[e]);return n}function bechChecksum(e,t,n=1){const s=e.length;let r=1;for(let t=0;t<s;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);r=bech32Polymod(r)^n>>5}r=bech32Polymod(r);for(let t=0;t<s;t++)r=bech32Polymod(r)^31&e.charCodeAt(t);for(let e of t)r=bech32Polymod(r)^e;for(let e=0;e<6;e++)r=bech32Polymod(r);return r^=n,BECH_ALPHABET.encode(convertRadix2([r%2**30],30,5,!1))}function genBech32(e){const t="bech32"===e?1:734539939,n=radix2(5),s=n.decode,r=n.encode,i=unsafeWrapper(s);function o(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const s=e.toLowerCase();if(e!==s&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const r=(e=s).lastIndexOf("1");if(0===r||-1===r)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,r),o=e.slice(r+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const a=BECH_ALPHABET.decode(o).slice(0,-6),c=bechChecksum(i,a,t);if(!o.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,n,s=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const r=e.length+7+n.length;if(!1!==s&&r>s)throw new TypeError(`Length ${r} exceeds limit ${s}`);return`${e=e.toLowerCase()}1${BECH_ALPHABET.encode(n)}${bechChecksum(e,n,t)}`},decode:o,decodeToBytes:function(e){const{prefix:t,words:n}=o(e,!1);return{prefix:t,words:n,bytes:s(n)}},decodeUnsafe:unsafeWrapper(o),fromWords:s,fromWordsUnsafe:i,toWords:r}}const bech32=genBech32("bech32");genBech32("bech32m");const utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},hex=chain(radix2(4),alphabet("0123456789abcdef"),join(""),normalize$1(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()})),CODERS={utf8:utf8,hex:hex,base16:base16,base32:base32,base64:base64,base64url:base64url,base58:base58,base58xmr:base58xmr};function number(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function bool(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function isBytes$1(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function bytes(e,...t){if(!isBytes$1(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function exists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function output(e,t){bytes(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Object.keys(CODERS).join(", ");const u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView$1=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$1(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes$1(e){if("string"==typeof e)e=utf8ToBytes$1(e);else{if(!isBytes$1(e))throw new Error("Uint8Array expected, got "+typeof e);e=e.slice()}return e}function checkOpts(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}function equalBytes(e,t){if(e.length!==t.length)return!1;let n=0;for(let s=0;s<e.length;s++)n|=e[s]^t[s];return 0===n}const wrapCipher=(e,t)=>(Object.assign(t,e),t);function setBigUint64$1(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),o=Number(n>>r&i),a=Number(n&i),c=s?4:0,l=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+l,a,s)}const BLOCK_SIZE=16,POLY=283;function mul2(e){return e<<1^POLY&-(e>>7)}function mul(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(1&t),e=mul2(e);return n}const sbox=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=mul2(n))e[t]=n;const t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let s=e[255-n];s|=s<<8,t[e[n]]=255&(s^s>>4^s>>5^s>>6^s>>7^99)}return t})(),invSbox=sbox.map((e,t)=>sbox.indexOf(t)),rotr32_8=e=>e<<24|e>>>8,rotl32_8=e=>e<<8|e>>>24;function genTtable(e,t){if(256!==e.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((n,s)=>t(e[s])),s=n.map(rotl32_8),r=s.map(rotl32_8),i=r.map(rotl32_8),o=new Uint32Array(65536),a=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let l=0;l<256;l++){const u=256*t+l;o[u]=n[t]^s[l],a[u]=r[t]^i[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:s,T2:r,T3:i,T01:o,T23:a}}const tableEncoding=genTtable(sbox,e=>mul(e,3)<<24|e<<16|e<<8|mul(e,2)),tableDecoding=genTtable(invSbox,e=>mul(e,11)<<24|mul(e,13)<<16|mul(e,9)<<8|mul(e,14)),xPowers=(()=>{const e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=mul2(n))e[t]=n;return e})();function expandKeyLE(e){bytes(e);const t=e.length;if(![16,24,32].includes(t))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${t}`);const{sbox2:n}=tableEncoding,s=u32(e),r=s.length,i=e=>applySbox(n,e,e,e,e),o=new Uint32Array(t+28);o.set(s);for(let e=r;e<o.length;e++){let t=o[e-1];e%r===0?t=i(rotr32_8(t))^xPowers[e/r-1]:r>6&&e%r===4&&(t=i(t)),o[e]=o[e-r]^t}return o}function expandKeyDecLE(e){const t=expandKeyLE(e),n=t.slice(),s=t.length,{sbox2:r}=tableEncoding,{T0:i,T1:o,T2:a,T3:c}=tableDecoding;for(let e=0;e<s;e+=4)for(let r=0;r<4;r++)n[e+r]=t[s-e-4+r];t.fill(0);for(let e=4;e<s-4;e++){const t=n[e],s=applySbox(r,t,t,t,t);n[e]=i[255&s]^o[s>>>8&255]^a[s>>>16&255]^c[s>>>24]}return n}function apply0123(e,t,n,s,r,i){return e[n<<8&65280|s>>>8&255]^t[r>>>8&65280|i>>>24&255]}function applySbox(e,t,n,s,r){return e[255&t|65280&n]|e[s>>>16&255|r>>>16&65280]<<16}function encrypt$3(e,t,n,s,r){const{sbox2:i,T01:o,T23:a}=tableEncoding;let c=0;t^=e[c++],n^=e[c++],s^=e[c++],r^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^apply0123(o,a,t,n,s,r),l=e[c++]^apply0123(o,a,n,s,r,t),u=e[c++]^apply0123(o,a,s,r,t,n),d=e[c++]^apply0123(o,a,r,t,n,s);t=i,n=l,s=u,r=d}return{s0:e[c++]^applySbox(i,t,n,s,r),s1:e[c++]^applySbox(i,n,s,r,t),s2:e[c++]^applySbox(i,s,r,t,n),s3:e[c++]^applySbox(i,r,t,n,s)}}function decrypt$3(e,t,n,s,r){const{sbox2:i,T01:o,T23:a}=tableDecoding;let c=0;t^=e[c++],n^=e[c++],s^=e[c++],r^=e[c++];const l=e.length/4-2;for(let i=0;i<l;i++){const i=e[c++]^apply0123(o,a,t,r,s,n),l=e[c++]^apply0123(o,a,n,t,r,s),u=e[c++]^apply0123(o,a,s,n,t,r),d=e[c++]^apply0123(o,a,r,s,n,t);t=i,n=l,s=u,r=d}return{s0:e[c++]^applySbox(i,t,r,s,n),s1:e[c++]^applySbox(i,n,t,r,s),s2:e[c++]^applySbox(i,s,n,t,r),s3:e[c++]^applySbox(i,r,s,n,t)}}function getDst(e,t){if(!t)return new Uint8Array(e);if(bytes(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function validateBlockDecrypt(e){if(bytes(e),e.length%BLOCK_SIZE!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`)}function validateBlockEncrypt(e,t,n){let s=e.length;const r=s%BLOCK_SIZE;if(!t&&0!==r)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const i=u32(e);if(t){let e=BLOCK_SIZE-r;e||(e=BLOCK_SIZE),s+=e}const o=getDst(s,n);return{b:i,o:u32(o),out:o}}function validatePCKS(e,t){if(!t)return e;const n=e.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const s=e[n-1];if(s<=0||s>16)throw new Error(`aes/pcks5: wrong padding byte: ${s}`);const r=e.subarray(0,-s);for(let t=0;t<s;t++)if(e[n-t-1]!==s)throw new Error("aes/pcks5: wrong padding");return r}function padPCKS(e){const t=new Uint8Array(16),n=u32(t);t.set(e);const s=BLOCK_SIZE-e.length;for(let e=BLOCK_SIZE-s;e<BLOCK_SIZE;e++)t[e]=s;return n}const cbc=wrapCipher({blockSize:16,nonceLength:16},function(e,t,n={}){bytes(e),bytes(t,16);const s=!n.disablePadding;return{encrypt:(n,r)=>{const i=expandKeyLE(e),{b:o,o:a,out:c}=validateBlockEncrypt(n,s,r),l=u32(t);let u=l[0],d=l[1],h=l[2],p=l[3],f=0;for(;f+4<=o.length;)u^=o[f+0],d^=o[f+1],h^=o[f+2],p^=o[f+3],({s0:u,s1:d,s2:h,s3:p}=encrypt$3(i,u,d,h,p)),a[f++]=u,a[f++]=d,a[f++]=h,a[f++]=p;if(s){const e=padPCKS(n.subarray(4*f));u^=e[0],d^=e[1],h^=e[2],p^=e[3],({s0:u,s1:d,s2:h,s3:p}=encrypt$3(i,u,d,h,p)),a[f++]=u,a[f++]=d,a[f++]=h,a[f++]=p}return i.fill(0),c},decrypt:(n,r)=>{validateBlockDecrypt(n);const i=expandKeyDecLE(e),o=u32(t),a=getDst(n.length,r),c=u32(n),l=u32(a);let u=o[0],d=o[1],h=o[2],p=o[3];for(let e=0;e+4<=c.length;){const t=u,n=d,s=h,r=p;u=c[e+0],d=c[e+1],h=c[e+2],p=c[e+3];const{s0:o,s1:a,s2:f,s3:g}=decrypt$3(i,u,d,h,p);l[e++]=o^t,l[e++]=a^n,l[e++]=f^s,l[e++]=g^r}return i.fill(0),validatePCKS(a,s)}}}),u8to16=(e,t)=>255&e[t++]|(255&e[t++])<<8;class Poly1305{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,bytes(e=toBytes$1(e),32);const t=u8to16(e,0),n=u8to16(e,2),s=u8to16(e,4),r=u8to16(e,6),i=u8to16(e,8),o=u8to16(e,10),a=u8to16(e,12),c=u8to16(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|n<<3),this.r[2]=7939&(n>>>10|s<<6),this.r[3]=8191&(s>>>7|r<<9),this.r[4]=255&(r>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|o<<2),this.r[7]=8065&(o>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=u8to16(e,16+2*t)}process(e,t,n=!1){const s=n?0:2048,{h:r,r:i}=this,o=i[0],a=i[1],c=i[2],l=i[3],u=i[4],d=i[5],h=i[6],p=i[7],f=i[8],g=i[9],y=u8to16(e,t+0),m=u8to16(e,t+2),b=u8to16(e,t+4),v=u8to16(e,t+6),_=u8to16(e,t+8),w=u8to16(e,t+10),k=u8to16(e,t+12),E=u8to16(e,t+14);let x=r[0]+(8191&y),$=r[1]+(8191&(y>>>13|m<<3)),S=r[2]+(8191&(m>>>10|b<<6)),T=r[3]+(8191&(b>>>7|v<<9)),A=r[4]+(8191&(v>>>4|_<<12)),R=r[5]+(_>>>1&8191),N=r[6]+(8191&(_>>>14|w<<2)),C=r[7]+(8191&(w>>>11|k<<5)),I=r[8]+(8191&(k>>>8|E<<8)),B=r[9]+(E>>>5|s),P=0,D=P+x*o+$*(5*g)+S*(5*f)+T*(5*p)+A*(5*h);P=D>>>13,D&=8191,D+=R*(5*d)+N*(5*u)+C*(5*l)+I*(5*c)+B*(5*a),P+=D>>>13,D&=8191;let L=P+x*a+$*o+S*(5*g)+T*(5*f)+A*(5*p);P=L>>>13,L&=8191,L+=R*(5*h)+N*(5*d)+C*(5*u)+I*(5*l)+B*(5*c),P+=L>>>13,L&=8191;let F=P+x*c+$*a+S*o+T*(5*g)+A*(5*f);P=F>>>13,F&=8191,F+=R*(5*p)+N*(5*h)+C*(5*d)+I*(5*u)+B*(5*l),P+=F>>>13,F&=8191;let O=P+x*l+$*c+S*a+T*o+A*(5*g);P=O>>>13,O&=8191,O+=R*(5*f)+N*(5*p)+C*(5*h)+I*(5*d)+B*(5*u),P+=O>>>13,O&=8191;let U=P+x*u+$*l+S*c+T*a+A*o;P=U>>>13,U&=8191,U+=R*(5*g)+N*(5*f)+C*(5*p)+I*(5*h)+B*(5*d),P+=U>>>13,U&=8191;let M=P+x*d+$*u+S*l+T*c+A*a;P=M>>>13,M&=8191,M+=R*o+N*(5*g)+C*(5*f)+I*(5*p)+B*(5*h),P+=M>>>13,M&=8191;let K=P+x*h+$*d+S*u+T*l+A*c;P=K>>>13,K&=8191,K+=R*a+N*o+C*(5*g)+I*(5*f)+B*(5*p),P+=K>>>13,K&=8191;let H=P+x*p+$*h+S*d+T*u+A*l;P=H>>>13,H&=8191,H+=R*c+N*a+C*o+I*(5*g)+B*(5*f),P+=H>>>13,H&=8191;let j=P+x*f+$*p+S*h+T*d+A*u;P=j>>>13,j&=8191,j+=R*l+N*c+C*a+I*o+B*(5*g),P+=j>>>13,j&=8191;let V=P+x*g+$*f+S*p+T*h+A*d;P=V>>>13,V&=8191,V+=R*u+N*l+C*c+I*a+B*o,P+=V>>>13,V&=8191,P=(P<<2)+P|0,P=P+D|0,D=8191&P,P>>>=13,L+=P,r[0]=D,r[1]=L,r[2]=F,r[3]=O,r[4]=U,r[5]=M,r[6]=K,r[7]=H,r[8]=j,r[9]=V}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=s,s=e[t]>>>13,e[t]&=8191;e[0]+=5*s,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+s,s=n[t]>>>13,n[t]&=8191;n[9]-=8192;let r=(1^s)-1;for(let e=0;e<10;e++)n[e]&=r;r=~r;for(let t=0;t<10;t++)e[t]=e[t]&r|n[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let i=e[0]+t[0];e[0]=65535&i;for(let n=1;n<8;n++)i=(e[n]+t[n]|0)+(i>>>16)|0,e[n]=65535&i}update(e){exists(this);const{buffer:t,blockLen:n}=this,s=(e=toBytes$1(e)).length;for(let r=0;r<s;){const i=Math.min(n-this.pos,s-r);if(i!==n)t.set(e.subarray(r,r+i),this.pos),this.pos+=i,r+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0);else for(;n<=s-r;r+=n)this.process(e,r)}return this}destroy(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(e){exists(this),output(e,this),this.finished=!0;const{buffer:t,h:n}=this;let{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let t=0;t<8;t++)e[r++]=n[t]>>>0,e[r++]=n[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}}function wrapConstructorWithKey(e){const t=(t,n)=>e(n).update(toBytes$1(t)).digest(),n=e(new Uint8Array(32));return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}const poly1305=wrapConstructorWithKey(e=>new Poly1305(e)),_utf8ToBytes=e=>Uint8Array.from(e.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);function rotl$1(e,t){return e<<t|e>>>32-t}function isAligned32(e){return e.byteOffset%4==0}sigma32_32.slice();const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(e,t,n,s,r,i,o,a){const c=r.length,l=new Uint8Array(BLOCK_LEN),u=u32(l),d=isAligned32(r)&&isAligned32(i),h=d?u32(r):U32_EMPTY,p=d?u32(i):U32_EMPTY;for(let f=0;f<c;o++){if(e(t,n,s,u,o,a),o>=MAX_COUNTER)throw new Error("arx: counter overflow");const g=Math.min(BLOCK_LEN,c-f);if(d&&g===BLOCK_LEN){const e=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<BLOCK_LEN32;n++)t=e+n,p[t]=h[t]^u[n];f+=BLOCK_LEN;continue}for(let e,t=0;t<g;t++)e=f+t,i[e]=r[e]^l[t];f+=g}}function createCipher(e,t){const{allowShortKeys:n,extendNonceFn:s,counterLength:r,counterRight:i,rounds:o}=checkOpts({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return number(r),number(o),bool(i),bool(n),(t,a,c,l,u=0)=>{bytes(t),bytes(a),bytes(c);const d=c.length;if(l||(l=new Uint8Array(d)),bytes(l),number(u),u<0||u>=MAX_COUNTER)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let p,f,g=t.length;if(32===g)p=t.slice(),h.push(p),f=sigma32_32;else{if(16!==g||!n)throw new Error(`arx: invalid 32-byte key, got length=${g}`);p=new Uint8Array(32),p.set(t),p.set(t,16),f=sigma16_32,h.push(p)}isAligned32(a)||(a=a.slice(),h.push(a));const y=u32(p);if(s){if(24!==a.length)throw new Error("arx: extended nonce must be 24 bytes");s(f,y,u32(a.subarray(0,16)),y),a=a.subarray(16)}const m=16-r;if(m!==a.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(12!==m){const e=new Uint8Array(12);e.set(a,i?0:12-a.length),a=e,h.push(a)}const b=u32(a);for(runCipher(e,f,y,b,c,l,u,o);h.length>0;)h.pop().fill(0);return l}}function chachaCore(e,t,n,s,r,i=20){let o=e[0],a=e[1],c=e[2],l=e[3],u=t[0],d=t[1],h=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=r,v=n[0],_=n[1],w=n[2],k=o,E=a,x=c,$=l,S=u,T=d,A=h,R=p,N=f,C=g,I=y,B=m,P=b,D=v,L=_,F=w;for(let e=0;e<i;e+=2)k=k+S|0,P=rotl$1(P^k,16),N=N+P|0,S=rotl$1(S^N,12),k=k+S|0,P=rotl$1(P^k,8),N=N+P|0,S=rotl$1(S^N,7),E=E+T|0,D=rotl$1(D^E,16),C=C+D|0,T=rotl$1(T^C,12),E=E+T|0,D=rotl$1(D^E,8),C=C+D|0,T=rotl$1(T^C,7),x=x+A|0,L=rotl$1(L^x,16),I=I+L|0,A=rotl$1(A^I,12),x=x+A|0,L=rotl$1(L^x,8),I=I+L|0,A=rotl$1(A^I,7),$=$+R|0,F=rotl$1(F^$,16),B=B+F|0,R=rotl$1(R^B,12),$=$+R|0,F=rotl$1(F^$,8),B=B+F|0,R=rotl$1(R^B,7),k=k+T|0,F=rotl$1(F^k,16),I=I+F|0,T=rotl$1(T^I,12),k=k+T|0,F=rotl$1(F^k,8),I=I+F|0,T=rotl$1(T^I,7),E=E+A|0,P=rotl$1(P^E,16),B=B+P|0,A=rotl$1(A^B,12),E=E+A|0,P=rotl$1(P^E,8),B=B+P|0,A=rotl$1(A^B,7),x=x+R|0,D=rotl$1(D^x,16),N=N+D|0,R=rotl$1(R^N,12),x=x+R|0,D=rotl$1(D^x,8),N=N+D|0,R=rotl$1(R^N,7),$=$+S|0,L=rotl$1(L^$,16),C=C+L|0,S=rotl$1(S^C,12),$=$+S|0,L=rotl$1(L^$,8),C=C+L|0,S=rotl$1(S^C,7);let O=0;s[O++]=o+k|0,s[O++]=a+E|0,s[O++]=c+x|0,s[O++]=l+$|0,s[O++]=u+S|0,s[O++]=d+T|0,s[O++]=h+A|0,s[O++]=p+R|0,s[O++]=f+N|0,s[O++]=g+C|0,s[O++]=y+I|0,s[O++]=m+B|0,s[O++]=b+P|0,s[O++]=v+D|0,s[O++]=_+L|0,s[O++]=w+F|0}function hchacha(e,t,n,s){let r=e[0],i=e[1],o=e[2],a=e[3],c=t[0],l=t[1],u=t[2],d=t[3],h=t[4],p=t[5],f=t[6],g=t[7],y=n[0],m=n[1],b=n[2],v=n[3];for(let e=0;e<20;e+=2)r=r+c|0,y=rotl$1(y^r,16),h=h+y|0,c=rotl$1(c^h,12),r=r+c|0,y=rotl$1(y^r,8),h=h+y|0,c=rotl$1(c^h,7),i=i+l|0,m=rotl$1(m^i,16),p=p+m|0,l=rotl$1(l^p,12),i=i+l|0,m=rotl$1(m^i,8),p=p+m|0,l=rotl$1(l^p,7),o=o+u|0,b=rotl$1(b^o,16),f=f+b|0,u=rotl$1(u^f,12),o=o+u|0,b=rotl$1(b^o,8),f=f+b|0,u=rotl$1(u^f,7),a=a+d|0,v=rotl$1(v^a,16),g=g+v|0,d=rotl$1(d^g,12),a=a+d|0,v=rotl$1(v^a,8),g=g+v|0,d=rotl$1(d^g,7),r=r+l|0,v=rotl$1(v^r,16),f=f+v|0,l=rotl$1(l^f,12),r=r+l|0,v=rotl$1(v^r,8),f=f+v|0,l=rotl$1(l^f,7),i=i+u|0,y=rotl$1(y^i,16),g=g+y|0,u=rotl$1(u^g,12),i=i+u|0,y=rotl$1(y^i,8),g=g+y|0,u=rotl$1(u^g,7),o=o+d|0,m=rotl$1(m^o,16),h=h+m|0,d=rotl$1(d^h,12),o=o+d|0,m=rotl$1(m^o,8),h=h+m|0,d=rotl$1(d^h,7),a=a+c|0,b=rotl$1(b^a,16),p=p+b|0,c=rotl$1(c^p,12),a=a+c|0,b=rotl$1(b^a,8),p=p+b|0,c=rotl$1(c^p,7);let _=0;s[_++]=r,s[_++]=i,s[_++]=o,s[_++]=a,s[_++]=y,s[_++]=m,s[_++]=b,s[_++]=v}const chacha20=createCipher(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1}),xchacha20=createCipher(chachaCore,{counterRight:!1,counterLength:8,extendNonceFn:hchacha,allowShortKeys:!1}),ZEROS16=new Uint8Array(16),updatePadded=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(ZEROS16.subarray(n))},ZEROS32=new Uint8Array(32);function computeTag(e,t,n,s,r){const i=e(t,n,ZEROS32),o=poly1305.create(i);r&&updatePadded(o,r),updatePadded(o,s);const a=new Uint8Array(16),c=createView$1(a);setBigUint64$1(c,0,BigInt(r?r.length:0),!0),setBigUint64$1(c,8,BigInt(s.length),!0),o.update(a);const l=o.digest();return i.fill(0),l}const _poly1305_aead=e=>(t,n,s)=>{const r=16;return bytes(t,32),bytes(n),{encrypt:(i,o)=>{const a=i.length,c=a+r;o?bytes(o,c):o=new Uint8Array(c),e(t,n,i,o,1);const l=computeTag(e,t,n,o.subarray(0,-16),s);return o.set(l,a),o},decrypt:(i,o)=>{const a=i.length,c=a-r;if(a<r)throw new Error("encrypted data must be at least 16 bytes");o?bytes(o,c):o=new Uint8Array(c);const l=i.subarray(0,-16);if(!equalBytes(i.subarray(-16),computeTag(e,t,n,l,s)))throw new Error("invalid tag");return e(t,n,l,o,1),o}}},xchacha20poly1305=wrapCipher({blockSize:64,nonceLength:24,tagLength:16},_poly1305_aead(xchacha20));let HMAC$1=class extends Hash$1{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert.hash(e);const n=toBytes$2(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(n.length>s?e.create().update(n).digest():n);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),r.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:n,finished:s,destroyed:r,blockLen:i,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$1=(e,t,n)=>new HMAC$1(e,t).update(n).digest();function extract(e,t,n){return assert.hash(e),void 0===n&&(n=new Uint8Array(e.outputLen)),hmac$1(e,toBytes$2(n),toBytes$2(t))}hmac$1.create=(e,t)=>new HMAC$1(e,t);const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(e,t,n,s=32){if(assert.hash(e),assert.number(s),s>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const r=Math.ceil(s/e.outputLen);void 0===n&&(n=EMPTY_BUFFER);const i=new Uint8Array(r*e.outputLen),o=hmac$1.create(e,t),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let t=0;t<r;t++)HKDF_COUNTER[0]=t+1,a.update(0===t?EMPTY_BUFFER:c).update(n).update(HKDF_COUNTER).digestInto(c),i.set(c,e.outputLen*t),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),HKDF_COUNTER.fill(0),i.slice(0,s)}var __defProp$1=Object.defineProperty,__export=(e,t)=>{for(var n in t)__defProp$1(e,n,{get:t[n],enumerable:!0})},verifiedSymbol=Symbol("verified"),isRecord=e=>e instanceof Object;function validateEvent(e){if(!isRecord(e))return!1;if("number"!=typeof e.kind)return!1;if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if("string"!=typeof e.pubkey)return!1;if(!e.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){let n=e.tags[t];if(!Array.isArray(n))return!1;for(let e=0;e<n.length;e++)if("string"!=typeof n[e])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$1,utf8Encoder:()=>utf8Encoder$1});var utf8Decoder$1=new TextDecoder("utf-8"),utf8Encoder$1=new TextEncoder;function normalizeURL(e){try{-1===e.indexOf("://")&&(e="wss://"+e);let t=new URL(e);return t.pathname=t.pathname.replace(/\/+/g,"/"),t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),("80"===t.port&&"ws:"===t.protocol||"443"===t.port&&"wss:"===t.protocol)&&(t.port=""),t.searchParams.sort(),t.hash="",t.toString()}catch(t){throw new Error(`Invalid URL: ${e}`)}}function insertEventIntoDescendingList(e,t){const[n,s]=binarySearch(e,e=>t.id===e.id?0:t.created_at===e.created_at?-1:e.created_at-t.created_at);return s||e.splice(n,0,t),e}function insertEventIntoAscendingList(e,t){const[n,s]=binarySearch(e,e=>t.id===e.id?0:t.created_at===e.created_at?-1:t.created_at-e.created_at);return s||e.splice(n,0,t),e}function binarySearch(e,t){let n=0,s=e.length-1;for(;n<=s;){const r=Math.floor((n+s)/2),i=t(e[r]);if(0===i)return[r,!0];i<0?s=r-1:n=r+1}return[n,!1]}var QueueNode=class{value;next=null;prev=null;constructor(e){this.value=e}},Queue$1=class{first;last;constructor(){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 e=this.first;return this.first=null,this.last=null,e.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(e){return bytesToHex$1(schnorr$1.getPublicKey(e))}finalizeEvent(e,t){const n=e;return n.pubkey=bytesToHex$1(schnorr$1.getPublicKey(t)),n.id=getEventHash$1(n),n.sig=bytesToHex$1(schnorr$1.sign(getEventHash$1(n),t)),n[verifiedSymbol]=!0,n}verifyEvent(e){if("boolean"==typeof e[verifiedSymbol])return e[verifiedSymbol];const t=getEventHash$1(e);if(t!==e.id)return e[verifiedSymbol]=!1,!1;try{const n=schnorr$1.verify(e.sig,t,e.pubkey);return e[verifiedSymbol]=n,n}catch(t){return e[verifiedSymbol]=!1,!1}}};function serializeEvent(e){if(!validateEvent(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function getEventHash$1(e){return bytesToHex$1(sha256$2(utf8Encoder$1.encode(serializeEvent(e))))}var i=new JS,generateSecretKey=i.generateSecretKey,getPublicKey=i.getPublicKey,finalizeEvent=i.finalizeEvent,verifyEvent=i.verifyEvent,kinds_exports={};function isRegularKind(e){return 1e3<=e&&e<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(e)}function isReplaceableKind(e){return[0,3].includes(e)||1e4<=e&&e<2e4}function isEphemeralKind(e){return 2e4<=e&&e<3e4}function isAddressableKind(e){return 3e4<=e&&e<4e4}function classifyKind(e){return isRegularKind(e)?"regular":isReplaceableKind(e)?"replaceable":isEphemeralKind(e)?"ephemeral":isAddressableKind(e)?"parameterized":"unknown"}function isKind(e,t){const n=t instanceof Array?t:[t];return validateEvent(e)&&n.includes(e.kind)||!1}__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});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(e,t){if(e.ids&&-1===e.ids.indexOf(t.id))return!1;if(e.kinds&&-1===e.kinds.indexOf(t.kind))return!1;if(e.authors&&-1===e.authors.indexOf(t.pubkey))return!1;for(let n in e)if("#"===n[0]){let s=e[`#${n.slice(1)}`];if(s&&!t.tags.find(([e,t])=>e===n.slice(1)&&-1!==s.indexOf(t)))return!1}return!(e.since&&t.created_at<e.since)&&!(e.until&&t.created_at>e.until)}function matchFilters(e,t){for(let n=0;n<e.length;n++)if(matchFilter(e[n],t))return!0;return!1}var fakejson_exports={};function getHex64(e,t){let n=t.length+3,s=e.indexOf(`"${t}":`)+n,r=e.slice(s).indexOf('"')+s+1;return e.slice(r,r+64)}function getInt(e,t){let n=t.length,s=e.indexOf(`"${t}":`)+n+3,r=e.slice(s),i=Math.min(r.indexOf(","),r.indexOf("}"));return parseInt(r.slice(0,i),10)}function getSubscriptionId(e){let t=e.slice(0,22).indexOf('"EVENT"');if(-1===t)return null;let n=e.slice(t+7+1).indexOf('"');if(-1===n)return null;let s=t+7+1+n,r=e.slice(s+1,80).indexOf('"');if(-1===r)return null;let i=s+1+r;return e.slice(s+1,i)}function matchEventId(e,t){return t===getHex64(e,"id")}function matchEventPubkey(e,t){return t===getHex64(e,"pubkey")}function matchEventKind(e,t){return t===getInt(e,"kind")}__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});var nip42_exports={},_WebSocket,_WebSocket2;function makeAuthEvent(e,t){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",e],["challenge",t]],content:""}}__export(nip42_exports,{makeAuthEvent:()=>makeAuthEvent});try{_WebSocket=WebSocket}catch{}try{_WebSocket2=WebSocket}catch{}var nip19_exports$1={};__export(nip19_exports$1,{BECH32_REGEX:()=>BECH32_REGEX$2,Bech32MaxSize:()=>Bech32MaxSize$2,NostrTypeGuard:()=>NostrTypeGuard$1,decode:()=>decode$1,decodeNostrURI:()=>decodeNostrURI$1,encodeBytes:()=>encodeBytes$2,naddrEncode:()=>naddrEncode$1,neventEncode:()=>neventEncode$1,noteEncode:()=>noteEncode$1,nprofileEncode:()=>nprofileEncode$1,npubEncode:()=>npubEncode$1,nsecEncode:()=>nsecEncode$1});var NostrTypeGuard$1={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},Bech32MaxSize$2=5e3,BECH32_REGEX$2=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array$1(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}function decodeNostrURI$1(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),decode$1(e)}catch(e){return{type:"invalid",data:null}}}function decode$1(e){let{prefix:t,words:n}=bech32.decode(e,Bech32MaxSize$2),s=new Uint8Array(bech32.fromWords(n));switch(t){case"nprofile":{let e=parseTLV$1(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[]}}}case"nevent":{let e=parseTLV$1(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[],author:e[2]?.[0]?bytesToHex$1(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$1(e[3][0]),16):void 0}}}case"naddr":{let e=parseTLV$1(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder$1.decode(e[0][0]),pubkey:bytesToHex$1(e[2][0]),kind:parseInt(bytesToHex$1(e[3][0]),16),relays:e[1]?e[1].map(e=>utf8Decoder$1.decode(e)):[]}}}case"nsec":return{type:t,data:s};case"npub":case"note":return{type:t,data:bytesToHex$1(s)};default:throw new Error(`unknown prefix ${t}`)}}function parseTLV$1(e){let t={},n=e;for(;n.length>0;){let e=n[0],s=n[1],r=n.slice(2,2+s);if(n=n.slice(2+s),r.length<s)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(r)}return t}function nsecEncode$1(e){return encodeBytes$2("nsec",e)}function npubEncode$1(e){return encodeBytes$2("npub",hexToBytes$1(e))}function noteEncode$1(e){return encodeBytes$2("note",hexToBytes$1(e))}function encodeBech32$2(e,t){let n=bech32.toWords(t);return bech32.encode(e,n,Bech32MaxSize$2)}function encodeBytes$2(e,t){return encodeBech32$2(e,t)}function nprofileEncode$1(e){return encodeBech32$2("nprofile",encodeTLV$1({0:[hexToBytes$1(e.pubkey)],1:(e.relays||[]).map(e=>utf8Encoder$1.encode(e))}))}function neventEncode$1(e){let t;return void 0!==e.kind&&(t=integerToUint8Array$1(e.kind)),encodeBech32$2("nevent",encodeTLV$1({0:[hexToBytes$1(e.id)],1:(e.relays||[]).map(e=>utf8Encoder$1.encode(e)),2:e.author?[hexToBytes$1(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function naddrEncode$1(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),encodeBech32$2("naddr",encodeTLV$1({0:[utf8Encoder$1.encode(e.identifier)],1:(e.relays||[]).map(e=>utf8Encoder$1.encode(e)),2:[hexToBytes$1(e.pubkey)],3:[new Uint8Array(t)]}))}function encodeTLV$1(e){let t=[];return Object.entries(e).reverse().forEach(([e,n])=>{n.forEach(n=>{let s=new Uint8Array(n.length+2);s.set([parseInt(e)],0),s.set([n.length],1),s.set(n,2),t.push(s)})}),concatBytes$1(...t)}var nip04_exports={};function encrypt$2(e,t,n){const s=e instanceof Uint8Array?bytesToHex$1(e):e,r=getNormalizedX(secp256k1$1.getSharedSecret(s,"02"+t));let i=Uint8Array.from(randomBytes$1(16)),o=utf8Encoder$1.encode(n),a=cbc(r,i).encrypt(o);return`${base64.encode(new Uint8Array(a))}?iv=${base64.encode(new Uint8Array(i.buffer))}`}function decrypt$2(e,t,n){const s=e instanceof Uint8Array?bytesToHex$1(e):e;let[r,i]=n.split("?iv="),o=getNormalizedX(secp256k1$1.getSharedSecret(s,"02"+t)),a=base64.decode(i),c=base64.decode(r),l=cbc(o,a).decrypt(c);return utf8Decoder$1.decode(l)}function getNormalizedX(e){return e.slice(1,33)}__export(nip04_exports,{decrypt:()=>decrypt$2,encrypt:()=>encrypt$2});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=e=>NIP05_REGEX$1.test(e||""),_fetch;try{_fetch=fetch}catch(e){}function useFetchImplementation(e){_fetch=e}async function searchDomain(e,t=""){try{const n=`https://${e}/.well-known/nostr.json?name=${t}`,s=await _fetch(n,{redirect:"manual"});if(200!==s.status)throw Error("Wrong response code");return(await s.json()).names}catch(e){return{}}}async function queryProfile(e){const t=e.match(NIP05_REGEX$1);if(!t)return null;const[,n="_",s]=t;try{const e=`https://${s}/.well-known/nostr.json?name=${n}`,t=await _fetch(e,{redirect:"manual"});if(200!==t.status)throw Error("Wrong response code");const r=await t.json(),i=r.names[n];return i?{pubkey:i,relays:r.relays?.[i]}:null}catch(e){return null}}async function isValid(e,t){const n=await queryProfile(t);return!!n&&n.pubkey===e}var nip10_exports={};function parse(e){const t={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,s;for(let r=e.tags.length-1;r>=0;r--){const i=e.tags[r];if("e"===i[0]&&i[1]){const[e,r,o,a,c]=i,l={id:r,relays:o?[o]:[],author:c};if("root"===a){t.root=l;continue}if("reply"===a){t.reply=l;continue}if("mention"===a){t.mentions.push(l);continue}n?s=l:n=l,t.mentions.push(l);continue}if("q"===i[0]&&i[1]){const[e,n,s]=i;t.quotes.push({id:n,relays:s?[s]:[]})}"p"===i[0]&&i[1]&&t.profiles.push({pubkey:i[1],relays:i[2]?[i[2]]:[]})}return t.root||(t.root=s||n||t.reply),t.reply||(t.reply=n||t.root),[t.reply,t.root].forEach(e=>{if(!e)return;let n=t.mentions.indexOf(e);if(-1!==n&&t.mentions.splice(n,1),e.author){let n=t.profiles.find(t=>t.pubkey===e.author);n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach(t=>{-1===e.relays?.indexOf(t)&&e.relays.push(t)}),n.relays=e.relays)}}),t.mentions.forEach(e=>{if(e.author){let n=t.profiles.find(t=>t.pubkey===e.author);n&&n.relays&&(e.relays||(e.relays=[]),n.relays.forEach(t=>{-1===e.relays.indexOf(t)&&e.relays.push(t)}),n.relays=e.relays)}}),t}__export(nip10_exports,{parse:()=>parse});var nip11_exports={},_fetch2;__export(nip11_exports,{fetchRelayInformation:()=>fetchRelayInformation$1,useFetchImplementation:()=>useFetchImplementation2});try{_fetch2=fetch}catch{}function useFetchImplementation2(e){_fetch2=e}async function fetchRelayInformation$1(e){return await(await fetch(e.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var nip13_exports={};function getPow(e){let t=0;for(let n=0;n<64;n+=8){const s=parseInt(e.substring(n,n+8),16);if(0!==s){t+=Math.clz32(s);break}t+=32}return t}function minePow(e,t){let n=0;const s=e,r=["nonce",n.toString(),t.toString()];for(s.tags.push(r);;){const e=Math.floor((new Date).getTime()/1e3);if(e!==s.created_at&&(n=0,s.created_at=e),r[1]=(++n).toString(),s.id=fastEventHash(s),getPow(s.id)>=t)break}return s}function fastEventHash(e){return bytesToHex$1(sha256$2(utf8Encoder$1.encode(JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]))))}__export(nip13_exports,{fastEventHash:()=>fastEventHash,getPow:()=>getPow,minePow:()=>minePow});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,encrypt:()=>encrypt2,getConversationKey:()=>getConversationKey,v2:()=>v2});var minPlaintextSize=1,maxPlaintextSize=65535;function getConversationKey(e,t){const n=secp256k1$1.getSharedSecret(e,"02"+t).subarray(1,33);return extract(sha256$2,n,"nip44-v2")}function getMessageKeys(e,t){const n=expand(sha256$2,e,t,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function calcPaddedLen(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("expected positive integer");if(e<=32)return 32;const t=1<<Math.floor(Math.log2(e-1))+1,n=t<=256?32:t/8;return n*(Math.floor((e-1)/n)+1)}function writeU16BE(e){if(!Number.isSafeInteger(e)||e<minPlaintextSize||e>maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const t=new Uint8Array(2);return new DataView(t.buffer).setUint16(0,e,!1),t}function pad(e){const t=utf8Encoder$1.encode(e),n=t.length;return concatBytes$1(writeU16BE(n),t,new Uint8Array(calcPaddedLen(n)-n))}function unpad(e){const t=new DataView(e.buffer).getUint16(0),n=e.subarray(2,2+t);if(t<minPlaintextSize||t>maxPlaintextSize||n.length!==t||e.length!==2+calcPaddedLen(t))throw new Error("invalid padding");return utf8Decoder$1.decode(n)}function hmacAad(e,t,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const s=concatBytes$1(n,t);return hmac$1(sha256$2,e,s)}function decodePayload(e){if("string"!=typeof e)throw new Error("payload must be a valid string");const t=e.length;if(t<132||t>87472)throw new Error("invalid payload length: "+t);if("#"===e[0])throw new Error("unknown encryption version");let n;try{n=base64.decode(e)}catch(e){throw new Error("invalid base64: "+e.message)}const s=n.length;if(s<99||s>65603)throw new Error("invalid data length: "+s);const r=n[0];if(2!==r)throw new Error("unknown encryption version "+r);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function encrypt2(e,t,n=randomBytes$1(32)){const{chacha_key:s,chacha_nonce:r,hmac_key:i}=getMessageKeys(t,n),o=pad(e),a=chacha20(s,r,o),c=hmacAad(i,a,n);return base64.encode(concatBytes$1(new Uint8Array([2]),n,a,c))}function decrypt2(e,t){const{nonce:n,ciphertext:s,mac:r}=decodePayload(e),{chacha_key:i,chacha_nonce:o,hmac_key:a}=getMessageKeys(t,n);if(!equalBytes(hmacAad(a,s,n),r))throw new Error("invalid MAC");return unpad(chacha20(i,o,s))}var v2={utils:{getConversationKey:getConversationKey,calcPaddedLen:calcPaddedLen},encrypt:encrypt2,decrypt:decrypt2},TWO_DAYS=172800,now=()=>Math.round(Date.now()/1e3),randomNow=()=>Math.round(now()-Math.random()*TWO_DAYS),nip44ConversationKey=(e,t)=>getConversationKey(e,t),nip44Encrypt=(e,t,n)=>encrypt2(JSON.stringify(e),nip44ConversationKey(t,n)),nip44Decrypt=(e,t)=>JSON.parse(decrypt2(e.content,nip44ConversationKey(t,e.pubkey)));function createRumor(e,t){const n={created_at:now(),content:"",tags:[],...e,pubkey:getPublicKey(t)};return n.id=getEventHash$1(n),n}function createSeal(e,t,n){return finalizeEvent({kind:Seal,content:nip44Encrypt(e,t,n),created_at:randomNow(),tags:[]},t)}function createWrap(e,t){const n=generateSecretKey();return finalizeEvent({kind:GiftWrap,content:nip44Encrypt(e,n,t),created_at:randomNow(),tags:[["p",t]]},n)}function wrapEvent$1(e,t,n){return createWrap(createSeal(createRumor(e,t),t,n),n)}function wrapManyEvents(e,t,n){if(!n||0===n.length)throw new Error("At least one recipient is required.");const s=getPublicKey(t),r=[wrapEvent$1(e,t,s)];return n.forEach(n=>{r.push(wrapEvent$1(e,t,n))}),r}function unwrapEvent(e,t){const n=nip44Decrypt(e,t);return nip44Decrypt(n,t)}function unwrapManyEvents(e,t){let n=[];return e.forEach(e=>{n.push(unwrapEvent(e,t))}),n.sort((e,t)=>e.created_at-t.created_at),n}function createEvent(e,t,n,s){const r={created_at:Math.ceil(Date.now()/1e3),kind:PrivateDirectMessage,tags:[],content:t};return(Array.isArray(e)?e:[e]).forEach(({publicKey:e,relayUrl:t})=>{r.tags.push(t?["p",e,t]:["p",e])}),s&&r.tags.push(["e",s.eventId,s.relayUrl||"","reply"]),n&&r.tags.push(["subject",n]),r}function wrapEvent2(e,t,n,s,r){return wrapEvent$1(createEvent(t,n,s,r),e,t.publicKey)}function wrapManyEvents2(e,t,n,s,r){if(!t||0===t.length)throw new Error("At least one recipient is required.");return[{publicKey:getPublicKey(e)},...t].map(t=>wrapEvent2(e,t,n,s,r))}var unwrapEvent2=unwrapEvent,unwrapManyEvents2=unwrapManyEvents,nip18_exports={};function finishRepostEvent(e,t,n,s){let r;const i=[...e.tags??[],["e",t.id,n],["p",t.pubkey]];return t.kind===ShortTextNote?r=Repost:(r=GenericRepost,i.push(["k",String(t.kind)])),finalizeEvent({kind:r,tags:i,content:""===e.content||t.tags?.find(e=>"-"===e[0])?"":JSON.stringify(t),created_at:e.created_at},s)}function getRepostedEventPointer(e){if(![Repost,GenericRepost].includes(e.kind))return;let t,n;for(let s=e.tags.length-1;s>=0&&(void 0===t||void 0===n);s--){const r=e.tags[s];r.length>=2&&("e"===r[0]&&void 0===t?t=r:"p"===r[0]&&void 0===n&&(n=r))}return void 0!==t?{id:t[1],relays:[t[2],n?.[2]].filter(e=>"string"==typeof e),author:n?.[1]}:void 0}function getRepostedEvent(e,{skipVerification:t}={}){const n=getRepostedEventPointer(e);if(void 0===n||""===e.content)return;let s;try{s=JSON.parse(e.content)}catch(e){return}return s.id===n.id&&(t||verifyEvent(s))?s:void 0}__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});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$2.source})`);function test(e){return"string"==typeof e&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(e)}function parse2(e){const t=e.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!t)throw new Error(`Invalid Nostr URI: ${e}`);return{uri:t[0],value:t[1],decoded:decode$1(t[1])}}var nip25_exports={};function finishReactionEvent(e,t,n){const s=t.tags.filter(e=>e.length>=2&&("e"===e[0]||"p"===e[0]));return finalizeEvent({...e,kind:Reaction,tags:[...e.tags??[],...s,["e",t.id],["p",t.pubkey]],content:e.content??"+"},n)}function getReactedEventPointer(e){if(e.kind!==Reaction)return;let t,n;for(let s=e.tags.length-1;s>=0&&(void 0===t||void 0===n);s--){const r=e.tags[s];r.length>=2&&("e"===r[0]&&void 0===t?t=r:"p"===r[0]&&void 0===n&&(n=r))}return void 0!==t&&void 0!==n?{id:t[1],relays:[t[2],n[2]].filter(e=>void 0!==e),author:n[1]}:void 0}__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});var nip27_exports={};__export(nip27_exports,{parse:()=>parse3});var noCharacter=/\W/m,noURLCharacter=/\W |\W$|$|,| /m;function*parse3(e){const t=e.length;let n=0,s=0;for(;s<t;){let r=e.indexOf(":",s);if(-1===r)break;if("nostr"===e.substring(r-5,r)){const i=e.substring(r+60).match(noCharacter),o=i?r+60+i.index:t;try{let t,{data:i,type:a}=decode$1(e.substring(r+1,o));switch(a){case"npub":t={pubkey:i};break;case"nsec":case"note":s=o+1;continue;default:t=i}n!==r-5&&(yield{type:"text",text:e.substring(n,r-5)}),yield{type:"reference",pointer:t},s=o,n=s;continue}catch(e){s=r+1;continue}}else if("https"===e.substring(r-5,r)||"http"===e.substring(r-4,r)){const i=e.substring(r+4).match(noURLCharacter),o=i?r+4+i.index:t,a="s"===e[r-1]?5:4;try{let t=new URL(e.substring(r-a,o));if(-1===t.hostname.indexOf("."))throw new Error("invalid url");if(n!==r-a&&(yield{type:"text",text:e.substring(n,r-a)}),/\.(png|jpe?g|gif|webp)$/i.test(t.pathname)){yield{type:"image",url:t.toString()},s=o,n=s;continue}if(/\.(mp4|avi|webm|mkv)$/i.test(t.pathname)){yield{type:"video",url:t.toString()},s=o,n=s;continue}if(/\.(mp3|aac|ogg|opus)$/i.test(t.pathname)){yield{type:"audio",url:t.toString()},s=o,n=s;continue}yield{type:"url",url:t.toString()},s=o,n=s;continue}catch(e){s=o+1;continue}}else{if("wss"!==e.substring(r-3,r)&&"ws"!==e.substring(r-2,r)){s=r+1;continue}{const i=e.substring(r+4).match(noURLCharacter),o=i?r+4+i.index:t,a="s"===e[r-1]?3:2;try{let t=new URL(e.substring(r-a,o));if(-1===t.hostname.indexOf("."))throw new Error("invalid ws url");n!==r-a&&(yield{type:"text",text:e.substring(n,r-a)}),yield{type:"relay",url:t.toString()},s=o,n=s;continue}catch(e){s=o+1;continue}}}}n!==t&&(yield{type:"text",text:e.substring(n)})}var nip28_exports={};__export(nip28_exports,{channelCreateEvent:()=>channelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finalizeEvent({kind:ChannelCreation,tags:[...e.tags??[]],content:n,created_at:e.created_at},t)},channelMetadataEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finalizeEvent({kind:ChannelMetadata,tags:[["e",e.channel_create_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},channelMessageEvent=(e,t)=>{const n=[["e",e.channel_create_event_id,e.relay_url,"root"]];return e.reply_to_channel_message_event_id&&n.push(["e",e.reply_to_channel_message_event_id,e.relay_url,"reply"]),finalizeEvent({kind:ChannelMessage,tags:[...n,...e.tags??[]],content:e.content,created_at:e.created_at},t)},channelHideMessageEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finalizeEvent({kind:ChannelHideMessage,tags:[["e",e.channel_message_event_id],...e.tags??[]],content:n,created_at:e.created_at},t)},channelMuteUserEvent=(e,t)=>{let n;if("object"==typeof e.content)n=JSON.stringify(e.content);else{if("string"!=typeof e.content)return;n=e.content}return finalizeEvent({kind:ChannelMuteUser,tags:[["p",e.pubkey_to_mute],...e.tags??[]],content:n,created_at:e.created_at},t)},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(e){const t=e.matchAll(regex());for(const e of t)try{const[t,n]=e;yield{shortcode:t,name:n,start:e.index,end:e.index+t.length}}catch(e){}}function replaceAll(e,t){return e.replaceAll(regex(),(e,n)=>t({shortcode:e,name:n}))}var nip39_exports={},_fetch3;__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation3,validateGithub:()=>validateGithub});try{_fetch3=fetch}catch{}function useFetchImplementation3(e){_fetch3=e}async function validateGithub(e,t,n){try{return await(await _fetch3(`https://gist.github.com/${t}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${e}`}catch(e){return!1}}var nip47_exports={};function parseConnectionString(e){const{host:t,pathname:n,searchParams:s}=new URL(e),r=n||t,i=s.get("relay"),o=s.get("secret");if(!r||!i||!o)throw new Error("invalid connection string");return{pubkey:r,relay:i,secret:o}}async function makeNwcRequestEvent(e,t,n){const s={method:"pay_invoice",params:{invoice:n}},r=encrypt$2(t,e,JSON.stringify(s)),i={kind:NWCWalletRequest,created_at:Math.round(Date.now()/1e3),content:r,tags:[["p",e]]};return finalizeEvent(i,t)}__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});var nip54_exports={};function normalizeIdentifier(e){return e=(e=e.trim().toLowerCase()).normalize("NFKC"),Array.from(e).map(e=>/\p{Letter}/u.test(e)||/\p{Number}/u.test(e)?e:"-").join("")}__export(nip54_exports,{normalizeIdentifier:()=>normalizeIdentifier});var nip57_exports={},_fetch4;__export(nip57_exports,{getSatoshisAmountFromBolt11:()=>getSatoshisAmountFromBolt11,getZapEndpoint:()=>getZapEndpoint,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation4,validateZapRequest:()=>validateZapRequest});try{_fetch4=fetch}catch{}function useFetchImplementation4(e){_fetch4=e}async function getZapEndpoint(e){try{let t="",{lud06:n,lud16:s}=JSON.parse(e.content);if(n){let{words:e}=bech32.decode(n,1e3),s=bech32.fromWords(e);t=utf8Decoder$1.decode(s)}else{if(!s)return null;{let[e,n]=s.split("@");t=new URL(`/.well-known/lnurlp/${e}`,`https://${n}`).toString()}}let r=await _fetch4(t),i=await r.json();if(i.allowsNostr&&i.nostrPubkey)return i.callback}catch(e){}return null}function makeZapRequest(e){let t={kind:9734,created_at:Math.round(Date.now()/1e3),content:e.comment||"",tags:[["p","pubkey"in e?e.pubkey:e.event.pubkey],["amount",e.amount.toString()],["relays",...e.relays]]};if("event"in e){if(t.tags.push(["e",e.event.id]),isReplaceableKind(e.event.kind)){const n=["a",`${e.event.kind}:${e.event.pubkey}:`];t.tags.push(n)}else if(isAddressableKind(e.event.kind)){let n=e.event.tags.find(([e,t])=>"d"===e&&t);if(!n)throw new Error("d tag not found or is empty");const s=["a",`${e.event.kind}:${e.event.pubkey}:${n[1]}`];t.tags.push(s)}t.tags.push(["k",e.event.kind.toString()])}return t}function validateZapRequest(e){let t;try{t=JSON.parse(e)}catch(e){return"Invalid zap request JSON."}if(!validateEvent(t))return"Zap request is not a valid Nostr event.";if(!verifyEvent(t))return"Invalid signature on zap request.";let n=t.tags.find(([e,t])=>"p"===e&&t);if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let s=t.tags.find(([e,t])=>"e"===e&&t);return s&&!s[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":t.tags.find(([e,t])=>"relays"===e&&t)?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:e,preimage:t,bolt11:n,paidAt:s}){let r=JSON.parse(e),i=r.tags.filter(([e])=>"e"===e||"p"===e||"a"===e),o={kind:9735,created_at:Math.round(s.getTime()/1e3),content:"",tags:[...i,["P",r.pubkey],["bolt11",n],["description",e]]};return t&&o.tags.push(["preimage",t]),o}function getSatoshisAmountFromBolt11(e){if(e.length<50)return 0;const t=(e=e.substring(0,50)).lastIndexOf("1");if(-1===t)return 0;const n=e.substring(0,t);if(!n.startsWith("lnbc"))return 0;const s=n.substring(4);if(s.length<1)return 0;const r=s[s.length-1],i=r.charCodeAt(0)-"0".charCodeAt(0),o=i>=0&&i<=9;let a=s.length-1;if(o&&a++,a<1)return 0;const c=parseInt(s.substring(0,a));switch(r){case"m":return 1e5*c;case"u":return 100*c;case"n":return c/10;case"p":return c/1e4;default:return 1e8*c}}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(e,t,n,s=!1,r){const i={kind:HTTPAuth,tags:[["u",e],["method",t]],created_at:Math.round((new Date).getTime()/1e3),content:""};r&&i.tags.push(["payload",hashPayload(r)]);const o=await n(i);return(s?_authorizationScheme:"")+base64.encode(utf8Encoder$1.encode(JSON.stringify(o)))}async function validateToken(e,t,n){const s=await unpackEventFromToken(e).catch(e=>{throw e});return await validateEvent2(s,t,n).catch(e=>{throw e})}async function unpackEventFromToken(e){if(!e)throw new Error("Missing token");e=e.replace(_authorizationScheme,"");const t=utf8Decoder$1.decode(base64.decode(e));if(!t||0===t.length||!t.startsWith("{"))throw new Error("Invalid token");return JSON.parse(t)}function validateEventTimestamp(e){return!!e.created_at&&Math.round((new Date).getTime()/1e3)-e.created_at<60}function validateEventKind(e){return e.kind===HTTPAuth}function validateEventUrlTag(e,t){const n=e.tags.find(e=>"u"===e[0]);return!!n&&(n.length>0&&n[1]===t)}function validateEventMethodTag(e,t){const n=e.tags.find(e=>"method"===e[0]);return!!n&&(n.length>0&&n[1].toLowerCase()===t.toLowerCase())}function hashPayload(e){return bytesToHex$1(sha256$2(utf8Encoder$1.encode(JSON.stringify(e))))}function validateEventPayloadTag(e,t){const n=e.tags.find(e=>"payload"===e[0]);if(!n)return!1;const s=hashPayload(t);return n.length>0&&n[1]===s}async function validateEvent2(e,t,n,s){if(!verifyEvent(e))throw new Error("Invalid nostr event, signature invalid");if(!validateEventKind(e))throw new Error("Invalid nostr event, kind invalid");if(!validateEventTimestamp(e))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!validateEventUrlTag(e,t))throw new Error("Invalid nostr event, url tag invalid");if(!validateEventMethodTag(e,n))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(s)&&"object"==typeof s&&Object.keys(s).length>0&&!validateEventPayloadTag(e,s))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function anumber(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function abytes(e,...t){if(!isBytes(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ahash(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");anumber(e.outputLen),anumber(e.blockLen)}function aexists(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function aoutput(e,t){abytes(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function clean(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function createView(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rotr(e,t){return e<<32-t|e>>>t}const hasHexBuiltin=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hexes=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex(e){if(abytes(e),hasHexBuiltin)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=hexes[e[n]];return t}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(e){return e>=asciis._0&&e<=asciis._9?e-asciis._0:e>=asciis.A&&e<=asciis.F?e-(asciis.A-10):e>=asciis.a&&e<=asciis.f?e-(asciis.a-10):void 0}function hexToBytes(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(hasHexBuiltin)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const s=new Uint8Array(n);for(let t=0,r=0;t<n;t++,r+=2){const n=asciiToBase16(e.charCodeAt(r)),i=asciiToBase16(e.charCodeAt(r+1));if(void 0===n||void 0===i){const t=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+r)}s[t]=16*n+i}return s}function utf8ToBytes(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function toBytes(e){return"string"==typeof e&&(e=utf8ToBytes(e)),abytes(e),e}function concatBytes(...e){let t=0;for(let n=0;n<e.length;n++){const s=e[n];abytes(s),t+=s.length}const n=new Uint8Array(t);for(let t=0,s=0;t<e.length;t++){const r=e[t];n.set(r,s),s+=r.length}return n}class Hash{}function createHasher(e){const t=t=>e().update(toBytes(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function randomBytes(e=32){if(crypto&&"function"==typeof crypto.getRandomValues)return crypto.getRandomValues(new Uint8Array(e));if(crypto&&"function"==typeof crypto.randomBytes)return Uint8Array.from(crypto.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),o=Number(n>>r&i),a=Number(n&i),c=s?4:0,l=s?0:4;e.setUint32(t+c,o,s),e.setUint32(t+l,a,s)}function Chi(e,t,n){return e&t^~e&n}function Maj(e,t,n){return e&t^e&n^t&n}class HashMD extends Hash{constructor(e,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this),abytes(e=toBytes(e));const{view:t,buffer:n,blockLen:s}=this,r=e.length;for(let i=0;i<r;){const o=Math.min(s-this.pos,r-i);if(o===s){const t=createView(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,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:n,blockLen:s,isLE:r}=this;let{pos:i}=this;t[i++]=128,clean(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let e=i;e<s;e++)t[e]=0;setBigUint64(n,s-8,BigInt(8*this.length),r),this.process(n,0);const o=createView(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,l[e],r)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:s,finished:r,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=r,e.length=s,e.pos=o,s%t&&e.buffer.set(n),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=0|SHA256_IV[0],this.B=0|SHA256_IV[1],this.C=0|SHA256_IV[2],this.D=0|SHA256_IV[3],this.E=0|SHA256_IV[4],this.F=0|SHA256_IV[5],this.G=0|SHA256_IV[6],this.H=0|SHA256_IV[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:i,G:o,H:a}=this;return[e,t,n,s,r,i,o,a]}set(e,t,n,s,r,i,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|s,this.E=0|r,this.F=0|i,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)SHA256_W[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=SHA256_W[e-15],n=SHA256_W[e-2],s=rotr(t,7)^rotr(t,18)^t>>>3,r=rotr(n,17)^rotr(n,19)^n>>>10;SHA256_W[e]=r+SHA256_W[e-7]+s+SHA256_W[e-16]|0}let{A:n,B:s,C:r,D:i,E:o,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(rotr(o,6)^rotr(o,11)^rotr(o,25))+Chi(o,a,c)+SHA256_K[e]+SHA256_W[e]|0,u=(rotr(n,2)^rotr(n,13)^rotr(n,22))+Maj(n,s,r)|0;l=c,c=a,a=o,o=i+t|0,i=r,r=s,s=n,n=t+u|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,s,r,i,o,a,c,l)}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 n=toBytes(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)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,r=new Uint8Array(s);r.set(n.length>s?e.create().update(n).digest():n);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),clean(r)}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:n,finished:s,destroyed:r,blockLen:i,outputLen:o}=this;return e.finished=s,e.destroyed=r,e.blockLen=i,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(e,t,n)=>new HMAC(e,t).update(n).digest();hmac.create=(e,t)=>new HMAC(e,t);
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$4=BigInt(0),_1n$4=BigInt(1);function _abool2(e,t=""){if("boolean"!=typeof e){throw new Error((t&&`"${t}"`)+"expected boolean, got type="+typeof e)}return e}function _abytes2(e,t,n=""){const s=isBytes(e),r=e?.length,i=void 0!==t;if(!s||i&&r!==t){throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(i?` of length ${t}`:"")+", got "+(s?`length=${r}`:"type="+typeof e))}return e}function numberToHexUnpadded(e){const t=e.toString(16);return 1&t.length?"0"+t:t}function hexToNumber(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?_0n$4:BigInt("0x"+e)}function bytesToNumberBE(e){return hexToNumber(bytesToHex(e))}function bytesToNumberLE(e){return abytes(e),hexToNumber(bytesToHex(Uint8Array.from(e).reverse()))}function numberToBytesBE(e,t){return hexToBytes(e.toString(16).padStart(2*t,"0"))}function numberToBytesLE(e,t){return numberToBytesBE(e,t).reverse()}function ensureBytes(e,t,n){let s;if("string"==typeof t)try{s=hexToBytes(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!isBytes(t))throw new Error(e+" must be hex string or Uint8Array");s=Uint8Array.from(t)}const r=s.length;if("number"==typeof n&&r!==n)throw new Error(e+" of length "+n+" expected, got "+r);return s}const isPosBig=e=>"bigint"==typeof e&&_0n$4<=e;function inRange(e,t,n){return isPosBig(e)&&isPosBig(t)&&isPosBig(n)&&t<=e&&e<n}function aInRange(e,t,n,s){if(!inRange(t,n,s))throw new Error("expected valid "+e+": "+n+" <= n < "+s+", got "+t)}function bitLen(e){let t;for(t=0;e>_0n$4;e>>=_1n$4,t+=1);return t}const bitMask=e=>(_1n$4<<BigInt(e))-_1n$4;function createHmacDrbg(e,t,n){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");const s=e=>new Uint8Array(e),r=e=>Uint8Array.of(e);let i=s(e),o=s(e),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...e)=>n(o,i,...e),u=(e=s(0))=>{o=l(r(0),e),i=l(),0!==e.length&&(o=l(r(1),e),i=l())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=l();const t=i.slice();n.push(t),e+=i.length}return concatBytes(...n)};return(e,t)=>{let n;for(c(),u(e);!(n=t(d()));)u();return c(),n}}function _validateObject(e,t,n={}){if(!e||"object"!=typeof e)throw new Error("expected valid options object");function s(t,n,s){const r=e[t];if(s&&void 0===r)return;const i=typeof r;if(i!==n||null===r)throw new Error(`param "${t}" is invalid: expected ${n}, got ${i}`)}Object.entries(t).forEach(([e,t])=>s(e,t,!1)),Object.entries(n).forEach(([e,t])=>s(e,t,!0))}function memoized(e){const t=new WeakMap;return(n,...s)=>{const r=t.get(n);if(void 0!==r)return r;const i=e(n,...s);return t.set(n,i),i}}
/*! 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(e,t){const n=e%t;return n>=_0n$3?n:t+n}function pow2(e,t,n){let s=e;for(;t-- >_0n$3;)s*=s,s%=n;return s}function invert(e,t){if(e===_0n$3)throw new Error("invert: expected non-zero number");if(t<=_0n$3)throw new Error("invert: expected positive modulus, got "+t);let n=mod(e,t),s=t,r=_0n$3,i=_1n$3;for(;n!==_0n$3;){const e=s%n,t=r-i*(s/n);s=n,n=e,r=i,i=t}if(s!==_1n$3)throw new Error("invert: does not exist");return mod(r,t)}function assertIsSquare(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function sqrt3mod4(e,t){const n=(e.ORDER+_1n$3)/_4n$1,s=e.pow(t,n);return assertIsSquare(e,s,t),s}function sqrt5mod8(e,t){const n=(e.ORDER-_5n)/_8n,s=e.mul(t,_2n$2),r=e.pow(s,n),i=e.mul(t,r),o=e.mul(e.mul(i,_2n$2),r),a=e.mul(i,e.sub(o,e.ONE));return assertIsSquare(e,a,t),a}function sqrt9mod16(e){const t=Field(e),n=tonelliShanks(e),s=n(t,t.neg(t.ONE)),r=n(t,s),i=n(t,t.neg(s)),o=(e+_7n)/_16n;return(e,t)=>{let n=e.pow(t,o),a=e.mul(n,s);const c=e.mul(n,r),l=e.mul(n,i),u=e.eql(e.sqr(a),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,a,u),a=e.cmov(l,c,d);const h=e.eql(e.sqr(a),t),p=e.cmov(n,a,h);return assertIsSquare(e,p,t),p}}function tonelliShanks(e){if(e<_3n$1)throw new Error("sqrt is not defined for small field");let t=e-_1n$3,n=0;for(;t%_2n$2===_0n$3;)t/=_2n$2,n++;let s=_2n$2;const r=Field(e);for(;1===FpLegendre(r,s);)if(s++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return sqrt3mod4;let i=r.pow(s,t);const o=(t+_1n$3)/_2n$2;return function(e,s){if(e.is0(s))return s;if(1!==FpLegendre(e,s))throw new Error("Cannot find square root");let r=n,a=e.mul(e.ONE,i),c=e.pow(s,t),l=e.pow(s,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===r)throw new Error("Cannot find square root");const s=_1n$3<<BigInt(r-t-1),i=e.pow(a,s);r=t,a=e.sqr(i),c=e.mul(c,a),l=e.mul(l,i)}return l}}function FpSqrt(e){return e%_4n$1===_3n$1?sqrt3mod4:e%_8n===_5n?sqrt5mod8:e%_16n===_9n?sqrt9mod16(e):tonelliShanks(e)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(e){return _validateObject(e,FIELD_FIELDS.reduce((e,t)=>(e[t]="function",e),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"})),e}function FpPow(e,t,n){if(n<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(n===_0n$3)return e.ONE;if(n===_1n$3)return t;let s=e.ONE,r=t;for(;n>_0n$3;)n&_1n$3&&(s=e.mul(s,r)),r=e.sqr(r),n>>=_1n$3;return s}function FpInvertBatch(e,t,n=!1){const s=new Array(t.length).fill(n?e.ZERO:void 0),r=t.reduce((t,n,r)=>e.is0(n)?t:(s[r]=t,e.mul(t,n)),e.ONE),i=e.inv(r);return t.reduceRight((t,n,r)=>e.is0(n)?t:(s[r]=e.mul(t,s[r]),e.mul(t,n)),i),s}function FpLegendre(e,t){const n=(e.ORDER-_1n$3)/_2n$2,s=e.pow(t,n),r=e.eql(s,e.ONE),i=e.eql(s,e.ZERO),o=e.eql(s,e.neg(e.ONE));if(!r&&!i&&!o)throw new Error("invalid Legendre symbol result");return r?1:i?0:-1}function nLength(e,t){void 0!==t&&anumber(t);const n=void 0!==t?t:e.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Field(e,t,n=!1,s={}){if(e<=_0n$3)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,i,o,a=!1;if("object"==typeof t&&null!=t){if(s.sqrt||n)throw new Error("cannot specify opts in two arguments");const e=t;e.BITS&&(r=e.BITS),e.sqrt&&(i=e.sqrt),"boolean"==typeof e.isLE&&(n=e.isLE),"boolean"==typeof e.modFromBytes&&(a=e.modFromBytes),o=e.allowedLengths}else"number"==typeof t&&(r=t),s.sqrt&&(i=s.sqrt);const{nBitLength:c,nByteLength:l}=nLength(e,r);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:bitMask(c),ZERO:_0n$3,ONE:_1n$3,allowedLengths:o,create:t=>mod(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return _0n$3<=t&&t<e},is0:e=>e===_0n$3,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&_1n$3)===_1n$3,neg:t=>mod(-t,e),eql:(e,t)=>e===t,sqr:t=>mod(t*t,e),add:(t,n)=>mod(t+n,e),sub:(t,n)=>mod(t-n,e),mul:(t,n)=>mod(t*n,e),pow:(e,t)=>FpPow(d,e,t),div:(t,n)=>mod(t*invert(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>invert(t,e),sqrt:i||(t=>(u||(u=FpSqrt(e)),u(d,t))),toBytes:e=>n?numberToBytesLE(e,l):numberToBytesBE(e,l),fromBytes:(t,s=!0)=>{if(o){if(!o.includes(t.length)||t.length>l)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);const e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+t.length);let r=n?bytesToNumberLE(t):bytesToNumberBE(t);if(a&&(r=mod(r,e)),!s&&!d.isValid(r))throw new Error("invalid field element: outside of range 0..ORDER");return r},invertBatch:e=>FpInvertBatch(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function getFieldBytesLength(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function getMinHashLength(e){const t=getFieldBytesLength(e);return t+Math.ceil(t/2)}function mapHashToField(e,t,n=!1){const s=e.length,r=getFieldBytesLength(t),i=getMinHashLength(t);if(s<16||s<i||s>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+s);const o=mod(n?bytesToNumberLE(e):bytesToNumberBE(e),t-_1n$3)+_1n$3;return n?numberToBytesLE(o,r):numberToBytesBE(o,r)}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$2=BigInt(1);function negateCt(e,t){const n=t.negate();return e?n:t}function normalizeZ(e,t){const n=FpInvertBatch(e.Fp,t.map(e=>e.Z));return t.map((t,s)=>e.fromAffine(t.toAffine(n[s])))}function validateW(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function calcWOpts(e,t){validateW(e,t);const n=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:bitMask(e),maxNumber:n,shiftBy:BigInt(e)}}function calcOffsets(e,t,n){const{windowSize:s,mask:r,maxNumber:i,shiftBy:o}=n;let a=Number(e&r),c=e>>o;a>s&&(a-=i,c+=_1n$2);const l=t*s;return{nextN:c,offset:l+Math.abs(a)-1,isZero:0===a,isNeg:a<0,isNegF:t%2!=0,offsetF:l}}function validateMSMPoints(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((e,n)=>{if(!(e instanceof t))throw new Error("invalid point at index "+n)})}function validateMSMScalars(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((e,n)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+n)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(e){return pointWindowSizes.get(e)||1}function assert0(e){if(e!==_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,n=this.ZERO){let s=e;for(;t>_0n$2;)t&_1n$2&&(n=n.add(s)),s=s.double(),t>>=_1n$2;return n}precomputeWindow(e,t){const{windows:n,windowSize:s}=calcWOpts(t,this.bits),r=[];let i=e,o=i;for(let e=0;e<n;e++){o=i,r.push(o);for(let e=1;e<s;e++)o=o.add(i),r.push(o);i=o.double()}return r}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,r=this.BASE;const i=calcWOpts(e,this.bits);for(let e=0;e<i.windows;e++){const{nextN:o,offset:a,isZero:c,isNeg:l,isNegF:u,offsetF:d}=calcOffsets(n,e,i);n=o,c?r=r.add(negateCt(u,t[d])):s=s.add(negateCt(l,t[a]))}return assert0(n),{p:s,f:r}}wNAFUnsafe(e,t,n,s=this.ZERO){const r=calcWOpts(e,this.bits);for(let e=0;e<r.windows&&n!==_0n$2;e++){const{nextN:i,offset:o,isZero:a,isNeg:c}=calcOffsets(n,e,r);if(n=i,!a){const e=t[o];s=s.add(c?e.negate():e)}}return assert0(n),s}getPrecomputes(e,t,n){let s=pointPrecomputes.get(t);return s||(s=this.precomputeWindow(t,e),1!==e&&("function"==typeof n&&(s=n(s)),pointPrecomputes.set(t,s))),s}cached(e,t,n){const s=getW(e);return this.wNAF(s,this.getPrecomputes(s,e,n),t)}unsafe(e,t,n,s){const r=getW(e);return 1===r?this._unsafeLadder(e,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,e,n),t,s)}createCache(e,t){validateW(t,this.bits),pointWindowSizes.set(e,t),pointPrecomputes.delete(e)}hasCache(e){return 1!==getW(e)}}function mulEndoUnsafe(e,t,n,s){let r=t,i=e.ZERO,o=e.ZERO;for(;n>_0n$2||s>_0n$2;)n&_1n$2&&(i=i.add(r)),s&_1n$2&&(o=o.add(r)),r=r.double(),n>>=_1n$2,s>>=_1n$2;return{p1:i,p2:o}}function pippenger(e,t,n,s){validateMSMPoints(n,e),validateMSMScalars(s,t);const r=n.length,i=s.length;if(r!==i)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=bitLen(BigInt(r));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=bitMask(c),u=new Array(Number(l)+1).fill(o);let d=o;for(let e=Math.floor((t.BITS-1)/c)*c;e>=0;e-=c){u.fill(o);for(let t=0;t<i;t++){const r=s[t],i=Number(r>>BigInt(e)&l);u[i]=u[i].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(d=d.add(t),0!==e)for(let e=0;e<c;e++)d=d.double()}return d}function createField(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return validateField(t),t}return Field(e,{isLE:n})}function _createCurveFields(e,t,n={},s){if(void 0===s&&(s="edwards"===e),!t||"object"!=typeof t)throw new Error(`expected valid ${e} CURVE object`);for(const e of["p","n","h"]){const n=t[e];if(!("bigint"==typeof n&&n>_0n$2))throw new Error(`CURVE.${e} must be positive bigint`)}const r=createField(t.p,n.Fp,s),i=createField(t.n,n.Fn,s),o=["Gx","Gy","a","weierstrass"===e?"b":"d"];for(const e of o)if(!r.isValid(t[e]))throw new Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:r,Fn:i}}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const divNearest=(e,t)=>(e+(e>=0?t:-t)/_2n$1)/t;function _splitEndoScalar(e,t,n){const[[s,r],[i,o]]=t,a=divNearest(o*e,n),c=divNearest(-r*e,n);let l=e-a*s-c*i,u=-a*r-c*o;const d=l<_0n$1,h=u<_0n$1;d&&(l=-l),h&&(u=-u);const p=bitMask(Math.ceil(bitLen(n)/2))+_1n$1;if(l<_0n$1||l>=p||u<_0n$1||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:l,k2neg:h,k2:u}}function validateSigFormat(e){if(!["compact","recovered","der"].includes(e))throw new Error('Signature format must be "compact", "recovered", or "der"');return e}function validateSigOpts(e,t){const n={};for(let s of Object.keys(t))n[s]=void 0===e[s]?t[s]:e[s];return _abool2(n.lowS,"lowS"),_abool2(n.prehash,"prehash"),void 0!==n.format&&validateSigFormat(n.format),n}class DERErr extends Error{constructor(e=""){super(e)}}const DER={Err:DERErr,_tlv:{encode:(e,t)=>{const{Err:n}=DER;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(1&t.length)throw new n("tlv.encode: unpadded data");const s=t.length/2,r=numberToHexUnpadded(s);if(r.length/2&128)throw new n("tlv.encode: long form length too big");const i=s>127?numberToHexUnpadded(r.length/2|128):"";return numberToHexUnpadded(e)+i+r+t},decode(e,t){const{Err:n}=DER;let s=0;if(e<0||e>256)throw new n("tlv.encode: wrong tag");if(t.length<2||t[s++]!==e)throw new n("tlv.decode: wrong tlv");const r=t[s++];let i=0;if(!!(128&r)){const e=127&r;if(!e)throw new n("tlv.decode(long): indefinite length not supported");if(e>4)throw new n("tlv.decode(long): byte length is too big");const o=t.subarray(s,s+e);if(o.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===o[0])throw new n("tlv.decode(long): zero leftmost byte");for(const e of o)i=i<<8|e;if(s+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=r;const o=t.subarray(s,s+i);if(o.length!==i)throw new n("tlv.decode: wrong value length");return{v:o,l:t.subarray(s+i)}}},_int:{encode(e){const{Err:t}=DER;if(e<_0n$1)throw new t("integer: negative integers are not allowed");let n=numberToHexUnpadded(e);if(8&Number.parseInt(n[0],16)&&(n="00"+n),1&n.length)throw new t("unexpected DER parsing assertion: unpadded hex");return n},decode(e){const{Err:t}=DER;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return bytesToNumberBE(e)}},toSig(e){const{Err:t,_int:n,_tlv:s}=DER,r=ensureBytes("signature",e),{v:i,l:o}=s.decode(48,r);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=s.decode(2,i),{v:l,l:u}=s.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(e){const{_tlv:t,_int:n}=DER,s=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,s)}},_0n$1=BigInt(0),_1n$1=BigInt(1),_2n$1=BigInt(2),_3n=BigInt(3),_4n=BigInt(4);function _normFnElement(e,t){const{BYTES:n}=e;let s;if("bigint"==typeof t)s=t;else{let r=ensureBytes("private key",t);try{s=e.fromBytes(r)}catch(e){throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}function weierstrassN(e,t={}){const n=_createCurveFields("weierstrass",e,t),{Fp:s,Fn:r}=n;let i=n.CURVE;const{h:o,n:a}=i;_validateObject(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=t;if(c&&(!s.is0(i.a)||"bigint"!=typeof c.beta||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=getWLengths(s,r);function u(){if(!s.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}const d=t.toBytes||function(e,t,n){const{x:r,y:i}=t.toAffine(),o=s.toBytes(r);if(_abool2(n,"isCompressed"),n){u();return concatBytes(pprefix(!s.isOdd(i)),o)}return concatBytes(Uint8Array.of(4),o,s.toBytes(i))},h=t.fromBytes||function(e){_abytes2(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=l,r=e.length,i=e[0],o=e.subarray(1);if(r!==t||2!==i&&3!==i){if(r===n&&4===i){const e=s.BYTES,t=s.fromBytes(o.subarray(0,e)),n=s.fromBytes(o.subarray(e,2*e));if(!f(t,n))throw new Error("bad point: is not on curve");return{x:t,y:n}}throw new Error(`bad point: got length ${r}, expected compressed=${t} or uncompressed=${n}`)}{const e=s.fromBytes(o);if(!s.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=p(e);let n;try{n=s.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("bad point: is not on curve, sqrt error"+t)}u();return!(1&~i)!==s.isOdd(n)&&(n=s.neg(n)),{x:e,y:n}}};function p(e){const t=s.sqr(e),n=s.mul(t,e);return s.add(s.add(n,s.mul(e,i.a)),i.b)}function f(e,t){const n=s.sqr(t),r=p(e);return s.eql(n,r)}if(!f(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const g=s.mul(s.pow(i.a,_3n),_4n),y=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(g,y)))throw new Error("bad curve params: a or b");function m(e,t,n=!1){if(!s.isValid(t)||n&&s.is0(t))throw new Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof E))throw new Error("ProjectivePoint expected")}function v(e){if(!c||!c.basises)throw new Error("no endo");return _splitEndoScalar(e,c.basises,r.ORDER)}const _=memoized((e,t)=>{const{X:n,Y:r,Z:i}=e;if(s.eql(i,s.ONE))return{x:n,y:r};const o=e.is0();null==t&&(t=o?s.ONE:s.inv(i));const a=s.mul(n,t),c=s.mul(r,t),l=s.mul(i,t);if(o)return{x:s.ZERO,y:s.ZERO};if(!s.eql(l,s.ONE))throw new Error("invZ was invalid");return{x:a,y:c}}),w=memoized(e=>{if(e.is0()){if(t.allowInfinityPoint&&!s.is0(e.Y))return;throw new Error("bad point: ZERO")}const{x:n,y:r}=e.toAffine();if(!s.isValid(n)||!s.isValid(r))throw new Error("bad point: x or y not field elements");if(!f(n,r))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(e,t,n,r,i){return n=new E(s.mul(n.X,e),n.Y,n.Z),t=negateCt(r,t),n=negateCt(i,n),t.add(n)}class E{constructor(e,t,n){this.X=m("x",e),this.Y=m("y",t,!0),this.Z=m("z",n),Object.freeze(this)}static CURVE(){return i}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!s.isValid(t)||!s.isValid(n))throw new Error("invalid affine point");if(e instanceof E)throw new Error("projective point not allowed");return s.is0(t)&&s.is0(n)?E.ZERO:new E(t,n,s.ONE)}static fromBytes(e){const t=E.fromAffine(h(_abytes2(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return E.fromBytes(ensureBytes("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return $.createCache(this,e),t||this.multiply(_3n),this}assertValidity(){w(this)}hasEvenY(){const{y:e}=this.toAffine();if(!s.isOdd)throw new Error("Field doesn't support isOdd");return!s.isOdd(e)}equals(e){b(e);const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:a}=e,c=s.eql(s.mul(t,a),s.mul(i,r)),l=s.eql(s.mul(n,a),s.mul(o,r));return c&&l}negate(){return new E(this.X,s.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=s.mul(t,_3n),{X:r,Y:o,Z:a}=this;let c=s.ZERO,l=s.ZERO,u=s.ZERO,d=s.mul(r,r),h=s.mul(o,o),p=s.mul(a,a),f=s.mul(r,o);return f=s.add(f,f),u=s.mul(r,a),u=s.add(u,u),c=s.mul(e,u),l=s.mul(n,p),l=s.add(c,l),c=s.sub(h,l),l=s.add(h,l),l=s.mul(c,l),c=s.mul(f,c),u=s.mul(n,u),p=s.mul(e,p),f=s.sub(d,p),f=s.mul(e,f),f=s.add(f,u),u=s.add(d,d),d=s.add(u,d),d=s.add(d,p),d=s.mul(d,f),l=s.add(l,d),p=s.mul(o,a),p=s.add(p,p),d=s.mul(p,f),c=s.sub(c,d),u=s.mul(p,h),u=s.add(u,u),u=s.add(u,u),new E(c,l,u)}add(e){b(e);const{X:t,Y:n,Z:r}=this,{X:o,Y:a,Z:c}=e;let l=s.ZERO,u=s.ZERO,d=s.ZERO;const h=i.a,p=s.mul(i.b,_3n);let f=s.mul(t,o),g=s.mul(n,a),y=s.mul(r,c),m=s.add(t,n),v=s.add(o,a);m=s.mul(m,v),v=s.add(f,g),m=s.sub(m,v),v=s.add(t,r);let _=s.add(o,c);return v=s.mul(v,_),_=s.add(f,y),v=s.sub(v,_),_=s.add(n,r),l=s.add(a,c),_=s.mul(_,l),l=s.add(g,y),_=s.sub(_,l),d=s.mul(h,v),l=s.mul(p,y),d=s.add(l,d),l=s.sub(g,d),d=s.add(g,d),u=s.mul(l,d),g=s.add(f,f),g=s.add(g,f),y=s.mul(h,y),v=s.mul(p,v),g=s.add(g,y),y=s.sub(f,y),y=s.mul(h,y),v=s.add(v,y),f=s.mul(g,v),u=s.add(u,f),f=s.mul(_,v),l=s.mul(m,l),l=s.sub(l,f),f=s.mul(m,g),d=s.mul(_,d),d=s.add(d,f),new E(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(E.ZERO)}multiply(e){const{endo:n}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,i;const o=e=>$.cached(this,e,e=>normalizeZ(E,e));if(n){const{k1neg:t,k1:r,k2neg:a,k2:c}=v(e),{p:l,f:u}=o(r),{p:d,f:h}=o(c);i=u.add(h),s=k(n.beta,l,d,t,a)}else{const{p:t,f:n}=o(e);s=t,i=n}return normalizeZ(E,[s,i])[0]}multiplyUnsafe(e){const{endo:n}=t,s=this;if(!r.isValid(e))throw new Error("invalid scalar: out of range");if(e===_0n$1||s.is0())return E.ZERO;if(e===_1n$1)return s;if($.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:r,k2neg:i,k2:o}=v(e),{p1:a,p2:c}=mulEndoUnsafe(E,s,r,o);return k(n.beta,a,c,t,i)}return $.unsafe(s,e)}multiplyAndAddUnsafe(e,t,n){const s=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return s.is0()?void 0:s}toAffine(e){return _(this,e)}isTorsionFree(){const{isTorsionFree:e}=t;return o===_1n$1||(e?e(E,this):$.unsafe(this,a).is0())}clearCofactor(){const{clearCofactor:e}=t;return o===_1n$1?this:e?e(E,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return _abool2(e,"isCompressed"),this.assertValidity(),d(E,this,e)}toHex(e=!0){return bytesToHex(this.toBytes(e))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return normalizeZ(E,e)}static msm(e,t){return pippenger(E,r,e,t)}static fromPrivateKey(e){return E.BASE.multiply(_normFnElement(r,e))}}E.BASE=new E(i.Gx,i.Gy,s.ONE),E.ZERO=new E(s.ZERO,s.ONE,s.ZERO),E.Fp=s,E.Fn=r;const x=r.BITS,$=new wNAF(E,t.endo?Math.ceil(x/2):x);return E.BASE.precompute(8),E}function pprefix(e){return Uint8Array.of(e?2:3)}function getWLengths(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function ecdh(e,t={}){const{Fn:n}=e,s=t.randomBytes||randomBytes,r=Object.assign(getWLengths(e.Fp,n),{seed:getMinHashLength(n.ORDER)});function i(e){try{return!!_normFnElement(n,e)}catch(e){return!1}}function o(e=s(r.seed)){return mapHashToField(_abytes2(e,r.seed,"seed"),n.ORDER)}function a(t,s=!0){return e.BASE.multiply(_normFnElement(n,t)).toBytes(s)}function c(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:s,publicKey:i,publicKeyUncompressed:o}=r;if(n.allowedLengths||s===i)return;const a=ensureBytes("key",t).length;return a===i||a===o}const l={isValidSecretKey:i,isValidPublicKey:function(t,n){const{publicKey:s,publicKeyUncompressed:i}=r;try{const r=t.length;return(!0!==n||r===s)&&((!1!==n||r===i)&&!!e.fromBytes(t))}catch(e){return!1}},randomSecretKey:o,isValidPrivateKey:i,randomPrivateKey:o,normPrivateKeyToScalar:e=>_normFnElement(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:a,getSharedSecret:function(t,s,r=!0){if(!0===c(t))throw new Error("first arg must be private key");if(!1===c(s))throw new Error("second arg must be public key");const i=_normFnElement(n,t);return e.fromHex(s).multiply(i).toBytes(r)},keygen:function(e){const t=o(e);return{secretKey:t,publicKey:a(t)}},Point:e,utils:l,lengths:r})}function ecdsa(e,t,n={}){ahash(t),_validateObject(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const s=n.randomBytes||randomBytes,r=n.hmac||((e,...n)=>hmac(t,e,concatBytes(...n))),{Fp:i,Fn:o}=e,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=ecdh(e,n),f={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},g="compact";function y(e){return e>a>>_1n$1}function m(e,t){if(!o.isValidNot0(t))throw new Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}class b{constructor(e,t,n){this.r=m("r",e),this.s=m("s",t),null!=n&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=g){let n;if(function(e,t){validateSigFormat(t);const n=p.signature;_abytes2(e,"compact"===t?n:"recovered"===t?n+1:void 0,`${t} signature`)}(e,t),"der"===t){const{r:t,s:n}=DER.toSig(_abytes2(e));return new b(t,n)}"recovered"===t&&(n=e[0],t="compact",e=e.subarray(1));const s=o.BYTES,r=e.subarray(0,s),i=e.subarray(s,2*s);return new b(o.fromBytes(r),o.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(hexToBytes(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:s,s:r,recovery:c}=this;if(null==c||![0,1,2,3].includes(c))throw new Error("recovery id invalid");if(a*_2n$1<n&&c>1)throw new Error("recovery id is ambiguous for h>1 curve");const l=2===c||3===c?s+a:s;if(!i.isValid(l))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(l),d=e.fromBytes(concatBytes(pprefix(!(1&c)),u)),h=o.inv(l),p=_(ensureBytes("msgHash",t)),f=o.create(-p*h),g=o.create(r*h),y=e.BASE.multiplyUnsafe(f).add(d.multiplyUnsafe(g));if(y.is0())throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return y(this.s)}toBytes(e=g){if(validateSigFormat(e),"der"===e)return hexToBytes(DER.hexFromSig(this));const t=o.toBytes(this.r),n=o.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return concatBytes(Uint8Array.of(this.recovery),t,n)}return concatBytes(t,n)}toHex(e){return bytesToHex(this.toBytes(e))}assertValidity(){}static fromCompact(e){return b.fromBytes(ensureBytes("sig",e),"compact")}static fromDER(e){return b.fromBytes(ensureBytes("sig",e),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex(this.toBytes("compact"))}}const v=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=bytesToNumberBE(e),n=8*e.length-c;return n>0?t>>BigInt(n):t},_=n.bits2int_modN||function(e){return o.create(v(e))},w=bitMask(c);function k(e){return aInRange("num < 2^"+c,e,_0n$1,w),o.toBytes(e)}function E(e,n){return _abytes2(e,void 0,"message"),n?_abytes2(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:e,sign:function(n,i,a={}){n=ensureBytes("message",n);const{seed:c,k2sig:l}=function(t,n,r){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:a,extraEntropy:c}=validateSigOpts(r,f);t=E(t,a);const l=_(t),u=_normFnElement(o,n),d=[k(u),k(l)];if(null!=c&&!1!==c){const e=!0===c?s(p.secretKey):c;d.push(ensureBytes("extraEntropy",e))}const h=concatBytes(...d),g=l;return{seed:h,k2sig:function(t){const n=v(t);if(!o.isValidNot0(n))return;const s=o.inv(n),r=e.BASE.multiply(n).toAffine(),a=o.create(r.x);if(a===_0n$1)return;const c=o.create(s*o.create(g+a*u));if(c===_0n$1)return;let l=(r.x===a?0:2)|Number(r.y&_1n$1),d=c;return i&&y(c)&&(d=o.neg(c),l^=1),new b(a,d,l)}}}(n,i,a);return createHmacDrbg(t.outputLen,o.BYTES,r)(c,l)},verify:function(t,n,s,r={}){const{lowS:i,prehash:a,format:c}=validateSigOpts(r,f);if(s=ensureBytes("publicKey",s),n=E(ensureBytes("message",n),a),"strict"in r)throw new Error("options.strict was renamed to lowS");const l=void 0===c?function(e){let t;const n="string"==typeof e||isBytes(e),s=!n&&null!==e&&"object"==typeof e&&"bigint"==typeof e.r&&"bigint"==typeof e.s;if(!n&&!s)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(s)t=new b(e.r,e.s);else if(n){try{t=b.fromBytes(ensureBytes("sig",e),"der")}catch(e){if(!(e instanceof DER.Err))throw e}if(!t)try{t=b.fromBytes(ensureBytes("sig",e),"compact")}catch(e){return!1}}return t||!1}(t):b.fromBytes(ensureBytes("sig",t),c);if(!1===l)return!1;try{const t=e.fromBytes(s);if(i&&l.hasHighS())return!1;const{r:r,s:a}=l,c=_(n),u=o.inv(a),d=o.create(c*u),h=o.create(r*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(h));if(p.is0())return!1;return o.create(p.x)===r}catch(e){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:s}=validateSigOpts(n,f);return t=E(t,s),b.fromBytes(e,"recovered").recoverPublicKey(t).toBytes()},Signature:b,hash:t})}function _weierstrass_legacy_opts_to_new(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let s=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Field(t.n,{BITS:e.nBitLength,allowedLengths:s,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function _ecdsa_legacy_opts_to_new(e){const{CURVE:t,curveOpts:n}=_weierstrass_legacy_opts_to_new(e),s={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:s}}function _ecdsa_new_output_to_legacy(e,t){const n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,nLength(n.Fn.ORDER,n.Fn.BITS))})}function weierstrass(e){const{CURVE:t,curveOpts:n,hash:s,ecdsaOpts:r}=_ecdsa_legacy_opts_to_new(e);return _ecdsa_new_output_to_legacy(e,ecdsa(weierstrassN(t,n),s,r))}
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createCurve(e,t){const n=t=>weierstrass({...e,hash:t});return{...n(t),create:n}}
/*! 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(e){const t=secp256k1_CURVE.p,n=BigInt(3),s=BigInt(6),r=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,d=pow2(u,n,t)*u%t,h=pow2(d,n,t)*u%t,p=pow2(h,_2n,t)*l%t,f=pow2(p,r,t)*p%t,g=pow2(f,i,t)*f%t,y=pow2(g,a,t)*g%t,m=pow2(y,c,t)*y%t,b=pow2(m,a,t)*g%t,v=pow2(b,n,t)*u%t,_=pow2(v,o,t)*f%t,w=pow2(_,s,t)*l%t,k=pow2(w,_2n,t);if(!Fpk1.eql(Fpk1.sqr(k),e))throw new Error("Cannot find square root");return k}const Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod}),secp256k1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$1),TAGGED_HASH_PREFIXES={};function taggedHash(e,...t){let n=TAGGED_HASH_PREFIXES[e];if(void 0===n){const t=sha256$1(utf8ToBytes(e));n=concatBytes(t,t),TAGGED_HASH_PREFIXES[e]=n}return sha256$1(concatBytes(n,...t))}const pointToBytes=e=>e.toBytes(!0).slice(1),Pointk1=(()=>secp256k1.Point)(),hasEven=e=>e%_2n===_0n;function schnorrGetExtPubKey(e){const{Fn:t,BASE:n}=Pointk1,s=_normFnElement(t,e),r=n.multiply(s);return{scalar:hasEven(r.y)?s:t.neg(s),bytes:pointToBytes(r)}}function lift_x(e){const t=Fpk1;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),s=t.create(n*e+BigInt(7));let r=t.sqrt(s);hasEven(r)||(r=t.neg(r));const i=Pointk1.fromAffine({x:e,y:r});return i.assertValidity(),i}const num=bytesToNumberBE;function challenge(...e){return Pointk1.Fn.create(num(taggedHash("BIP0340/challenge",...e)))}function schnorrGetPublicKey(e){return schnorrGetExtPubKey(e).bytes}function schnorrSign(e,t,n=randomBytes(32)){const{Fn:s}=Pointk1,r=ensureBytes("message",e),{bytes:i,scalar:o}=schnorrGetExtPubKey(t),a=ensureBytes("auxRand",n,32),c=s.toBytes(o^num(taggedHash("BIP0340/aux",a))),l=taggedHash("BIP0340/nonce",c,i,r),{bytes:u,scalar:d}=schnorrGetExtPubKey(l),h=challenge(u,i,r),p=new Uint8Array(64);if(p.set(u,0),p.set(s.toBytes(s.create(d+h*o)),32),!schnorrVerify(p,r,i))throw new Error("sign: Invalid signature produced");return p}function schnorrVerify(e,t,n){const{Fn:s,BASE:r}=Pointk1,i=ensureBytes("signature",e,64),o=ensureBytes("message",t),a=ensureBytes("publicKey",n,32);try{const e=lift_x(num(a)),t=num(i.subarray(0,32));if(!inRange(t,_1n,secp256k1_CURVE.p))return!1;const n=num(i.subarray(32,64));if(!inRange(n,_1n,secp256k1_CURVE.n))return!1;const c=challenge(s.toBytes(t),pointToBytes(e),o),l=r.multiplyUnsafe(n).add(e.multiplyUnsafe(s.neg(c))),{x:u,y:d}=l.toAffine();return!(l.is0()||!hasEven(d)||u!==t)}catch(e){return!1}}const schnorr=(()=>{const e=(e=randomBytes(48))=>mapHashToField(e,secp256k1_CURVE.n);return secp256k1.utils.randomSecretKey,{keygen:function(t){const n=e(t);return{secretKey:n,publicKey:schnorrGetPublicKey(n)}},getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,Point:Pointk1,utils:{randomSecretKey:e,randomPrivateKey:e,taggedHash:taggedHash,lift_x:lift_x,pointToBytes:pointToBytes,numberToBytesBE:numberToBytesBE,bytesToNumberBE:bytesToNumberBE,mod:mod},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,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,n){const{entryExpirationTimeInMS:s=null,next:r=null,prev:i=null,onEntryEvicted:o,onEntryMarkedAsMostRecentlyUsed:a,clone:c,cloneFn:l}=null!=n?n:{};if("number"==typeof s&&(s<=0||Number.isNaN(s)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.clone=null!=c&&c,this.cloneFn=null!=l?l:this.defaultClone,this.key=e,this.internalValue=this.clone?this.cloneFn(t):t,this.created=Date.now(),this.entryExpirationTimeInMS=s,this.next=r,this.prev=i,this.onEntryEvicted=o,this.onEntryMarkedAsMostRecentlyUsed=a}get value(){return this.clone?this.cloneFn(this.internalValue):this.internalValue}get isExpired(){return"number"==typeof this.entryExpirationTimeInMS&&Date.now()-this.created>this.entryExpirationTimeInMS}invokeOnEvicted(){if(this.onEntryEvicted){const{key:e,value:t,isExpired:n}=this;this.onEntryEvicted({key:e,value:t,isExpired:n})}}invokeOnEntryMarkedAsMostRecentlyUsed(){if(this.onEntryMarkedAsMostRecentlyUsed){const{key:e,value:t}=this;this.onEntryMarkedAsMostRecentlyUsed({key:e,value:t})}}defaultClone(e){return"boolean"==typeof e||"string"==typeof e||"number"==typeof e?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:n=null,onEntryEvicted:s,onEntryMarkedAsMostRecentlyUsed:r,cloneFn:i,clone:o}=null!=e?e:{};if(Number.isNaN(t)||t<=0)throw new Error("maxSize must be greater than 0.");if("number"==typeof n&&(n<=0||Number.isNaN(n)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.maxSizeInternal=t,this.entryExpirationTimeInMS=n,this.onEntryEvicted=s,this.onEntryMarkedAsMostRecentlyUsed=r,this.clone=o,this.cloneFn=i}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,n){const s=this.lookupTable.get(e);s&&this.removeNodeFromListAndLookupTable(s);const r=new LRUCacheNode_1.LRUCacheNode(e,t,{entryExpirationTimeInMS:this.entryExpirationTimeInMS,onEntryEvicted:this.onEntryEvicted,onEntryMarkedAsMostRecentlyUsed:this.onEntryMarkedAsMostRecentlyUsed,clone:this.clone,cloneFn:this.cloneFn,...n});return this.setNodeAsHead(r),this.lookupTable.set(e,r),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)}has(e){const t=this.lookupTable.get(e);return!!t&&(!t.isExpired||(this.removeNodeFromListAndLookupTable(t),!1))}clear(){this.head=null,this.tail=null,this.lookupTable.clear()}find(e){let t=this.head;for(;t;){if(t.isExpired){const e=t.next;this.removeNodeFromListAndLookupTable(t),t=e;continue}const n=this.mapNodeToEntry(t);if(e(n))return this.setNodeAsHead(t),n;t=t.next}return null}forEach(e){let t=this.head,n=0;for(;t;){if(t.isExpired){const e=t.next;this.removeNodeFromListAndLookupTable(t),t=e;continue}e(t.value,t.key,n),t=t.next,n++}}*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(;null!==e&&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){null!==e.prev&&(e.prev.next=e.next),null!==e.next&&(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(e=>this.removeNodeFromListAndLookupTable(e))}}function pbkdf2Init(e,t,n,s){assert.hash(e);const r=checkOpts$1({dkLen:32,asyncTick:10},s),{c:i,dkLen:o,asyncTick:a}=r;if(assert.number(i),assert.number(o),assert.number(a),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=toBytes$2(t),l=toBytes$2(n),u=new Uint8Array(o),d=hmac$1.create(e,c),h=d._cloneInto().update(l);return{c:i,dkLen:o,asyncTick:a,DK:u,PRF:d,PRFSalt:h}}function pbkdf2Output(e,t,n,s,r){return e.destroy(),t.destroy(),s&&s.destroy(),r.fill(0),n}function pbkdf2(e,t,n,s){const{c:r,dkLen:i,DK:o,PRF:a,PRFSalt:c}=pbkdf2Init(e,t,n,s);let l;const u=new Uint8Array(4),d=createView$2(u),h=new Uint8Array(a.outputLen);for(let e=1,t=0;t<i;e++,t+=a.outputLen){const n=o.subarray(t,t+a.outputLen);d.setInt32(0,e,!1),(l=c._cloneInto(l)).update(u).digestInto(h),n.set(h.subarray(0,n.length));for(let e=1;e<r;e++){a._cloneInto(l).update(h).digestInto(h);for(let e=0;e<n.length;e++)n[e]^=h[e]}}return pbkdf2Output(a,c,o,l,h)}LRUCache$1.LRUCache=LRUCache,function(e){var t=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(e,t,n,s){void 0===s&&(s=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,r)}:function(e,t,n,s){void 0===s&&(s=n),e[s]=t[n]}),n=commonjsGlobal&&commonjsGlobal.__exportStar||function(e,n){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(n,s)||t(n,e,s)};Object.defineProperty(e,"__esModule",{value:!0}),n(LRUCache$1,e)}(dist);const rotl=(e,t)=>e<<t|e>>>32-t;function XorAndSalsa(e,t,n,s,r,i){let o=e[t++]^n[s++],a=e[t++]^n[s++],c=e[t++]^n[s++],l=e[t++]^n[s++],u=e[t++]^n[s++],d=e[t++]^n[s++],h=e[t++]^n[s++],p=e[t++]^n[s++],f=e[t++]^n[s++],g=e[t++]^n[s++],y=e[t++]^n[s++],m=e[t++]^n[s++],b=e[t++]^n[s++],v=e[t++]^n[s++],_=e[t++]^n[s++],w=e[t++]^n[s++],k=o,E=a,x=c,$=l,S=u,T=d,A=h,R=p,N=f,C=g,I=y,B=m,P=b,D=v,L=_,F=w;for(let e=0;e<8;e+=2)S^=rotl(k+P|0,7),N^=rotl(S+k|0,9),P^=rotl(N+S|0,13),k^=rotl(P+N|0,18),C^=rotl(T+E|0,7),D^=rotl(C+T|0,9),E^=rotl(D+C|0,13),T^=rotl(E+D|0,18),L^=rotl(I+A|0,7),x^=rotl(L+I|0,9),A^=rotl(x+L|0,13),I^=rotl(A+x|0,18),$^=rotl(F+B|0,7),R^=rotl($+F|0,9),B^=rotl(R+$|0,13),F^=rotl(B+R|0,18),E^=rotl(k+$|0,7),x^=rotl(E+k|0,9),$^=rotl(x+E|0,13),k^=rotl($+x|0,18),A^=rotl(T+S|0,7),R^=rotl(A+T|0,9),S^=rotl(R+A|0,13),T^=rotl(S+R|0,18),B^=rotl(I+C|0,7),N^=rotl(B+I|0,9),C^=rotl(N+B|0,13),I^=rotl(C+N|0,18),P^=rotl(F+L|0,7),D^=rotl(P+F|0,9),L^=rotl(D+P|0,13),F^=rotl(L+D|0,18);r[i++]=o+k|0,r[i++]=a+E|0,r[i++]=c+x|0,r[i++]=l+$|0,r[i++]=u+S|0,r[i++]=d+T|0,r[i++]=h+A|0,r[i++]=p+R|0,r[i++]=f+N|0,r[i++]=g+C|0,r[i++]=y+I|0,r[i++]=m+B|0,r[i++]=b+P|0,r[i++]=v+D|0,r[i++]=_+L|0,r[i++]=w+F|0}function BlockMix(e,t,n,s,r){let i=s+0,o=s+16*r;for(let s=0;s<16;s++)n[o+s]=e[t+16*(2*r-1)+s];for(let s=0;s<r;s++,i+=16,t+=16)XorAndSalsa(n,o,e,t,n,i),s>0&&(o+=16),XorAndSalsa(n,i,e,t+=16,n,o)}function scryptInit(e,t,n){const s=checkOpts$1({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:r,r:i,p:o,dkLen:a,asyncTick:c,maxmem:l,onProgress:u}=s;if(assert.number(r),assert.number(i),assert.number(o),assert.number(a),assert.number(c),assert.number(l),void 0!==u&&"function"!=typeof u)throw new Error("progressCb should be function");const d=128*i,h=d/4;if(r<=1||r&r-1||r>=2**(d/8)||r>2**32)throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32");if(o<0||o>137438953440/d)throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");if(a<0||a>137438953440)throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");const p=d*(r+o);if(p>l)throw new Error(`Scrypt: parameters too large, ${p} (128 * r * (N + p)) > ${l} (maxmem)`);const f=pbkdf2(sha256$2,e,t,{c:1,dkLen:d*o}),g=u32$1(f),y=u32$1(new Uint8Array(d*r)),m=u32$1(new Uint8Array(d));let b=()=>{};if(u){const e=2*r*o,t=Math.max(Math.floor(e/1e4),1);let n=0;b=()=>{n++,!u||n%t&&n!==e||u(n/e)}}return{N:r,r:i,p:o,dkLen:a,blockSize32:h,V:y,B32:g,B:f,tmp:m,blockMixCb:b,asyncTick:c}}function scryptOutput(e,t,n,s,r){const i=pbkdf2(sha256$2,e,n,{c:1,dkLen:t});return n.fill(0),s.fill(0),r.fill(0),i}function scrypt(e,t,n){const{N:s,r:r,p:i,dkLen:o,blockSize32:a,V:c,B32:l,B:u,tmp:d,blockMixCb:h}=scryptInit(e,t,n);for(let e=0;e<i;e++){const t=a*e;for(let e=0;e<a;e++)c[e]=l[t+e];for(let e=0,t=0;e<s-1;e++)BlockMix(c,t,c,t+=a,r),h();BlockMix(c,(s-1)*a,l,t,r),h();for(let e=0;e<s;e++){const e=l[t+a-16]%s;for(let n=0;n<a;n++)d[n]=l[t+n]^c[e*a+n];BlockMix(d,0,l,t,r),h()}}return scryptOutput(e,o,u,c,d)}var Bech32MaxSize$1=5e3;function encodeBech32$1(e,t){let n=bech32.toWords(t);return bech32.encode(e,n,Bech32MaxSize$1)}function encodeBytes$1(e,t){return encodeBech32$1(e,t)}function encrypt$1(e,t,n=16,s=2){let r=randomBytes$1(16),i=2**n,o=scrypt(t.normalize("NFKC"),r,{N:i,r:8,p:1,dkLen:32}),a=randomBytes$1(24),c=Uint8Array.from([s]),l=xchacha20poly1305(o,a,c).encrypt(e);return encodeBytes$1("ncryptsec",concatBytes$1(Uint8Array.from([2]),Uint8Array.from([n]),r,a,c,l))}function decrypt$1(e,t){let{prefix:n,words:s}=bech32.decode(e,Bech32MaxSize$1);if("ncryptsec"!==n)throw new Error(`invalid prefix ${n}, expected 'ncryptsec'`);let r=new Uint8Array(bech32.fromWords(s)),i=r[0];if(2!==i)throw new Error(`invalid version ${i}, expected 0x02`);let o=2**r[1],a=r.slice(2,18),c=r.slice(18,42),l=r[42],u=Uint8Array.from([l]),d=r.slice(43),h=scrypt(t.normalize("NFKC"),a,{N:o,r:8,p:1,dkLen:32});return xchacha20poly1305(h,c,u).decrypt(d)}var nip49_star=Object.freeze({__proto__:null,decrypt:decrypt$1,encrypt:encrypt$1}),utf8Decoder=new TextDecoder("utf-8"),utf8Encoder=new TextEncoder,NostrTypeGuard={isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},Bech32MaxSize=5e3,BECH32_REGEX$1=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}function decodeNostrURI(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),decode(e)}catch(e){return{type:"invalid",data:null}}}function decode(e){let{prefix:t,words:n}=bech32.decode(e,Bech32MaxSize),s=new Uint8Array(bech32.fromWords(n));switch(t){case"nprofile":{let e=parseTLV(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder.decode(e)):[]}}}case"nevent":{let e=parseTLV(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==e[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(e[2]&&32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(e[3]&&4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$1(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder.decode(e)):[],author:e[2]?.[0]?bytesToHex$1(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$1(e[3][0]),16):void 0}}}case"naddr":{let e=parseTLV(s);if(!e[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!e[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==e[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!e[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==e[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder.decode(e[0][0]),pubkey:bytesToHex$1(e[2][0]),kind:parseInt(bytesToHex$1(e[3][0]),16),relays:e[1]?e[1].map(e=>utf8Decoder.decode(e)):[]}}}case"nsec":return{type:t,data:s};case"npub":case"note":return{type:t,data:bytesToHex$1(s)};default:throw new Error(`unknown prefix ${t}`)}}function parseTLV(e){let t={},n=e;for(;n.length>0;){let e=n[0],s=n[1],r=n.slice(2,2+s);if(n=n.slice(2+s),r.length<s)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(r)}return t}function nsecEncode(e){return encodeBytes("nsec",e)}function npubEncode(e){return encodeBytes("npub",hexToBytes$1(e))}function noteEncode(e){return encodeBytes("note",hexToBytes$1(e))}function encodeBech32(e,t){let n=bech32.toWords(t);return bech32.encode(e,n,Bech32MaxSize)}function encodeBytes(e,t){return encodeBech32(e,t)}function nprofileEncode(e){return encodeBech32("nprofile",encodeTLV({0:[hexToBytes$1(e.pubkey)],1:(e.relays||[]).map(e=>utf8Encoder.encode(e))}))}function neventEncode(e){let t;return void 0!==e.kind&&(t=integerToUint8Array(e.kind)),encodeBech32("nevent",encodeTLV({0:[hexToBytes$1(e.id)],1:(e.relays||[]).map(e=>utf8Encoder.encode(e)),2:e.author?[hexToBytes$1(e.author)]:[],3:t?[new Uint8Array(t)]:[]}))}function naddrEncode(e){let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,e.kind,!1),encodeBech32("naddr",encodeTLV({0:[utf8Encoder.encode(e.identifier)],1:(e.relays||[]).map(e=>utf8Encoder.encode(e)),2:[hexToBytes$1(e.pubkey)],3:[new Uint8Array(t)]}))}function encodeTLV(e){let t=[];return Object.entries(e).reverse().forEach(([e,n])=>{n.forEach(n=>{let s=new Uint8Array(n.length+2);s.set([parseInt(e)],0),s.set([n.length],1),s.set(n,2),t.push(s)})}),concatBytes$1(...t)}var nip19_star=Object.freeze({__proto__:null,BECH32_REGEX:BECH32_REGEX$1,Bech32MaxSize:Bech32MaxSize,NostrTypeGuard:NostrTypeGuard,decode:decode,decodeNostrURI:decodeNostrURI,encodeBytes:encodeBytes,naddrEncode:naddrEncode,neventEncode:neventEncode,noteEncode:noteEncode,nprofileEncode:nprofileEncode,npubEncode:npubEncode,nsecEncode:nsecEncode}),lib={};!function(e){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const t=(e,t)=>n=>e(t(n)),n=Array.from(e).reverse().reduce((e,n)=>e?t(e,n.encode):n.encode,void 0),s=e.reduce((e,n)=>e?t(e,n.decode):n.decode,void 0);return{encode:n,decode:s}}function s(e){return{encode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("alphabet.encode input should be an array of numbers");return n.map(n=>{if(t(n),n<0||n>=e.length)throw new Error(`Digit index outside alphabet: ${n} (alphabet: ${e.length})`);return e[n]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const n=e.indexOf(t);if(-1===n)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return n})}}}function r(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function i(e,n="="){if(t(e),"string"!=typeof n)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(n);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let s=t.length;if(s*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;s>0&&t[s-1]===n;s--)if(!((s-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,s)}}}function o(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function a(e,n,s){if(n<2)throw new Error(`convertRadix: wrong from=${n}, base cannot be less than 2`);if(s<2)throw new Error(`convertRadix: wrong to=${s}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let r=0;const i=[],o=Array.from(e);for(o.forEach(e=>{if(t(e),e<0||e>=n)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=r;i<o.length;i++){const a=o[i],c=n*e+a;if(!Number.isSafeInteger(c)||n*e/n!==e||c-a!==n*e)throw new Error("convertRadix: carry overflow");if(e=c%s,o[i]=Math.floor(c/s),!Number.isSafeInteger(o[i])||o[i]*s+e!==c)throw new Error("convertRadix: carry overflow");t&&(o[i]?t=!1:r=i)}if(i.push(e),t)break}for(let t=0;t<e.length-1&&0===e[t];t++)i.push(0);return i.reverse()}
/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
Object.defineProperty(e,"__esModule",{value:!0}),e.bytes=e.stringToBytes=e.str=e.bytesToString=e.hex=e.utf8=e.bech32m=e.bech32=e.base58check=e.base58xmr=e.base58xrp=e.base58flickr=e.base58=e.base64url=e.base64=e.base32crockford=e.base32hex=e.base32=e.base16=e.utils=e.assertNumber=void 0,e.assertNumber=t;const c=(e,t)=>t?c(t,e%t):e,l=(e,t)=>e+(t-c(e,t));function u(e,n,s,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(l(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${l(n,s)}`);let i=0,o=0;const a=2**s-1,c=[];for(const r of e){if(t(r),r>=2**n)throw new Error(`convertRadix2: invalid data word=${r} from=${n}`);if(i=i<<n|r,o+n>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${n}`);for(o+=n;o>=s;o-=s)c.push((i>>o-s&a)>>>0);i&=2**o-1}if(i=i<<s-o&a,!r&&o>=n)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&c.push(i>>>0),c}function d(e){return t(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return a(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(a(t,e,256))}}}function h(e,n=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(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 u(Array.from(t),8,e,!n)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(u(t,e,8,n))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function f(e,n){if(t(e),"function"!=typeof n)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 s=n(t).slice(0,e),r=new Uint8Array(t.length+e);return r.set(t),r.set(s,t.length),r},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const s=t.slice(0,-e),r=n(s).slice(0,e),i=t.slice(-e);for(let t=0;t<e;t++)if(r[t]!==i[t])throw new Error("Invalid checksum");return s}}}e.utils={alphabet:s,chain:n,checksum:f,radix:d,radix2:h,join:r,padding:i},e.base16=n(h(4),s("0123456789ABCDEF"),r("")),e.base32=n(h(5),s("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),i(5),r("")),e.base32hex=n(h(5),s("0123456789ABCDEFGHIJKLMNOPQRSTUV"),i(5),r("")),e.base32crockford=n(h(5),s("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),r(""),o(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),e.base64=n(h(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),i(6),r("")),e.base64url=n(h(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),i(6),r(""));const g=e=>n(d(58),s(e),r(""));e.base58=g("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.base58flickr=g("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),e.base58xrp=g("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[0,2,3,5,6,7,9,10,11];e.base58xmr={encode(t){let n="";for(let s=0;s<t.length;s+=8){const r=t.subarray(s,s+8);n+=e.base58.encode(r).padStart(y[r.length],"1")}return n},decode(t){let n=[];for(let s=0;s<t.length;s+=11){const r=t.slice(s,s+11),i=y.indexOf(r.length),o=e.base58.decode(r);for(let e=0;e<o.length-i;e++)if(0!==o[e])throw new Error("base58xmr: wrong padding");n=n.concat(Array.from(o.slice(o.length-i)))}return Uint8Array.from(n)}};e.base58check=t=>n(f(4,e=>t(t(e))),e.base58);const m=n(s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),r("")),b=[996825010,642813549,513874426,1027748829,705979059];function v(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<b.length;e++)1==(t>>e&1)&&(n^=b[e]);return n}function _(e,t,n=1){const s=e.length;let r=1;for(let t=0;t<s;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);r=v(r)^n>>5}r=v(r);for(let t=0;t<s;t++)r=v(r)^31&e.charCodeAt(t);for(let e of t)r=v(r)^e;for(let e=0;e<6;e++)r=v(r);return r^=n,m.encode(u([r%2**30],30,5,!1))}function w(e){const t="bech32"===e?1:734539939,n=h(5),s=n.decode,r=n.encode,i=p(s);function o(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const s=e.toLowerCase();if(e!==s&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const r=(e=s).lastIndexOf("1");if(0===r||-1===r)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,r),o=e.slice(r+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const a=m.decode(o).slice(0,-6),c=_(i,a,t);if(!o.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,n,s=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const r=e.length+7+n.length;if(!1!==s&&r>s)throw new TypeError(`Length ${r} exceeds limit ${s}`);return`${e=e.toLowerCase()}1${m.encode(n)}${_(e,n,t)}`},decode:o,decodeToBytes:function(e){const{prefix:t,words:n}=o(e,!1);return{prefix:t,words:n,bytes:s(n)}},decodeUnsafe:p(o),fromWords:s,fromWordsUnsafe:i,toWords:r}}e.bech32=w("bech32"),e.bech32m=w("bech32m"),e.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},e.hex=n(h(4),s("0123456789abcdef"),r(""),o(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const k={utf8:e.utf8,hex:e.hex,base16:e.base16,base32:e.base32,base64:e.base64,base64url:e.base64url,base58:e.base58,base58xmr:e.base58xmr},E=`Invalid encoding type. Available types: ${Object.keys(k).join(", ")}`;e.bytesToString=(e,t)=>{if("string"!=typeof e||!k.hasOwnProperty(e))throw new TypeError(E);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return k[e].encode(t)},e.str=e.bytesToString;e.stringToBytes=(e,t)=>{if(!k.hasOwnProperty(e))throw new TypeError(E);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return k[e].decode(t)},e.bytes=e.stringToBytes}(lib),BigInt(1e3),BigInt(1e6),BigInt(1e9),BigInt(1e12),BigInt("2100000000000000000"),BigInt(1e11);const 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};for(let e=0,t=Object.keys(TAGCODES);e<t.length;e++)t[e],TAGCODES[t[e]].toString();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of __getOwnPropNames(t))__hasOwnProp.call(e,r)||r===n||__defProp(e,r,{get:()=>t[r],enumerable:!(s=__getOwnPropDesc(t,r))||s.enumerable});return e},__reExport=(e,t,n)=>(__copyProps(e,t,"default"),n&&__copyProps(n,t,"default"));function getRelaysForSync(e,t,n="write"){if(!e.outboxTracker)return;const s=e.outboxTracker.data.get(t);return s?"write"===n?s.writeRelays:s.readRelays:void 0}async function getWriteRelaysFor(e,t,n="write"){if(e.outboxTracker)return e.outboxTracker.data.has(t)||await e.outboxTracker.trackUsers([t]),getRelaysForSync(e,t,n)}function getTopRelaysForAuthors(e,t){const n=new Map;t.forEach(t=>{const s=getRelaysForSync(e,t);s&&s.forEach(e=>{const t=n.get(e)||0;n.set(e,t+1)})});return Array.from(n.entries()).sort((e,t)=>t[1]-e[1]).map(e=>e[0])}function getAllRelaysForAllPubkeys(e,t,n="read"){const s=new Map,r=new Set;return t.forEach(t=>{const i=getRelaysForSync(e,t,n);i&&i.size>0?(i.forEach(e=>{(s.get(e)||new Set).add(t)}),s.set(t,i)):r.add(t)}),{pubkeysToRelays:s,authorsMissingRelays:r}}function chooseRelayCombinationForPubkeys(e,t,n,{count:s,preferredRelays:r}={}){s??=2,r??=new Set;const i=e.pool,o=i.connectedRelays();o.forEach(e=>{r?.add(e.url)});const a=new Map,{pubkeysToRelays:c,authorsMissingRelays:l}=getAllRelaysForAllPubkeys(e,t,n),u=getTopRelaysForAuthors(e,t),d=(e,t)=>{const n=a.get(t)||[];n.push(e),a.set(t,n)};for(const[e,t]of c.entries()){let n=s;const r=new Set;for(const s of o)t.has(s.url)&&(d(e,s.url),r.add(s.url),n--);for(const s of t)r.has(s)||a.has(s)&&(d(e,s),r.add(s),n--);if(!(n<=0))for(const s of u){if(n<=0)break;r.has(s)||t.has(s)&&(d(e,s),r.add(s),n--)}}for(const e of l)i.permanentAndConnectedRelays().forEach(t=>{const n=a.get(t.url)||[];n.push(e),a.set(t.url,n)});return a}function getRelaysForFilterWithAuthors(e,t,n=2){return chooseRelayCombinationForPubkeys(e,t,"write",{count:n})}function tryNormalizeRelayUrl(e){try{return normalizeRelayUrl(e)}catch{return}}function normalizeRelayUrl(e){let t=normalizeUrl(e,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return t.endsWith("/")||(t+="/"),t}function normalize(e){const t=new Set;for(const n of e)try{t.add(normalizeRelayUrl(n))}catch{}return Array.from(t)}var DATA_URL_DEFAULT_MIME_TYPE="text/plain",DATA_URL_DEFAULT_CHARSET="us-ascii",testParameter=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e),supportedProtocols=new Set(["https:","http:","file:"]),hasCustomProtocol=e=>{try{const{protocol:t}=new URL(e);return t.endsWith(":")&&!t.includes(".")&&!supportedProtocols.has(t)}catch{return!1}},normalizeDataURL=(e,{stripHash:t})=>{const n=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!n)throw new Error(`Invalid URL: ${e}`);const s=n.groups?.type??"",r=n.groups?.data??"";let i=n.groups?.hash??"";const o=s.split(";");i=t?"":i;let a=!1;"base64"===o[o.length-1]&&(o.pop(),a=!0);const c=o.shift()?.toLowerCase()??"",l=[...o.map(e=>{let[t,n=""]=e.split("=").map(e=>e.trim());return"charset"===t&&(n=n.toLowerCase(),n===DATA_URL_DEFAULT_CHARSET)?"":`${t}${n?`=${n}`:""}`}).filter(Boolean)];return a&&l.push("base64"),(l.length>0||c&&c!==DATA_URL_DEFAULT_MIME_TYPE)&&l.unshift(c),`data:${l.join(";")},${a?r.trim():r}${i?`#${i}`:""}`};function normalizeUrl(e,t={}){if("string"!=typeof(t={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,...t}).defaultProtocol||t.defaultProtocol.endsWith(":")||(t.defaultProtocol=`${t.defaultProtocol}:`),e=e.trim(),/^data:/i.test(e))return normalizeDataURL(e,t);if(hasCustomProtocol(e))return e;const n=e.startsWith("//");!n&&/^\.*\//.test(e)||(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));const s=new URL(e);if(s.hostname=s.hostname.toLowerCase(),t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&"https:"===s.protocol&&(s.protocol="http:"),t.forceHttps&&"http:"===s.protocol&&(s.protocol="https:"),t.stripAuthentication&&(s.username="",s.password=""),t.stripHash?s.hash="":t.stripTextFragment&&(s.hash=s.hash.replace(/#?:~:text.*?$/i,"")),s.pathname){const e=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let t=0,n="";for(;;){const r=e.exec(s.pathname);if(!r)break;const i=r[0],o=r.index;n+=s.pathname.slice(t,o).replace(/\/{2,}/g,"/"),n+=i,t=o+i.length}n+=s.pathname.slice(t,s.pathname.length).replace(/\/{2,}/g,"/"),s.pathname=n}if(s.pathname)try{s.pathname=decodeURI(s.pathname)}catch{}if(!0===t.removeDirectoryIndex&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=s.pathname.split("/");const n=e[e.length-1];testParameter(n,t.removeDirectoryIndex)&&(e=e.slice(0,-1),s.pathname=`${e.slice(1).join("/")}/`)}if(s.hostname&&(s.hostname=s.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(s.hostname)&&(s.hostname=s.hostname.replace(/^www\./,""))),Array.isArray(t.removeQueryParameters))for(const e of[...s.searchParams.keys()])testParameter(e,t.removeQueryParameters)&&s.searchParams.delete(e);if(Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(s.search=""),Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const e of[...s.searchParams.keys()])testParameter(e,t.keepQueryParameters)||s.searchParams.delete(e);if(t.sortQueryParameters){s.searchParams.sort();try{s.search=decodeURIComponent(s.search)}catch{}}t.removeTrailingSlash&&(s.pathname=s.pathname.replace(/\/$/,"")),t.removeExplicitPort&&s.port&&(s.port="");const r=e;return e=s.toString(),t.removeSingleSlash||"/"!==s.pathname||r.endsWith("/")||""!==s.hash||(e=e.replace(/\/$/,"")),(t.removeTrailingSlash||"/"===s.pathname)&&""===s.hash&&t.removeSingleSlash&&(e=e.replace(/\/$/,"")),n&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,"//")),t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,"")),e}var NDKRelayKeepalive=class{constructor(e=3e4,t){this.onSilenceDetected=t,this.timeout=e}lastActivity=Date.now();timer;timeout;isRunning=!1;recordActivity(){this.lastActivity=Date.now(),this.isRunning&&this.resetTimer()}start(){this.isRunning||(this.isRunning=!0,this.lastActivity=Date.now(),this.resetTimer())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{const e=Date.now()-this.lastActivity;if(e>=this.timeout)this.onSilenceDetected();else{const t=this.timeout-e;this.timer=setTimeout(()=>{this.onSilenceDetected()},t)}},this.timeout)}};async function probeRelayConnection(e){const t=`probe-${Math.random().toString(36).substring(7)}`;return new Promise(n=>{let s=!1;const r=setTimeout(()=>{s||(s=!0,e.send(["CLOSE",t]),n(!1))},5e3);e.once("message",()=>{s||(s=!0,clearTimeout(r),e.send(["CLOSE",t]),n(!0))}),e.send(["REQ",t,{kinds:[99999],limit:0}])})}var MAX_RECONNECT_ATTEMPTS=5,FLAPPING_THRESHOLD_MS=1e3,NDKRelayConnectivity=class{ndkRelay;ws;_status;timeoutMs;connectedAt;_connectionStats={attempts:0,success:0,durations:[]};debug;netDebug;connectTimeout;reconnectTimeout;ndk;openSubs=new Map;openCountRequests=new Map;openEventPublishes=new Map;serial=0;baseEoseTimeout=4400;keepalive;wsStateMonitor;sleepDetector;lastSleepCheck=Date.now();lastMessageSent=Date.now();wasIdle=!1;constructor(e,t){this.ndkRelay=e,this._status=1;const n=Math.floor(1e3*Math.random());this.debug=this.ndkRelay.debug.extend(`connectivity${n}`),this.ndk=t,this.setupMonitoring()}setupMonitoring(){this.keepalive=new NDKRelayKeepalive(12e4,async()=>{this.debug("Relay silence detected, probing connection");await probeRelayConnection({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const s=JSON.parse(e.data);"EOSE"!==s[0]&&"EVENT"!==s[0]&&"NOTICE"!==s[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}})||(this.debug("Probe failed, connection is stale"),this.handleStaleConnection())}),this.wsStateMonitor=setInterval(()=>{5===this._status&&(this.ws&&this.ws.readyState===WebSocket.OPEN||(this.debug("WebSocket died silently, reconnecting"),this.handleStaleConnection()))},5e3),this.sleepDetector=setInterval(()=>{const e=Date.now(),t=e-this.lastSleepCheck;t>15e3&&(this.debug(`Detected possible sleep/wake (${t}ms gap)`),this.handlePossibleWake()),this.lastSleepCheck=e},1e4)}handleStaleConnection(){this._status=1,this.wasIdle=!0,this.onDisconnect()}handlePossibleWake(){this.debug("System wake detected, checking all connections"),this.wasIdle=!0,this._status>=5&&(this.ws&&this.ws.readyState===WebSocket.OPEN?probeRelayConnection({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const s=JSON.parse(e.data);"EOSE"!==s[0]&&"EVENT"!==s[0]&&"NOTICE"!==s[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}}).then(e=>{e||this.handleStaleConnection()}):this.handleStaleConnection())}resetReconnectionState(){this.wasIdle=!0,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}async connect(e,t=!0){if(this.ws&&this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING){this.debug("Cleaning up stale WebSocket connection");try{this.ws.close()}catch(e){}this.ws=void 0,this._status=1}if(2!==this._status&&1!==this._status||this.reconnectTimeout)this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);else{this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),e??=this.timeoutMs,!this.timeoutMs&&e&&(this.timeoutMs=e),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(t),this.timeoutMs));try{this.updateConnectionStats.attempt(),1===this._status?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(e){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,e),this._status=1,t?this.handleReconnection():this.ndkRelay.emit("delayed-connect",1728e5),e}}}disconnect(){this._status=0,this.keepalive?.stop(),this.wsStateMonitor&&(clearInterval(this.wsStateMonitor),this.wsStateMonitor=void 0),this.sleepDetector&&(clearInterval(this.sleepDetector),this.sleepDetector=void 0);try{this.ws?.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(e){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),e&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){this.netDebug?.("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.keepalive?.start(),this.wasIdle=!1,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){this.netDebug?.("disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this.keepalive?.stop(),5===this._status&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(e){this.netDebug?.(e.data,this.ndkRelay,"recv"),this.keepalive?.recordActivity();try{const t=JSON.parse(e.data),[n,s,...r]=t,i=this.ndkRelay.getProtocolHandler(n);if(i)return void i(this.ndkRelay,t);switch(n){case"EVENT":{const e=this.openSubs.get(s),n=t[2];return e?void e.onevent(n):void this.debug(`Received event for unknown subscription ${s}`)}case"COUNT":{const e=t[2],n=this.openCountRequests.get(s);return void(n&&(n.resolve(e.count),this.openCountRequests.delete(s)))}case"EOSE":{const e=this.openSubs.get(s);if(!e)return;return void e.oneose(s)}case"OK":{const e=t[2],n=t[3],r=this.openEventPublishes.get(s),i=r?.pop();return r&&i?(e?i.resolve(n):i.reject(new Error(n)),void(0===r.length?this.openEventPublishes.delete(s):this.openEventPublishes.set(s,r))):void this.debug("Received OK for unknown event publish",s)}case"CLOSED":{const e=this.openSubs.get(s);if(!e)return;return void e.onclosed(t[2])}case"NOTICE":return void this.onNotice(t[1]);case"AUTH":return void this.onAuthRequested(t[1])}}catch(e){return void this.debug(`Error parsing message from ${this.ndkRelay.url}: ${e.message}`,e?.stack)}}async onAuthRequested(e){const t=this.ndkRelay.authPolicy??this.ndk?.relayAuthDefaultPolicy;if(this.debug("Relay requested authentication",{havePolicy:!!t}),7!==this._status)if(this._status=6,t){if(this._status>=5){let n;this._status=7;try{n=await t(this.ndkRelay,e)}catch(e){this.debug("Authentication policy threw an error",e),n=!1}if(this.debug("Authentication policy returned",!!n),n instanceof NDKEvent||!0===n){n instanceof NDKEvent&&await this.auth(n);const t=async()=>{if(this._status>=5&&this._status<8){const t=new NDKEvent(this.ndk);t.kind=22242,t.tags=[["relay",this.ndkRelay.url],["challenge",e]],await t.sign(),this.auth(t).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(e=>{this._status=6,this.ndkRelay.emit("auth:failed",e),this.debug("Authentication failed",e)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};!0===n&&(this.ndk?.signer?t().catch(e=>{console.error("Error authenticating",e)}):(this.debug("No signer available for authentication localhost"),this.ndk?.once("signer:ready",t))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",e);else this.debug("Already authenticating, ignoring")}onError(e){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,e)}get status(){return this._status}isAvailable(){return 5===this._status}isFlapping(){const e=this._connectionStats.durations;if(e.length%3!=0)return!1;const t=e.reduce((e,t)=>e+t,0)/e.length,n=e.map(e=>(e-t)**2).reduce((e,t)=>e+t,0)/e.length;return Math.sqrt(n)<FLAPPING_THRESHOLD_MS}async onNotice(e){this.ndkRelay.emit("notice",e)}handleReconnection(e=0){if(this.reconnectTimeout)return;if(this.isFlapping())return this.ndkRelay.emit("flapping",this._connectionStats),void(this._status=3);let t;if(this.wasIdle){const n=[0,1e3,2e3,5e3,1e4,3e4];t=n[Math.min(e,n.length-1)],this.debug(`Using aggressive reconnect after idle, attempt ${e}, delay ${t}ms`)}else this.connectedAt?t=Math.max(0,6e4-(Date.now()-this.connectedAt)):(t=Math.min(1e3*2**e,3e4),this.debug(`Using standard backoff, attempt ${e}, delay ${t}ms`));this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{e<MAX_RECONNECT_ATTEMPTS?this.handleReconnection(e+1):(this.debug("Max reconnect attempts reached"),this.wasIdle=!1)})},t),this.ndkRelay.emit("delayed-connect",t),this.debug("Reconnecting in",t),this._connectionStats.nextReconnectAt=Date.now()+t}async send(e){Date.now()-this.lastMessageSent>12e4&&(this.wasIdle=!0),this._status>=5&&this.ws?.readyState===WebSocket.OPEN?(this.ws?.send(e),this.netDebug?.(e,this.ndkRelay,"send"),this.lastMessageSent=Date.now()):(this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${e}`,this._status),this._status>=5&&this.ws?.readyState!==WebSocket.OPEN&&(this.debug(`Stale connection detected, WebSocket state: ${this.ws?.readyState}`),this.handleStaleConnection()))}async auth(e){const t=new Promise((t,n)=>{const s=this.openEventPublishes.get(e.id)??[];s.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,s)});return this.send(`["AUTH",${JSON.stringify(e.rawEvent())}]`),t}async publish(e){const t=new Promise((t,n)=>{const s=this.openEventPublishes.get(e.id)??[];s.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${e.id} twice`),s.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,s)});return this.send(`["EVENT",${JSON.stringify(e)}]`),t}async count(e,t){this.serial++;const n=t?.id||`count:${this.serial}`,s=new Promise((e,t)=>{this.openCountRequests.set(n,{resolve:e,reject:t})});return this.send(`["COUNT","${n}",${JSON.stringify(e).substring(1)}`),s}close(e,t){this.send(`["CLOSE","${e}"]`);const n=this.openSubs.get(e);this.openSubs.delete(e),n&&n.onclose(t)}req(e){this.send(`["REQ","${e.subId}",${JSON.stringify(e.executeFilters).substring(1)}`),this.openSubs.set(e.subId,e)}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()}};get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){return this._status>=5&&this.ws?.readyState===WebSocket.OPEN}};async function fetchRelayInformation(e){const t=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://"),n=await fetch(t,{headers:{Accept:"application/nostr+json"}});if(!n.ok)throw new Error(`Failed to fetch relay information: ${n.status} ${n.statusText}`);return await n.json()}var NDKRelayPublisher=class{ndkRelay;debug;constructor(e){this.ndkRelay=e,this.debug=e.debug.extend("publisher")}async publish(e,t=2500){let n;const s=()=>new Promise((t,n)=>{try{this.publishEvent(e).then(n=>{this.ndkRelay.emit("published",e),e.emit("relay:published",this.ndkRelay),t(!0)}).catch(n)}catch(e){n(e)}}),r=new Promise((e,s)=>{n=setTimeout(()=>{n=void 0,s(new Error(`Timeout: ${t}ms`))},t)}),i=()=>{s().then(e=>o(e)).catch(e=>a(e))};let o,a;const c=t=>{throw this.ndkRelay.debug("Publish failed",t,e.id),this.ndkRelay.emit("publish:failed",e,t),e.emit("relay:publish:failed",this.ndkRelay,t),t},l=()=>{n&&clearTimeout(n),this.ndkRelay.removeListener("connect",i)};return this.ndkRelay.status>=5?Promise.race([s(),r]).catch(c).finally(l):(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((e,t)=>{o=e,a=t,this.ndkRelay.on("connect",i)}),r]).catch(c).finally(l))}async publishEvent(e){return this.ndkRelay.connectivity.publish(e.rawEvent())}};function filterFingerprint(e,t){const n=[];for(const t of e){const e=Object.entries(t||{}).map(([e,t])=>["since","until"].includes(e)?`${e}:${t}`:e).sort().join("-");n.push(e)}let s=t?"+":"";return s+=n.join("|"),s}function mergeFilters(e){const t=[],n={};return e.filter(e=>!!e.limit).forEach(e=>t.push(e)),0===(e=e.filter(e=>!e.limit)).length?t:(e.forEach(e=>{Object.entries(e).forEach(([e,t])=>{Array.isArray(t)?void 0===n[e]?n[e]=[...t]:n[e]=Array.from(new Set([...n[e],...t])):n[e]=t})}),[...t,n])}var MAX_ITEMS=3;function formatArray(e,t){const n=(t?e.slice(0,MAX_ITEMS).map(t):e.slice(0,MAX_ITEMS)).join(",");return e.length>MAX_ITEMS?`${n}+${e.length-MAX_ITEMS}`:n}function formatFilters(e){return e.map(e=>{const t=[];e.ids?.length&&t.push(`ids:[${formatArray(e.ids,e=>String(e).slice(0,8))}]`),e.kinds?.length&&t.push(`kinds:[${formatArray(e.kinds)}]`),e.authors?.length&&t.push(`authors:[${formatArray(e.authors,e=>String(e).slice(0,8))}]`),e.since&&t.push(`since:${e.since}`),e.until&&t.push(`until:${e.until}`),e.limit&&t.push(`limit:${e.limit}`),e.search&&t.push(`search:"${String(e.search).slice(0,20)}"`);for(const[n,s]of Object.entries(e))n.startsWith("#")&&Array.isArray(s)&&s.length>0&&t.push(`${n}:[${formatArray(s,e=>String(e).slice(0,8))}]`);return`{${t.join(" ")}}`}).join(", ")}var NDKRelaySubscription=class{fingerprint;items=new Map;topSubManager;debug;status=0;onClose;relay;eosed=!1;executionTimer;fireTime;delayType;executeFilters;id=Math.random().toString(36).substring(7);constructor(e,t,n){this.relay=e,this.topSubManager=n,this.debug=e.debug.extend(`sub[${this.id}]`),this.fingerprint=t||Math.random().toString(36).substring(7)}_subId;get subId(){return this._subId||(this._subId=this.fingerprint.slice(0,15)),this._subId}subIdParts=new Set;addSubIdPart(e){this.subIdParts.add(e)}addItem(e,t){if(this.debug("Adding item",{filters:formatFilters(t),internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,itemsSize:this.items.size}),!this.items.has(e.internalId))switch(e.on("close",this.removeItem.bind(this,e)),this.items.set(e.internalId,{subscription:e,filters:t}),3!==this.status&&e.subId&&(!this._subId||this._subId.length<48)&&(0!==this.status&&1!==this.status||this.addSubIdPart(e.subId)),this.status){case 0:case 1:this.evaluateExecutionPlan(e);break;case 3:break;case 4:throw this.debug("Subscription is closed, cannot add new items",{filters:formatFilters(t),subId:e.subId,internalId:e.internalId}),new Error("Cannot add new items to a closed subscription")}}removeItem(e){if(this.items.delete(e.internalId),0===this.items.size){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(4===this.status)return;const e=this.status;if(this.status=4,3===e)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:e,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(e){if(!e.isGroupable())return this.status=1,void this.execute();if(e.filters.find(e=>!!e.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10))return this.status=1,void this.execute();const t=e.groupableDelay,n=e.groupableDelayType;if(!t)throw new Error("Cannot group a subscription without a delay");if(0===this.status)this.schedule(t,n);else{const e=this.delayType,s=this.fireTime-Date.now();if("at-least"===e&&"at-least"===n)s<t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-least"===e&&"at-most"===n)s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-most"===e&&"at-most"===n)s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else{if("at-most"!==e||"at-least"!==n)throw new Error(`Unknown delay type combination ${e} ${n}`);s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n))}}}schedule(e,t){this.status=1;const n=Date.now();this.fireTime=n+e,this.delayType=t;const s=setTimeout(this.execute.bind(this),e);"at-least"===t&&(this.executionTimer=s)}executeOnRelayReady=()=>{if(2===this.status){if(0===this.items.size)return 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,id:this.id,subId:this.subId}),void this.cleanup();this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,itemsSize:this.items.size,filters:formatFilters(this.compileFilters())}),this.status=1,this.execute()}};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)}`}reExecuteAfterAuth=(()=>{const e=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:e}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",e,this.subId)}).bind(this);execute(){if(1===this.status){if(!this.relay.connected)return this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,itemsSize:this.items.size}),void this.relay.once("ready",this.executeOnRelayReady);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(e){this.topSubManager.dispatchEvent(e,this.relay)}oneose(e){if(this.eosed=!0,e!==this.subId)return this.debug("Received EOSE for an abandoned subscription",e,this.subId),void this.relay.close(e);0===this.items.size&&this.close();for(const{subscription:e}of this.items.values())e.eoseReceived(this.relay),e.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:formatFilters(e.filters),internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,itemsSize:this.items.size}),this.removeItem(e))}onclose(e){this.status=4}onclosed(e){if(e)for(const{subscription:t}of this.items.values())t.closedReceived(this.relay,e)}compileFilters(){const e=[],t=Array.from(this.items.values()).map(e=>e.filters);if(!t[0])return this.debug("👀 No filters to merge",{itemsSize:this.items.size}),[];const n=t[0].length;for(let s=0;s<n;s++){const n=mergeFilters(t.map(e=>e[s]));e.push(...n)}return e}},NDKRelaySubscriptionManager=class{relay;subscriptions;generalSubManager;constructor(e,t){this.relay=e,this.subscriptions=new Map,this.generalSubManager=t}addSubscription(e,t){let n;if(e.isGroupable()){const s=filterFingerprint(t,e.closeOnEose);if(s){n=(this.subscriptions.get(s)||[]).find(e=>e.status<3)}n??=this.createSubscription(e,t,s)}else n=this.createSubscription(e,t);n.addItem(e,t)}createSubscription(e,t,n){const s=new NDKRelaySubscription(this.relay,n||null,this.generalSubManager);s.onClose=this.onRelaySubscriptionClose.bind(this);const r=this.subscriptions.get(s.fingerprint)??[];return this.subscriptions.set(s.fingerprint,[...r,s]),s}onRelaySubscriptionClose(e){let t=this.subscriptions.get(e.fingerprint)??[];t?1===t.length?this.subscriptions.delete(e.fingerprint):(t=t.filter(t=>t.id!==e.id),this.subscriptions.set(e.fingerprint,t)):console.warn("Unexpectedly did not find a subscription with fingerprint",e.fingerprint)}},NDKRelay=class e extends lib$1.EventEmitter{url;scores;connectivity;subs;publisher;authPolicy;protocolHandlers=new Map;_relayInfo;lowestValidationRatio;targetValidationRatio;validationRatioFn;validatedEventCount=0;nonValidatedEventCount=0;trusted=!1;complaining=!1;debug;static defaultValidationRatioUpdateFn=(e,t,n)=>{if(void 0===e.lowestValidationRatio||void 0===e.targetValidationRatio)return 1;let s=e.validationRatio;if(e.validationRatio>e.targetValidationRatio){const n=t/100;s=Math.max(e.lowestValidationRatio,e.validationRatio-n)}return s<e.validationRatio?s:e.validationRatio};constructor(t,n,s){super(),this.url=normalizeRelayUrl(t),this.scores=new Map,this.debug=createDebug5(`ndk:relay:${t}`),this.connectivity=new NDKRelayConnectivity(this,s),this.connectivity.netDebug=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=n,this.targetValidationRatio=s?.initialValidationRatio,this.lowestValidationRatio=s?.lowestValidationRatio,this.validationRatioFn=(s?.validationRatioFn??e.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),s||console.trace("relay created without ndk")}updateValidationRatio(){if(this.validationRatioFn&&this.validatedEventCount>0){const e=this.validationRatioFn(this,this.validatedEventCount,this.nonValidatedEventCount);this.targetValidationRatio=e}setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(e,t=!0){return this.connectivity.connect(e,t)}disconnect(){1!==this.status&&this.connectivity.disconnect()}subscribe(e,t){this.subs.addSubscription(e,t)}async publish(e,t=2500){return this.publisher.publish(e,t)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return 0===this.nonValidatedEventCount?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return!this.trusted&&(void 0===this.targetValidationRatio||(this.targetValidationRatio>=1||Math.random()<this.targetValidationRatio))}get connected(){return this.connectivity.connected}req;close;registerProtocolHandler(e,t){this.protocolHandlers.set(e,t)}unregisterProtocolHandler(e){this.protocolHandlers.delete(e)}getProtocolHandler(e){return this.protocolHandlers.get(e)}async fetchInfo(e=!1){const t=this.connectivity.ndk;if(!e&&t?.cacheAdapter?.getRelayStatus){const e=await t.cacheAdapter.getRelayStatus(this.url);if(e?.nip11&&Date.now()-e.nip11.fetchedAt<864e5)return this._relayInfo=e.nip11.data,e.nip11.data}return!e&&this._relayInfo||(this._relayInfo=await fetchRelayInformation(this.url),t?.cacheAdapter?.updateRelayStatus&&await t.cacheAdapter.updateRelayStatus(this.url,{nip11:{data:this._relayInfo,fetchedAt:Date.now()}})),this._relayInfo}get info(){return this._relayInfo}},NDKPublishError=class extends Error{errors;publishedToRelays;intendedRelaySet;constructor(e,t,n,s){super(e),this.errors=t,this.publishedToRelays=n,this.intendedRelaySet=s}get relayErrors(){const e=[];for(const[t,n]of this.errors)e.push(`${t.url}: ${n}`);return e.join("\n")}},NDKRelaySet=class e{relays;debug;ndk;pool;constructor(e,t,n){this.relays=e,this.ndk=t,this.pool=n??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(t,n,s=!0,r){if(!(r=r??n.pool))throw new Error("No pool provided");const i=new Set;for(const e of t){const o=r.relays.get(normalizeRelayUrl(e));if(o)o.status<5&&s&&o.connect(),i.add(o);else{const s=new NDKRelay(normalizeRelayUrl(e),n?.relayAuthDefaultPolicy,n);r.useTemporaryRelay(s,void 0,`requested from fromRelayUrls ${t}`),i.add(s)}}return new e(new Set(i),n,r)}async publish(e,t,n=1){const s=new Set,r=new Map,i=e.isEphemeral();e.publishStatus="pending";const o=e=>{s.add(e)};e.on("relay:published",o);try{const o=Array.from(this.relays).map(n=>new Promise(o=>{const a=t?setTimeout(()=>{s.has(n)||(r.set(n,new Error(`Publish timeout after ${t}ms`)),o(!1))},t):null;n.publish(e,t).then(e=>{a&&clearTimeout(a),e?(s.add(n),o(!0)):o(!1)}).catch(e=>{a&&clearTimeout(a),i||r.set(n,e),o(!1)})}));if(await Promise.all(o),s.size<n){if(!i){const t=new NDKPublishError("Not enough relays received the event ("+s.size+" published, "+n+" required)",r,s,this);throw e.publishStatus="error",e.publishError=t,this.ndk?.emit("event:publish-failed",e,t,this.relayUrls),t}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:s});return s}finally{e.off("relay:published",o)}}get size(){return this.relays.size}},d=createDebug5("ndk:outbox:calculate");async function calculateRelaySetFromEvent(e,t,n){const s=new Set,r=await getWriteRelaysFor(e,t.pubkey);r&&r.forEach(t=>{const n=e.pool?.getRelay(t);n&&s.add(n)});let i=t.tags.filter(e=>["a","e"].includes(e[0])).map(e=>e[2]).filter(e=>e?.startsWith("wss://")).filter(e=>{try{return new URL(e),!0}catch{return!1}}).map(e=>normalizeRelayUrl(e));i=Array.from(new Set(i)).slice(0,5),i.forEach(t=>{const n=e.pool?.getRelay(t,!0,!0);n&&(d("Adding relay hint %s",t),s.add(n))});const o=t.getMatchingTags("p").map(e=>e[1]);if(o.length<5){Array.from(chooseRelayCombinationForPubkeys(e,o,"read",{preferredRelays:new Set(r)}).keys()).forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(d("Adding p-tagged relay %s",t),s.add(n))})}else d("Too many p-tags to consider %d",o.length);if(e.pool?.permanentAndConnectedRelays().forEach(e=>s.add(e)),n&&s.size<n){const t=e.explicitRelayUrls?.filter(e=>!Array.from(s).some(t=>t.url===e)).slice(0,n-s.size);t?.forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(d("Adding explicit relay %s",t),s.add(n))})}return new NDKRelaySet(s,e)}function calculateRelaySetsFromFilter(e,t,n,s){const r=new Map,i=new Set;if(t.forEach(e=>{e.authors&&e.authors.forEach(e=>i.add(e))}),i.size>0){const n=getRelaysForFilterWithAuthors(e,Array.from(i),s);for(const e of n.keys())r.set(e,[]);for(const e of t)if(e.authors)for(const[t,s]of n.entries()){const n=e.authors.filter(e=>s.includes(e));r.set(t,[...r.get(t),{...e,authors:n}])}else for(const t of n.keys())r.set(t,[...r.get(t),e])}else e.explicitRelayUrls&&e.explicitRelayUrls.forEach(e=>{r.set(e,t)});return 0===r.size&&n.permanentAndConnectedRelays().slice(0,5).forEach(e=>{r.set(e.url,t)}),r}function calculateRelaySetsFromFilters(e,t,n,s){return calculateRelaySetsFromFilter(e,t,n,s)}function checkMissingKind(e,t){void 0!==e.kind&&null!==e.kind||t("event-missing-kind",`Cannot sign event without 'kind'.\n\n📦 Event data:\n • content: ${e.content?`"${e.content.substring(0,50)}${e.content.length>50?"...":""}"`:"(empty)"}\n • tags: ${e.tags.length} tag${1!==e.tags.length?"s":""}\n • kind: ${e.kind}\n\nSet event.kind before signing.`,"Example: event.kind = 1; // for text note",!1)}function checkContentIsObject(e,t){if("object"==typeof e.content){const n=JSON.stringify(e.content,null,2).substring(0,200);t("event-content-is-object",`Event content is an object. Content must be a string.\n\n📦 Your content (${typeof e.content}):\n${n}${JSON.stringify(e.content).length>200?"...":""}\n\n❌ event.content = { ... } // WRONG\n✅ event.content = JSON.stringify({ ... }) // CORRECT`,"Use JSON.stringify() for structured data: event.content = JSON.stringify(data)",!1)}}function checkCreatedAtMilliseconds(e,t){if(e.created_at&&e.created_at>1e10){const n=Math.floor(e.created_at/1e3),s=new Date(e.created_at).toISOString();t("event-created-at-milliseconds",`Event created_at is in milliseconds, not seconds.\n\n📦 Your value:\n • created_at: ${e.created_at}\n • Interpreted as: ${s}\n • Should be: ${n}\n\nNostr timestamps MUST be in seconds since Unix epoch.`,"Use Math.floor(Date.now() / 1000) instead of Date.now()",!1)}}function checkInvalidPTags(e,t){e.getMatchingTags("p").forEach((e,n)=>{if(e[1]&&!/^[0-9a-f]{64}$/i.test(e[1])){const s=JSON.stringify(e);t("tag-invalid-p-tag",`p-tag[${n}] has invalid pubkey.\n\n📦 Your tag:\n ${s}\n\n❌ Invalid value: "${e[1]}"\n • Length: ${e[1].length} (expected 64)\n • Format: ${e[1].startsWith("npub")?"bech32 (npub)":"unknown"}\n\np-tags MUST contain 64-character hex pubkeys.`,e[1].startsWith("npub")?"Use ndkUser.pubkey instead of npub:\n ✅ event.tags.push(['p', ndkUser.pubkey])\n ❌ event.tags.push(['p', 'npub1...'])":"p-tags must contain valid hex pubkeys (64 characters, 0-9a-f)",!1)}})}function checkInvalidETags(e,t){e.getMatchingTags("e").forEach((e,n)=>{if(e[1]&&!/^[0-9a-f]{64}$/i.test(e[1])){const s=JSON.stringify(e),r=e[1].startsWith("note")||e[1].startsWith("nevent");t("tag-invalid-e-tag",`e-tag[${n}] has invalid event ID.\n\n📦 Your tag:\n ${s}\n\n❌ Invalid value: "${e[1]}"\n • Length: ${e[1].length} (expected 64)\n • Format: ${r?"bech32 (note/nevent)":"unknown"}\n\ne-tags MUST contain 64-character hex event IDs.`,r?"Use event.id instead of bech32:\n ✅ event.tags.push(['e', referencedEvent.id])\n ❌ event.tags.push(['e', 'note1...'])":"e-tags must contain valid hex event IDs (64 characters, 0-9a-f)",!1)}})}function checkManualReplyMarkers(e,t,n){if(1!==e.kind)return;if(n.has(e))return;const s=e.tags.filter(e=>"e"===e[0]&&("reply"===e[3]||"root"===e[3]));if(s.length>0){const e=s.map((e,t)=>` ${t+1}. ${JSON.stringify(e)}`).join("\n");t("event-manual-reply-markers",`Event has ${s.length} e-tag(s) with manual reply/root markers.\n\n📦 Your tags with markers:\n${e}\n\n⚠️ Manual reply markers detected! This will cause incorrect threading.`,"Reply events MUST be created using .reply():\n\n ✅ CORRECT:\n const replyEvent = originalEvent.reply();\n replyEvent.content = 'good point!';\n await replyEvent.publish();\n\n ❌ WRONG:\n event.tags.push(['e', eventId, '', 'reply']);\n\nNDK handles all reply threading automatically - never add reply/root markers manually.")}}function signing(e,t,n,s){checkMissingKind(e,t),checkContentIsObject(e,t),checkCreatedAtMilliseconds(e,t),checkInvalidPTags(e,t),checkInvalidETags(e,t),checkManualReplyMarkers(e,n,s)}function isNip33Pattern(e){const t=Array.isArray(e)?e:[e];if(1!==t.length)return!1;const n=t[0];return n.kinds&&Array.isArray(n.kinds)&&1===n.kinds.length&&n.authors&&Array.isArray(n.authors)&&1===n.authors.length&&n["#d"]&&Array.isArray(n["#d"])&&1===n["#d"].length}function isSingleIdLookup(e){const t=Array.isArray(e)?e:[e];if(1!==t.length)return!1;const n=t[0];return n.ids&&Array.isArray(n.ids)&&1===n.ids.length}function isReplaceableEventFilter(e){const t=Array.isArray(e)?e:[e];return 0!==t.length&&t.every(e=>{if(!e.kinds||!Array.isArray(e.kinds)||0===e.kinds.length)return!1;if(!e.authors||!Array.isArray(e.authors)||0===e.authors.length)return!1;return e.kinds.every(e=>0===e||3===e||e>=1e4&&e<=19999)})}function formatFilter(e){return JSON.stringify(e,null,2).split("\n").map((e,t)=>0===t?e:` ${e}`).join("\n")}function fetchingEvents(e,t,n){if("ONLY_CACHE"===t?.cacheUsage)return;const s=Array.isArray(e)?e:[e],r=s.map(formatFilter).join("\n\n ---\n\n ");if(isNip33Pattern(e))s[0],n("fetch-events-usage","For fetching a NIP-33 addressable event, use fetchEvent() with the naddr directly.\n\n📦 Your filter:\n "+r+"\n\n ❌ BAD: const decoded = nip19.decode(naddr);\n const events = await ndk.fetchEvents({\n kinds: [decoded.data.kind],\n authors: [decoded.data.pubkey],\n \"#d\": [decoded.data.identifier]\n });\n const event = Array.from(events)[0];\n\n ✅ GOOD: const event = await ndk.fetchEvent(naddr);\n ✅ GOOD: const event = await ndk.fetchEvent('naddr1...');\n\nfetchEvent() handles naddr decoding automatically and returns the event directly.");else if(isSingleIdLookup(e)){n("fetch-events-usage","For fetching a single event, use fetchEvent() instead.\n\n📦 Your filter:\n "+r+"\n\n💡 Looking for event: "+s[0].ids[0]+"\n\n ❌ BAD: const events = await ndk.fetchEvents({ ids: [eventId] });\n ✅ GOOD: const event = await ndk.fetchEvent(eventId);\n ✅ GOOD: const event = await ndk.fetchEvent('note1...');\n ✅ GOOD: const event = await ndk.fetchEvent('nevent1...');\n\nfetchEvent() is optimized for single event lookups and returns the event directly.")}else{if(isReplaceableEventFilter(e))return;{let e="";const t=s.some(e=>void 0!==e.limit),i=new Set(s.flatMap(e=>e.kinds||[])).size,o=new Set(s.flatMap(e=>e.authors||[])).size;if(t){const t=Math.max(...s.map(e=>e.limit||0));e+=`\n • Limit: ${t} event${1!==t?"s":""}`}i>0&&(e+=`\n • Kinds: ${i} type${1!==i?"s":""}`),o>0&&(e+=`\n • Authors: ${o} author${1!==o?"s":""}`),n("fetch-events-usage","fetchEvents() is a BLOCKING operation that waits for EOSE.\nIn most cases, you should use subscribe() instead.\n\n📦 Your filter"+(s.length>1?"s":"")+":\n "+r+(e?"\n\n📊 Filter analysis:"+e:"")+"\n\n ❌ BAD: const events = await ndk.fetchEvents(filter);\n ✅ GOOD: ndk.subscribe(filter, { onEvent: (e) => ... });\n\nOnly use fetchEvents() when you MUST block until data arrives.","For one-time queries, use fetchEvent() instead of fetchEvents() when expecting a single result.")}}}var GuardrailCheckId={NDK_NO_CACHE:"ndk-no-cache",FILTER_BECH32_IN_ARRAY:"filter-bech32-in-array",FILTER_INVALID_HEX:"filter-invalid-hex",FILTER_ONLY_LIMIT:"filter-only-limit",FILTER_LARGE_LIMIT:"filter-large-limit",FILTER_EMPTY:"filter-empty",FILTER_SINCE_AFTER_UNTIL:"filter-since-after-until",FILTER_INVALID_A_TAG:"filter-invalid-a-tag",FETCH_EVENTS_USAGE:"fetch-events-usage",EVENT_MISSING_KIND:"event-missing-kind",EVENT_PARAM_REPLACEABLE_NO_DTAG:"event-param-replaceable-no-dtag",EVENT_CREATED_AT_MILLISECONDS:"event-created-at-milliseconds",EVENT_NO_NDK_INSTANCE:"event-no-ndk-instance",EVENT_CONTENT_IS_OBJECT:"event-content-is-object",EVENT_MODIFIED_AFTER_SIGNING:"event-modified-after-signing",EVENT_MANUAL_REPLY_MARKERS:"event-manual-reply-markers",TAG_E_FOR_PARAM_REPLACEABLE:"tag-e-for-param-replaceable",TAG_BECH32_VALUE:"tag-bech32-value",TAG_DUPLICATE:"tag-duplicate",TAG_INVALID_P_TAG:"tag-invalid-p-tag",TAG_INVALID_E_TAG:"tag-invalid-e-tag",SUBSCRIBE_NOT_STARTED:"subscribe-not-started",SUBSCRIBE_CLOSE_ON_EOSE_NO_HANDLER:"subscribe-close-on-eose-no-handler",SUBSCRIBE_PASSED_EVENT_NOT_FILTER:"subscribe-passed-event-not-filter",SUBSCRIBE_AWAITED:"subscribe-awaited",RELAY_INVALID_URL:"relay-invalid-url",RELAY_HTTP_INSTEAD_OF_WS:"relay-http-instead-of-ws",RELAY_NO_ERROR_HANDLERS:"relay-no-error-handlers",VALIDATION_PUBKEY_IS_NPUB:"validation-pubkey-is-npub",VALIDATION_PUBKEY_WRONG_LENGTH:"validation-pubkey-wrong-length",VALIDATION_EVENT_ID_IS_BECH32:"validation-event-id-is-bech32",VALIDATION_EVENT_ID_WRONG_LENGTH:"validation-event-id-wrong-length"};function checkCachePresence(e,t){t(GuardrailCheckId.NDK_NO_CACHE)&&setTimeout(()=>{if(!e.cacheAdapter){const e=`\n🤖 AI_GUARDRAILS WARNING: NDK initialized without a cache adapter. Apps perform significantly better with caching.\n\n💡 ${"undefined"!=typeof window?"Consider using @nostr-dev-kit/ndk-cache-dexie or @nostr-dev-kit/ndk-cache-sqlite-wasm":"Consider using @nostr-dev-kit/ndk-cache-redis or @nostr-dev-kit/ndk-cache-sqlite"}\n\n🔇 To disable this check:\n ndk.aiGuardrails.skip('${GuardrailCheckId.NDK_NO_CACHE}')\n or set: ndk.aiGuardrails = { skip: new Set(['${GuardrailCheckId.NDK_NO_CACHE}']) }`;console.warn(e)}},2500)}var AIGuardrails=class{enabled=!1;skipSet=new Set;extensions=new Map;_nextCallDisabled=null;_replyEvents=new WeakSet;constructor(e=!1){this.setMode(e)}register(e,t){this.extensions.has(e)&&console.warn(`AIGuardrails: Extension '${e}' already registered, overwriting`);const n={};for(const[e,s]of Object.entries(t))"function"==typeof s&&(n[e]=(...e)=>{this.enabled&&s(...e,this.shouldCheck.bind(this),this.error.bind(this),this.warn.bind(this))});this.extensions.set(e,n),this[e]=n}setMode(e){"boolean"==typeof e?(this.enabled=e,this.skipSet.clear()):e&&"object"==typeof e&&(this.enabled=!0,this.skipSet=e.skip||new Set)}isEnabled(){return this.enabled}shouldCheck(e){return!!this.enabled&&(!this.skipSet.has(e)&&("all"!==this._nextCallDisabled&&(!this._nextCallDisabled||!this._nextCallDisabled.has(e))))}skip(e){this.skipSet.add(e)}enable(e){this.skipSet.delete(e)}getSkipped(){return Array.from(this.skipSet)}captureAndClearNextCallDisabled(){const e=this._nextCallDisabled;return this._nextCallDisabled=null,e}error(e,t,n,s=!0){if(!this.shouldCheck(e))return;const r=this.formatMessage(e,"ERROR",t,n,s);throw console.error(r),new Error(r)}warn(e,t,n){if(!this.shouldCheck(e))return;const s=this.formatMessage(e,"WARNING",t,n,!0);throw console.error(s),new Error(s)}formatMessage(e,t,n,s,r=!0){let i=`\n🤖 AI_GUARDRAILS ${t}: ${n}`;return s&&(i+=`\n\n💡 ${s}`),r&&(i+=`\n\n🔇 To disable this check:\n ndk.guardrailOff('${e}').yourMethod() // For one call`,i+=`\n ndk.aiGuardrails.skip('${e}') // Permanently`,i+=`\n or set: ndk.aiGuardrails = { skip: new Set(['${e}']) }`),i}ndkInstantiated(e){this.enabled&&checkCachePresence(e,this.shouldCheck.bind(this))}ndk={fetchingEvents:(e,t)=>{this.enabled&&fetchingEvents(e,t,this.warn.bind(this))}};event={signing:e=>{this.enabled&&signing(e,this.error.bind(this),this.warn.bind(this),this._replyEvents)},publishing:e=>{this.enabled},received:(e,t)=>{this.enabled},creatingReply:e=>{this.enabled&&this._replyEvents.add(e)}};subscription={created:(e,t)=>{this.enabled}};relay={connected:e=>{this.enabled}}};function isValidPubkey(e){return"string"==typeof e&&/^[0-9a-f]{64}$/i.test(e)}function processFilters(e,t="validate",n,s){if("ignore"===t)return e;const r=[],i=e.map((e,i)=>{s?.aiGuardrails.isEnabled()&&runAIGuardrailsForFilter(e,i,s);return processFilter(e,t,i,r,n)});if("validate"===t&&r.length>0)throw new Error(`Invalid filter(s) detected:\n${r.join("\n")}`);return i}function processFilter(e,t,n,s,r){const i="validate"===t,o=i?e:{...e};if(e.ids){const t=[];e.ids.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].ids[${o}] is undefined`):r?.(`Fixed: Removed undefined value at ids[${o}]`):"string"!=typeof e?i?s.push(`Filter[${n}].ids[${o}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at ids[${o}] (was ${typeof e})`):/^[0-9a-f]{64}$/i.test(e)?t.push(e):i?s.push(`Filter[${n}].ids[${o}] is not a valid 64-char hex string: "${e}"`):r?.(`Fixed: Removed invalid hex string at ids[${o}]`)}),i||(o.ids=t.length>0?t:void 0)}if(e.authors){const t=[];e.authors.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].authors[${o}] is undefined`):r?.(`Fixed: Removed undefined value at authors[${o}]`):"string"!=typeof e?i?s.push(`Filter[${n}].authors[${o}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at authors[${o}] (was ${typeof e})`):/^[0-9a-f]{64}$/i.test(e)?t.push(e):i?s.push(`Filter[${n}].authors[${o}] is not a valid 64-char hex pubkey: "${e}"`):r?.(`Fixed: Removed invalid hex pubkey at authors[${o}]`)}),i||(o.authors=t.length>0?t:void 0)}if(e.kinds){const t=[];e.kinds.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].kinds[${o}] is undefined`):r?.(`Fixed: Removed undefined value at kinds[${o}]`):"number"!=typeof e?i?s.push(`Filter[${n}].kinds[${o}] is not a number (got ${typeof e})`):r?.(`Fixed: Removed non-number value at kinds[${o}] (was ${typeof e})`):Number.isInteger(e)?e<0||e>65535?i?s.push(`Filter[${n}].kinds[${o}] is out of valid range (0-65535): ${e}`):r?.(`Fixed: Removed out-of-range kind at kinds[${o}]: ${e}`):t.push(e):i?s.push(`Filter[${n}].kinds[${o}] is not an integer: ${e}`):r?.(`Fixed: Removed non-integer value at kinds[${o}]: ${e}`)}),i||(o.kinds=t.length>0?t:void 0)}for(const t in e)if(t.startsWith("#")&&2===t.length){const a=e[t];if(Array.isArray(a)){const e=[];a.forEach((o,a)=>{void 0===o?i?s.push(`Filter[${n}].${t}[${a}] is undefined`):r?.(`Fixed: Removed undefined value at ${t}[${a}]`):"string"!=typeof o?i?s.push(`Filter[${n}].${t}[${a}] is not a string (got ${typeof o})`):r?.(`Fixed: Removed non-string value at ${t}[${a}] (was ${typeof o})`):"#e"!==t&&"#p"!==t||/^[0-9a-f]{64}$/i.test(o)?e.push(o):i?s.push(`Filter[${n}].${t}[${a}] is not a valid 64-char hex string: "${o}"`):r?.(`Fixed: Removed invalid hex string at ${t}[${a}]`)}),i||(o[t]=e.length>0?e:void 0)}}return i||Object.keys(o).forEach(e=>{void 0===o[e]&&delete o[e]}),o}function runAIGuardrailsForFilter(e,t,n){const s=n.aiGuardrails,r=JSON.stringify(e,null,2);if(1===Object.keys(e).length&&void 0!==e.limit&&s.error(GuardrailCheckId.FILTER_ONLY_LIMIT,`Filter[${t}] contains only 'limit' without any filtering criteria.\n\n📦 Your filter:\n${r}\n\n⚠️ This will fetch random events from relays without any criteria.`,"Add filtering criteria:\n ✅ { kinds: [1], limit: 10 }\n ✅ { authors: [pubkey], limit: 10 }\n ❌ { limit: 10 }"),0===Object.keys(e).length&&s.error(GuardrailCheckId.FILTER_EMPTY,`Filter[${t}] is empty.\n\n📦 Your filter:\n${r}\n\n⚠️ This will request ALL events from relays, which is never what you want.`,"Add filtering criteria like 'kinds', 'authors', or tags.",!1),void 0!==e.since&&void 0!==e.until&&e.since>e.until){const n=new Date(1e3*e.since).toISOString(),i=new Date(1e3*e.until).toISOString();s.error(GuardrailCheckId.FILTER_SINCE_AFTER_UNTIL,`Filter[${t}] has 'since' AFTER 'until'.\n\n📦 Your filter:\n${r}\n\n❌ since: ${e.since} (${n})\n❌ until: ${e.until} (${i})\n\nNo events can match this time range!`,"'since' must be BEFORE 'until'. Both are Unix timestamps in seconds.",!1)}const i=/^n(addr|event|ote|pub|profile)1/,o=/^[0-9a-f]{64}$/i;e.ids&&e.ids.forEach((e,n)=>{"string"==typeof e&&(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].ids[${n}] contains bech32: "${e}". IDs must be hex, not bech32.`,'Use filterFromId() to decode bech32 first: import { filterFromId } from "@nostr-dev-kit/ndk"',!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].ids[${n}] is not a valid 64-char hex string: "${e}"`,"Event IDs must be 64-character hexadecimal strings. Invalid IDs often come from corrupted data in user-generated lists. Always validate hex strings before using them in filters:\n\n const validIds = ids.filter(id => /^[0-9a-f]{64}$/i.test(id));",!1))}),e.authors&&e.authors.forEach((e,n)=>{"string"==typeof e&&(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].authors[${n}] contains bech32: "${e}". Authors must be hex pubkeys, not npub.`,"Use ndkUser.pubkey instead. Example: { authors: [ndkUser.pubkey] }",!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].authors[${n}] is not a valid 64-char hex pubkey: "${e}"`,'Kind:3 follow lists can contain invalid entries like labels ("Follow List"), partial strings ("highlig"), or other corrupted data. You MUST validate all pubkeys before using them in filters.\n\n Example:\n const validPubkeys = pubkeys.filter(p => /^[0-9a-f]{64}$/i.test(p));\n ndk.subscribe({ authors: validPubkeys, kinds: [1] });',!1))});for(const n in e)if(n.startsWith("#")&&2===n.length){const r=e[n];Array.isArray(r)&&r.forEach((e,r)=>{"string"==typeof e&&("#e"!==n&&"#p"!==n||(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].${n}[${r}] contains bech32: "${e}". Tag values must be decoded.`,"Use filterFromId() or nip19.decode() to get the hex value first.",!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].${n}[${r}] is not a valid 64-char hex string: "${e}"`,("#e"===n?"Event IDs":"Public keys")+" in tag filters must be 64-character hexadecimal strings. Kind:3 follow lists and other user-generated content can contain invalid data. Always filter before using:\n\n const validValues = values.filter(v => /^[0-9a-f]{64}$/i.test(v));",!1)))})}if(e["#a"]){const n=e["#a"];n?.forEach((e,n)=>{if("string"==typeof e)if(/^\d+:[0-9a-f]{64}:.*$/.test(e)){const r=Number.parseInt(e.split(":")[0],10);(r<3e4||r>39999)&&s.error(GuardrailCheckId.FILTER_INVALID_A_TAG,`Filter[${t}].#a[${n}] uses non-addressable kind ${r}: "${e}". #a filters are only for addressable events (kinds 30000-39999).`,`Addressable events include:\n • 30000-30039: Parameterized Replaceable Events (profiles, settings, etc.)\n • 30040-39999: Other addressable events\n\nFor regular events (kind ${r}), use:\n • #e filter for specific event IDs\n • kinds + authors filters for event queries`,!1)}else s.error(GuardrailCheckId.FILTER_INVALID_A_TAG,`Filter[${t}].#a[${n}] has invalid format: "${e}". Must be "kind:pubkey:d-tag".`,'Example: "30023:fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52:my-article"',!1)})}}function mergeTags(e,t){const n=new Map,s=(e,t)=>e.every((e,n)=>e===t[n]);return e.concat(t).forEach(e=>{for(const[t,r]of n)if(s(r,e)||s(e,r))return void(e.length>=r.length&&n.set(t,e));n.set((e=>e.join(","))(e),e)}),Array.from(n.values())}var hashtagRegex=/(?<=\s|^)(#[^\s!@#$%^&*()=+./,[{\]};:'"?><]+)/g;function generateHashtags(e){const t=e.match(hashtagRegex),n=new Set,s=new Set;if(t)for(const e of t)n.has(e.slice(1))||(s.add(e.slice(1)),n.add(e.slice(1)));return Array.from(s)}async function generateContentTags(e,t=[],n,s){if(n?.skipContentTagging)return{content:e,tags:t};const r=[],i=e=>{t.find(t=>["q",e[0]].includes(t[0])&&t[1]===e[1])||t.push(e)};if(e=e.replace(/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,e=>{try{const t=e.split(/(@|nostr:)/)[2],{type:s,data:o}=nip19_exports$1.decode(t);let a;if(n?.filters){const t=!n.filters.includeTypes||n.filters.includeTypes.includes(s),r=n.filters.excludeTypes?.includes(s);if(!t||r)return e}switch(s){case"npub":!1!==n?.pTags&&(a=["p",o]);break;case"nprofile":!1!==n?.pTags&&(a=["p",o.pubkey]);break;case"note":r.push(new Promise(async e=>{const n=await maybeGetEventRelayUrl(t);i(["q",o,n]),e()}));break;case"nevent":r.push(new Promise(async e=>{const{id:s,author:r}=o;let{relays:a}=o;a&&0!==a.length||(a=[await maybeGetEventRelayUrl(t)]),i(["q",s,a[0]]),r&&!1!==n?.pTags&&!1!==n?.pTagOnQTags&&i(["p",r]),e()}));break;case"naddr":r.push(new Promise(async e=>{const s=[o.kind,o.pubkey,o.identifier].join(":");let r=o.relays??[];0===r.length&&(r=[await maybeGetEventRelayUrl(t)]),i(["q",s,r[0]]),!1!==n?.pTags&&!1!==n?.pTagOnQTags&&!1!==n?.pTagOnATags&&i(["p",o.pubkey]),e()}));break;default:return e}return a&&i(a),`nostr:${t}`}catch(t){return e}}),await Promise.all(r),!n?.filters?.excludeTypes?.includes("hashtag")){const n=generateHashtags(e).map(e=>["t",e]);t=mergeTags(t,n)}if(!1!==n?.pTags&&n?.copyPTagsFromTarget&&s){const e=s.getMatchingTags("p");for(const n of e)n[1]&&isValidPubkey(n[1])&&(t.find(e=>"p"===e[0]&&e[1]===n[1])||t.push(n))}return{content:e,tags:t}}async function maybeGetEventRelayUrl(e){return""}async function encrypt(e,t,n="nip44"){let s;if(!this.ndk)throw new Error("No NDK instance found!");let r=t;if(r||(this.ndk.assertSigner(),r=this.ndk.signer),!r)throw new Error("no NDK signer");const i=e||(()=>{const e=this.getMatchingTags("p");if(1!==e.length)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:e[0][1]})})();if("nip44"===n&&await isEncryptionEnabled(r,"nip44")&&(s=await r.encrypt(i,this.content,"nip44")),s&&"nip04"!==n||!await isEncryptionEnabled(r,"nip04")||(s=await r.encrypt(i,this.content,"nip04")),!s)throw new Error("Failed to encrypt event.");this.content=s}async function decrypt(e,t,n){if(this.ndk?.cacheAdapter?.getDecryptedEvent){const e=await this.ndk.cacheAdapter.getDecryptedEvent(this.id);if(e)return void(this.content=e.content)}let s;if(!this.ndk)throw new Error("No NDK instance found!");let r=t;if(r||(this.ndk.assertSigner(),r=this.ndk.signer),!r)throw new Error("no NDK signer");const i=e||this.author;if(!i)throw new Error("No sender provided and no author available");const o=n||(this.content.match(/\\?iv=/)?"nip04":"nip44");if(("nip04"===o||4===this.kind)&&await isEncryptionEnabled(r,"nip04")&&this.content.search("\\?iv=")&&(s=await r.decrypt(i,this.content,"nip04")),!s&&"nip44"===o&&await isEncryptionEnabled(r,"nip44")&&(s=await r.decrypt(i,this.content,"nip44")),!s)throw new Error("Failed to decrypt event.");this.content=s,this.ndk?.cacheAdapter?.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function isEncryptionEnabled(e,t){return!!e.encryptionEnabled&&(!t||Boolean(await e.encryptionEnabled(t)))}function eventHasETagMarkers(e){for(const t of e.tags)if("e"===t[0]&&(t[3]??"").length>0)return!0;return!1}function getRootTag(e,t){t??=e.tagType();const n=e.tags.find(isTagRootTag);if(!n){if(eventHasETagMarkers(e))return;const n=e.getMatchingTags(t);if(n.length<3)return n[0]}return n}var nip22RootTags=new Set(["A","E","I"]),nip22ReplyTags=new Set(["a","e","i"]);function getReplyTag(e,t){if(1111===e.kind){let t;for(const n of e.tags)if(nip22RootTags.has(n[0]))t=n;else if(nip22ReplyTags.has(n[0])){t=n;break}return t}t??=e.tagType();let n,s=!1;for(const r of e.tags)if(r[0]===t){if((r[3]??"").length>0&&(s=!0),s&&"reply"===r[3])return r;s&&"root"===r[3]&&(n=r),s||(n=r)}return n}function isTagRootTag(e){return"E"===e[0]||"root"===e[3]}async function fetchTaggedEvent(e,t){if(!this.ndk)throw new Error("NDK instance not found");const n=this.getMatchingTags(e,t);if(0===n.length)return;const[s,r,i]=n[0],o=""!==i?this.ndk.pool.getRelay(i):void 0;return await this.ndk.fetchEvent(r,{},o)}async function fetchRootEvent(e){if(!this.ndk)throw new Error("NDK instance not found");const t=getRootTag(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}async function fetchReplyEvent(e){if(!this.ndk)throw new Error("NDK instance not found");const t=getReplyTag(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}function isReplaceable(){if(void 0===this.kind)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(void 0===this.kind)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}var DEFAULT_RELAY_COUNT=2,worker;function encode(e=DEFAULT_RELAY_COUNT){let t=[];return this.onRelays.length>0?t=this.onRelays.map(e=>e.url):this.relay&&(t=[this.relay.url]),t.length>e&&(t=t.slice(0,e)),this.isParamReplaceable()?nip19_exports$1.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:t}):t.length>0?nip19_exports$1.neventEncode({id:this.tagId(),relays:t,author:this.pubkey}):nip19_exports$1.noteEncode(this.tagId())}async function repost(e=!0,t){if(!t&&e){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t=this.ndk.signer}const n=new NDKEvent(this.ndk,{kind:getKind(this)});return this.isProtected||(n.content=JSON.stringify(this.rawEvent())),n.tag(this),1!==this.kind&&n.tags.push(["k",`${this.kind}`]),t&&await n.sign(t),e&&await n.publish(),n}function getKind(e){return 1===e.kind?6:16}function serialize(e=!1,t=!1){const n=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return e&&n.push(this.sig),t&&n.push(this.id),JSON.stringify(n)}function deserialize(e){const t=JSON.parse(e),n={pubkey:t[1],created_at:t[2],kind:t[3],tags:t[4],content:t[5]};if(t.length>=7){const e=t[6],s=t[7];e&&128===e.length?(n.sig=e,s&&64===s.length&&(n.id=s)):e&&64===e.length&&(n.id=e,s&&128===s.length&&(n.sig=s))}return n}var processingQueue={};function signatureVerificationInit(e){(worker=e).onmessage=e=>{const[t,n]=e.data,s=processingQueue[t];if(s){delete processingQueue[t];for(const e of s.resolves)e(n)}else console.error("No record found for event",t)}}async function verifySignatureAsync(e,t,n){const s=e.ndk,r=Date.now();let i;return i=s.signatureVerificationFunction?await s.signatureVerificationFunction(e):await new Promise(t=>{const s=e.serialize();let r=!1;processingQueue[e.id]||(processingQueue[e.id]={event:e,resolves:[],relay:n},r=!0),processingQueue[e.id].resolves.push(t),r&&worker?.postMessage({serialized:s,id:e.id,sig:e.sig,pubkey:e.pubkey})}),s.signatureVerificationTimeMs+=Date.now()-r,i}var PUBKEY_REGEX=/^[a-f0-9]{64}$/;function validate(){if("number"!=typeof this.kind)return!1;if("string"!=typeof this.content)return!1;if("number"!=typeof this.created_at)return!1;if("string"!=typeof this.pubkey)return!1;if(!this.pubkey.match(PUBKEY_REGEX))return!1;if(!Array.isArray(this.tags))return!1;for(let e=0;e<this.tags.length;e++){const t=this.tags[e];if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if("object"==typeof t[e])return!1}return!0}var verifiedSignatures=new dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function verifySignature(e){if("boolean"==typeof this.signatureVerified)return this.signatureVerified;const t=verifiedSignatures.get(this.id);if(null!==t)return this.signatureVerified=!!t,this.signatureVerified;try{if(!this.ndk?.asyncSigVerification){const e=sha256((new TextEncoder).encode(this.serialize())),t=schnorr.verify(this.sig,e,this.pubkey);return t?verifiedSignatures.set(this.id,this.sig):verifiedSignatures.set(this.id,!1),this.signatureVerified=t,t}{const t=this.relay;verifySignatureAsync(this,e,t).then(n=>{e&&(this.signatureVerified=n,n&&verifiedSignatures.set(this.id,this.sig)),n?t&&t.addValidatedEvent():(t?this.ndk?.reportInvalidSignature(this,t):this.ndk?.reportInvalidSignature(this),verifiedSignatures.set(this.id,!1))}).catch(e=>{console.error("signature verification error",this.id,e)})}}catch(e){return this.signatureVerified=!1,!1}}function getEventHash(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(e){return bytesToHex(sha256((new TextEncoder).encode(e)))}var skipClientTagOnKinds=new Set([0,4,1059,13,3,9734,5]),NDKEvent=class e extends lib$1.EventEmitter{ndk;created_at;content="";tags=[];kind;id="";sig;pubkey="";signatureVerified;_author=void 0;relay;get onRelays(){let e=[];return this.ndk?e=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&e.push(this.relay),e}publishStatus="success";publishError;constructor(t,n){super(),this.ndk=t,this.created_at=n?.created_at,this.content=n?.content||"",this.tags=n?.tags||[],this.id=n?.id||"",this.sig=n?.sig,this.pubkey=n?.pubkey||"",this.kind=n?.kind,n instanceof e&&(this.relay&&(this.relay=n.relay,this.ndk?.subManager.seenEvent(n.id,this.relay)),this.publishStatus=n.publishStatus,this.publishError=n.publishError)}static deserialize(t,n){return new e(t,deserialize(n))}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(e){this.pubkey=e.pubkey,this._author=e,this._author.ndk??=this.ndk}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const e=this.ndk.getUser({pubkey:this.pubkey});return this._author=e,e}tagExternal(e,t,n){const s=["i"],r=["k"];switch(t){case"url":{const t=new URL(e);t.hash="",s.push(t.toString()),r.push(`${t.protocol}//${t.host}`);break}case"hashtag":s.push(`#${e.toLowerCase()}`),r.push("#");break;case"geohash":s.push(`geo:${e.toLowerCase()}`),r.push("geo");break;case"isbn":s.push(`isbn:${e.replace(/-/g,"")}`),r.push("isbn");break;case"podcast:guid":s.push(`podcast:guid:${e}`),r.push("podcast:guid");break;case"podcast:item:guid":s.push(`podcast:item:guid:${e}`),r.push("podcast:item:guid");break;case"podcast:publisher:guid":s.push(`podcast:publisher:guid:${e}`),r.push("podcast:publisher:guid");break;case"isan":s.push(`isan:${e.split("-").slice(0,4).join("-")}`),r.push("isan");break;case"doi":s.push(`doi:${e.toLowerCase()}`),r.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${t}`)}n&&s.push(n),this.tags.push(s),this.tags.push(r)}tag(t,n,s,r,i){let o=[];if(void 0!==t.fetchProfile){if(r??="p","p"===r&&!1===i?.pTags)return;const e=[r,t.pubkey];n&&e.push("",n),o.push(e)}else if(t instanceof e){const e=t;if(s??=e?.pubkey===this.pubkey,o=e.referenceTags(n,s,r,i),!1!==i?.pTags)for(const t of e.getMatchingTags("p"))t[1]&&isValidPubkey(t[1])&&t[1]!==this.pubkey&&(this.tags.find(e=>"p"===e[0]&&e[1]===t[1])||this.tags.push(["p",t[1]]))}else{if(!Array.isArray(t))throw new Error("Invalid argument",t);o=[t]}this.tags=mergeTags(this.tags,o)}async toNostrEvent(e,t){if(!e&&""===this.pubkey){const e=await(this.ndk?.signer?.user());this.pubkey=e?.pubkey||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:n,tags:s}=await this.generateTags(t);this.content=n||"",this.tags=s;try{this.id=this.getEventHash()}catch(e){}return this.rawEvent()}serialize=serialize.bind(this);getEventHash=getEventHash.bind(this);validate=validate.bind(this);verifySignature=verifySignature.bind(this);isReplaceable=isReplaceable.bind(this);isEphemeral=isEphemeral.bind(this);isDvm=()=>this.kind&&this.kind>=5e3&&this.kind<=7e3;isParamReplaceable=isParamReplaceable.bind(this);encode=encode.bind(this);encrypt=encrypt.bind(this);decrypt=decrypt.bind(this);getMatchingTags(e,t){const n=this.tags.filter(t=>t[0]===e);return void 0===t?n:n.filter(e=>e[3]===t)}hasTag(e,t){return this.tags.some(n=>n[0]===e&&(!t||n[3]===t))}tagValue(e,t){const n=this.getMatchingTags(e,t);if(0!==n.length)return n[0][1]}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}get dTag(){return this.tagValue("d")}set dTag(e){this.removeTag("d"),e&&this.tags.push(["d",e])}removeTag(e,t){const n=Array.isArray(e)?e:[e];this.tags=this.tags.filter(e=>{const s=n.includes(e[0]),r=!t||e[3]===t;return!(s&&r)})}replaceTag(e){this.removeTag(e[0]),this.tags.push(e)}async sign(e,t){this.ndk?.aiGuardrails?.event?.signing(this),e?this.author=await e.user():(this.ndk?.assertSigner(),e=this.ndk?.signer);const n=await this.toNostrEvent(void 0,t);return this.sig=await e.sign(n),this.sig}async publishReplaceable(e,t,n){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(e,t,n)}async publish(e,t,n,s){if(n||(n=1),this.sig||await this.sign(void 0,s),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if(e&&0!==e.size||(e=this.ndk.devWriteRelaySet||await calculateRelaySetFromEvent(this.ndk,this,n)),5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds){const e=this.getMatchingTags("e").map(e=>e[1]);this.ndk.cacheAdapter.deleteEventIds(e)}const r=this.rawEvent();if(this.ndk.cacheAdapter?.addUnpublishedEvent&&shouldTrackUnpublishedEvent(this))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,e.relayUrls)}catch(e){console.error("Error adding unpublished event to cache",e)}5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(e=>e[1])),this.ndk.subManager.dispatchEvent(r,void 0,!0);const i=await e.publish(this,t,n);return i.forEach(e=>this.ndk?.subManager.seenEvent(this.id,e)),i}async generateTags(e){let t=[];const n=await generateContentTags(this.content,this.tags,e,this),s=n.content;if(t=n.tags,this.kind&&this.isParamReplaceable()){if(!this.getMatchingTags("d")[0]){const e=this.tagValue("title");let n=[...Array(e?6:16)].map(()=>Math.random().toString(36)[2]).join("");e&&e.length>0&&(n=`${e.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${n}`),t.push(["d",n])}}if(this.shouldAddClientTag){const e=["client",this.ndk?.clientName??""];this.ndk?.clientNip89&&e.push(this.ndk?.clientNip89),t.push(e)}else this.shouldStripClientTag&&(t=t.filter(e=>"client"!==e[0]));return{content:s||"",tags:t}}get shouldAddClientTag(){return!(!this.ndk?.clientName&&!this.ndk?.clientNip89)&&(!skipClientTagOnKinds.has(this.kind)&&(!this.isEphemeral()&&(!(this.isReplaceable()&&!this.isParamReplaceable())&&(!this.isDvm()&&!this.hasTag("client")))))}get shouldStripClientTag(){return skipClientTagOnKinds.has(this.kind)}muted(){return this.ndk?.muteFilter&&this.ndk.muteFilter(this)?"muted":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const e=this.getMatchingTags("d")[0];return e?e[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return 0===this.kind||3===this.kind||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 e=this.dTag??"";return`${this.kind}:${this.pubkey}:${e}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(e){let t;return t=this.isParamReplaceable()?["a",this.tagAddress()]:["e",this.tagId()],this.relay?t.push(this.relay.url):t.push(""),t.push(e??""),this.isParamReplaceable()||t.push(this.pubkey),t}referenceTags(e,t,n,s){let r=[];return r=this.isParamReplaceable()?[[n??"a",this.tagAddress()],[n??"e",this.id]]:[[n??"e",this.id]],r=r.map(t=>("e"===t[0]||e?t.push(this.relay?.url??""):this.relay?.url&&t.push(this.relay?.url),t)),r.forEach(t=>{"e"===t[0]?(t.push(e??""),t.push(this.pubkey)):e&&t.push(e)}),r=[...r,...this.getMatchingTags("h")],t||!1===s?.pTags||r.push(...this.author.referenceTags()),r}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new e(this.ndk,{kind:5,content:t||""});return s.tag(this,void 0,!0),s.tags.push(["k",this.kind?.toString()]),n&&(this.emit("deleted"),await s.publish()),s}set isProtected(e){this.removeTag("-"),e&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}fetchTaggedEvent=fetchTaggedEvent.bind(this);fetchRootEvent=fetchRootEvent.bind(this);fetchReplyEvent=fetchReplyEvent.bind(this);repost=repost.bind(this);async react(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new e(this.ndk,{kind:7,content:t});return s.tag(this),1!==this.kind&&s.tags.push(["k",`${this.kind}`]),n&&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(e=>e.url).join(", "))}reply(t,n){const s=new e(this.ndk);if(this.ndk?.aiGuardrails?.event?.creatingReply(s),1!==this.kind||t){s.kind=1111;const e=["A","E","I","P"],t=this.tags.filter(t=>e.includes(t[0]));if(t.length>0){const e=this.tagValue("K");let n;if(s.tags.push(...t),e&&s.tags.push(["K",e]),this.isParamReplaceable()){n=["a",this.tagAddress()];const e=this.relay?.url??"";e&&n.push(e)}else{n=["e",this.tagId()];const e=this.relay?.url??"";n.push(e),n.push(this.pubkey)}s.tags.push(n)}else{let e,t;const r=this.relay?.url??"";this.isParamReplaceable()?(e=["a",this.tagAddress(),r],t=["A",this.tagAddress(),r]):(e=["e",this.tagId(),r,this.pubkey],t=["E",this.tagId(),r,this.pubkey]),s.tags.push(e),s.tags.push(t),s.tags.push(["K",this.kind?.toString()]),!1!==n?.pTags&&!1!==n?.pTagOnATags&&s.tags.push(["P",this.pubkey])}s.tags.push(["k",this.kind?.toString()]),!1!==n?.pTags&&(s.tags.push(...this.getMatchingTags("p")),s.tags.push(["p",this.pubkey]))}else{s.kind=1;this.hasTag("e")?s.tags=[...s.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply",!1,void 0,n)]:s.tag(this,"root",!1,void 0,n)}return s}},untrackedUnpublishedEvents=new Set([24133,13194,23194,23195]);function shouldTrackUnpublishedEvent(e){return!untrackedUnpublishedEvents.has(e.kind)}var NDKPool=class extends lib$1.EventEmitter{_relays=new Map;status="idle";autoConnectRelays=new Set;debug;temporaryRelayTimers=new Map;flappingRelays=new Set;backoffTimes=new Map;ndk;disconnectionTimes=new Map;systemEventDetector;constructor(e,t,{debug:n,name:s}={}){super(),this.debug=n??t.debug.extend("pool"),s&&(this._name=s),this.ndk=t,this.relayUrls=e,this.ndk.pools&&this.ndk.pools.push(this)}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const e=new NDKRelay(t,void 0,this.ndk);e.connectivity.netDebug=this.ndk.netDebug,this.addRelay(e)}}_name="unnamed";get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,n){const s=this.relays.has(e.url);s||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,n));const r=this.temporaryRelayTimers.get(e.url);if(r&&clearTimeout(r),!s||r){const n=setTimeout(()=>{this.ndk.explicitRelayUrls?.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,n)}}addRelay(e,t=!0){const n=this.relays.has(e.url),s=e.url.includes("/npub1");let r=!0;const i=e.url;if(n)return;if(this.ndk.relayConnectionFilter&&!this.ndk.relayConnectionFilter(i))return void this.debug(`Refusing to add relay ${i}: blocked by relayConnectionFilter`);if(s)return void this.debug(`Refusing to add relay ${i}: is a filter relay`);if(this.ndk.cacheAdapter?.getRelayStatus){const n=this.ndk.cacheAdapter.getRelayStatus(i),s=n instanceof Promise?void 0:n;if(s?.dontConnectBefore){if(s.dontConnectBefore>Date.now()){const n=s.dontConnectBefore-Date.now();return this.debug(`Refusing to add relay ${i}: delayed connect for ${n}ms`),void setTimeout(()=>{this.addRelay(e,t)},n)}r=!1}}const o=t=>this.emit("notice",e,t),a=()=>this.handleRelayConnect(i),c=()=>this.handleRelayReady(e),l=()=>{this.recordDisconnection(e),this.emit("relay:disconnect",e)},u=()=>this.handleFlapping(e),d=t=>this.emit("relay:auth",e,t),h=()=>this.emit("relay:authed",e);e.off("notice",o),e.off("connect",a),e.off("ready",c),e.off("disconnect",l),e.off("flapping",u),e.off("auth",d),e.off("authed",h),e.on("notice",o),e.on("connect",a),e.on("ready",c),e.on("disconnect",l),e.on("flapping",u),e.on("auth",d),e.on("authed",h),e.on("delayed-connect",t=>{this.ndk.cacheAdapter?.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+t})}),this._relays.set(i,e),t&&this.autoConnectRelays.add(i),t&&"active"===this.status&&(this.emit("relay:connecting",e),e.connect(void 0,r).catch(e=>{this.debug(`Failed to connect to relay ${i}`,e)}))}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 n=this.temporaryRelayTimers.get(e);return n&&(clearTimeout(n),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=normalizeRelayUrl(e),n=this.relays.get(t);return!!n&&5===n.status}getRelay(e,t=!0,n=!1,s){let r=this.relays.get(normalizeRelayUrl(e));return r||(r=new NDKRelay(e,void 0,this.ndk),r.connectivity.netDebug=this.ndk.netDebug,n?this.useTemporaryRelay(r,3e4,s):this.addRelay(r,t)),r}handleRelayConnect(e){const t=this.relays.get(e);t?(this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")):console.error("NDK BUG: relay not found in pool",{relayUrl:e})}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(e=>this.relays.get(e)).filter(e=>!!e);for(const e of t)5!==e.status&&4!==e.status&&(this.emit("relay:connecting",e),e.connect().catch(t=>{this.debug(`Failed to connect to relay ${e.url}: ${t??"No reason specified"}`)}));const n=()=>t.every(e=>5===e.status),s=new Promise(e=>{if(n())return void e();const s=[];for(const r of t){const i=()=>{if(n()){for(let e=0;e<t.length;e++)t[e].off("connect",s[e]);e()}};s.push(i),r.on("connect",i)}}),r=new Promise("number"==typeof e?t=>setTimeout(t,e):()=>{});await Promise.race([s,r])}checkOnFlappingRelays(){if(this.flappingRelays.size/this.relays.size>=.8)for(const e of this.flappingRelays)this.backoffTimes.set(e,0)}recordDisconnection(e){const t=Date.now();this.disconnectionTimes.set(e.url,t);for(const[e,n]of this.disconnectionTimes.entries())t-n>1e4&&this.disconnectionTimes.delete(e);this.checkForSystemWideDisconnection()}checkForSystemWideDisconnection(){const e=Date.now(),t=[];for(const n of this.disconnectionTimes.values())e-n<5e3&&t.push(n);t.length>this.relays.size/2&&this.relays.size>1&&(this.debug(`System-wide disconnection detected: ${t.length}/${this.relays.size} relays disconnected`),this.handleSystemWideReconnection())}handleSystemWideReconnection(){if(this.systemEventDetector)this.debug("System-wide reconnection already in progress, skipping");else{this.debug("Initiating system-wide reconnection with reset backoff"),this.systemEventDetector=setTimeout(()=>{this.systemEventDetector=void 0},1e4);for(const e of this.relays.values())e.connectivity&&(e.connectivity.resetReconnectionState(),5!==e.status&&4!==e.status&&e.connect().catch(t=>{this.debug(`Failed to reconnect relay ${e.url} after system event: ${t}`)}));this.disconnectionTimes.clear()}}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;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++,5===t.status?e.connected++:1===t.status?e.disconnected++:4===t.status&&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())}},NDKDVMJobFeedback=class e extends NDKEvent{static kinds=[7e3];constructor(e,t){super(e,t),this.kind??=7e3}static async from(t){const n=new e(t.ndk,t.rawEvent());return n.encrypted&&await n.dvmDecrypt(),n}get status(){return this.tagValue("status")}set status(e){this.removeTag("status"),void 0!==e&&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)}},NDKCashuMintList=class e extends NDKEvent{static kind=10019;static kinds=[10019];_p2pk;constructor(e,t){super(e,t),this.kind??=10019}static from(t){return new e(t.ndk,t)}set relays(e){this.tags=this.tags.filter(e=>"relay"!==e[0]);for(const t of e)this.tags.push(["relay",t])}get relays(){const e=[];for(const t of this.tags)"relay"===t[0]&&e.push(t[1]);return e}set mints(e){this.tags=this.tags.filter(e=>"mint"!==e[0]);for(const t of e)this.tags.push(["mint",t])}get mints(){const e=[];for(const t of this.tags)"mint"===t[0]&&e.push(t[1]);return Array.from(new Set(e))}get p2pk(){return this._p2pk||(this._p2pk=this.tagValue("pubkey")??this.pubkey),this._p2pk}set p2pk(e){this._p2pk=e,this.removeTag("pubkey"),e&&this.tags.push(["pubkey",e])}get relaySet(){return NDKRelaySet.fromRelayUrls(this.relays,this.ndk)}},NDKArticle=class e extends NDKEvent{static kind=30023;static kinds=[30023];constructor(e,t){super(e,t),this.kind??=30023}static from(t){return new e(t.ndk,t)}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"),void 0!==e&&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")}},NDKBlossomList=class e extends NDKEvent{static kinds=[10063];constructor(e,t){super(e,t),this.kind??=10063}static from(t){return new e(t.ndk,t.rawEvent())}get servers(){return this.tags.filter(e=>"server"===e[0]).map(e=>e[1])}set servers(e){this.tags=this.tags.filter(e=>"server"!==e[0]);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 t=this.servers.filter(t=>t!==e);this.servers=[e,...t]}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(t=>t!==e)}},NDKFedimintMint=class e extends NDKEvent{static kind=38173;static kinds=[38173];constructor(e,t){super(e,t),this.kind??=38173}static async from(t){return new e(t.ndk,t)}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get inviteCodes(){return this.getMatchingTags("u").map(e=>e[1])}set inviteCodes(e){this.removeTag("u");for(const t of e)this.tags.push(["u",t])}get modules(){return this.getMatchingTags("modules").map(e=>e[1])}set modules(e){this.removeTag("modules");for(const t of e)this.tags.push(["modules",t])}get network(){return this.tagValue("n")}set network(e){this.removeTag("n"),e&&this.tags.push(["n",e])}get metadata(){if(this.content)try{return JSON.parse(this.content)}catch{return}}set metadata(e){this.content=e?JSON.stringify(e):""}},NDKCashuMintAnnouncement=class e extends NDKEvent{static kind=38172;static kinds=[38172];constructor(e,t){super(e,t),this.kind??=38172}static async from(t){return new e(t.ndk,t)}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get url(){return this.tagValue("u")}set url(e){this.removeTag("u"),e&&this.tags.push(["u",e])}get nuts(){return this.getMatchingTags("nuts").map(e=>e[1])}set nuts(e){this.removeTag("nuts");for(const t of e)this.tags.push(["nuts",t])}get network(){return this.tagValue("n")}set network(e){this.removeTag("n"),e&&this.tags.push(["n",e])}get metadata(){if(this.content)try{return JSON.parse(this.content)}catch{return}}set metadata(e){this.content=e?JSON.stringify(e):""}},NDKMintRecommendation=class e extends NDKEvent{static kind=38e3;static kinds=[38e3];constructor(e,t){super(e,t),this.kind??=38e3}static async from(t){return new e(t.ndk,t)}get recommendedKind(){const e=this.tagValue("k");return e?Number(e):void 0}set recommendedKind(e){this.removeTag("k"),e&&this.tags.push(["k",e.toString()])}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get urls(){return this.getMatchingTags("u").map(e=>e[1])}set urls(e){this.removeTag("u");for(const t of e)this.tags.push(["u",t])}get mintEventPointers(){return this.getMatchingTags("a").map(e=>({kind:Number(e[1].split(":")[0]),identifier:e[1].split(":")[2],relay:e[2]}))}addMintEventPointer(e,t,n,s){const r=["a",`${e}:${t}:${n}`];s&&r.push(s),this.tags.push(r)}get review(){return this.content}set review(e){this.content=e}},NDKClassified=class e extends NDKEvent{static kinds=[30402];constructor(e,t){super(e,t),this.kind??=30402}static from(t){return new e(t.ndk,t)}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"),void 0!==e&&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(e=>"price"===e[0]);if(e)return{amount:Number.parseFloat(e[1]),currency:e[2],frequency:e[3]}}set price(e){if("string"==typeof e&&(e={amount:Number.parseFloat(e)}),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()}},NDKDraft=class e extends NDKEvent{_event;static kind=31234;static kinds=[31234,1234];counterparty;constructor(e,t){super(e,t),this.kind??=31234}static from(t){return new e(t.ndk,t)}set identifier(e){this.removeTag("d"),this.tags.push(["d",e])}get identifier(){return this.dTag}set event(e){this._event=e instanceof NDKEvent?e:new NDKEvent(void 0,e),this.prepareEvent()}set checkpoint(e){e?(this.tags.push(e.tagReference()),this.kind=1234):(this.removeTag("a"),this.kind=31234)}get isCheckpoint(){return 1234===this.kind}get isProposal(){const e=this.tagValue("p");return!!e&&e!==this.pubkey}async getEvent(e){if(this._event)return this._event;if(e??=this.ndk?.signer,!e)throw new Error("No signer available");if(!(this.content&&this.content.length>0))return null;try{const t=e.pubkey,n=[this.tagValue("p"),this.pubkey].filter(Boolean).find(e=>e!==t);let s;s=new NDKUser({pubkey:n??t}),await this.decrypt(s,e);const r=JSON.parse(this.content);return this._event=await wrapEvent(new NDKEvent(this.ndk,r)),this._event}catch(e){return void console.error(e)}}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:e,publish:t,relaySet:n}){if(e??=this.ndk?.signer,!e)throw new Error("No signer available");const s=this.counterparty||await e.user();if(await this.encrypt(s,e),this.counterparty){const e=this.counterparty.pubkey;this.removeTag("p"),this.tags.push(["p",e])}if(!1!==t)return this.publishReplaceable(n)}};function mapImetaTag(e){const t={};if(2===e.length){const n=e[1].split(" ");for(let e=0;e<n.length;e+=2){const s=n[e],r=n[e+1];"fallback"===s?(t.fallback||(t.fallback=[]),t.fallback.push(r)):t[s]=r}return t}const n=e.slice(1);for(const e of n){const n=e.split(" "),s=n[0],r=n.slice(1).join(" ");"fallback"===s?(t.fallback||(t.fallback=[]),t.fallback.push(r)):t[s]=r}return t}function imetaTagToTag(e){const t=["imeta"];for(const[n,s]of Object.entries(e))if(Array.isArray(s))for(const e of s)t.push(`${n} ${e}`);else s&&t.push(`${n} ${s}`);return t}var NDKFollowPack=class e extends NDKEvent{static kind=39089;static kinds=[39089,39092];constructor(e,t){super(e,t),this.kind??=39089}static from(t){return new e(t.ndk,t)}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(e=>"imeta"===e[0]);if(e){const t=mapImetaTag(e);if(t.url)return t.url}return this.tagValue("image")}set image(e){this.tags=this.tags.filter(e=>"imeta"!==e[0]&&"image"!==e[0]),"string"==typeof e?void 0!==e&&this.tags.push(["image",e]):e&&"object"==typeof e&&(this.tags.push(imetaTagToTag(e)),e.url&&this.tags.push(["image",e.url]))}get pubkeys(){return Array.from(new Set(this.tags.filter(e=>"p"===e[0]&&e[1]&&isValidPubkey(e[1])).map(e=>e[1])))}set pubkeys(e){this.tags=this.tags.filter(e=>"p"!==e[0]);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])}},NDKHighlight=class e extends NDKEvent{_article;static kind=9802;static kinds=[9802];constructor(e,t){super(e,t),this.kind??=9802}static from(t){return new e(t.ndk,t)}get url(){return this.tagValue("r")}set context(e){void 0===e?this.tags=this.tags.filter(([e,t])=>"context"!==e):(this.tags=this.tags.filter(([e,t])=>"context"!==e),this.tags.push(["context",e]))}get context(){return this.tags.find(([e,t])=>"context"===e)?.[1]??void 0}get article(){return this._article}set article(e){this._article=e,"string"==typeof e?this.tags.push(["r",e]):this.tag(e)}getArticleTag(){return this.getMatchingTags("a")[0]||this.getMatchingTags("e")[0]||this.getMatchingTags("r")[0]}async getArticle(){if(void 0!==this._article)return this._article;let e;const t=this.getArticleTag();if(t){switch(t[0]){case"a":{const[n,s,r]=t[1].split(":");e=nip19_exports$1.naddrEncode({kind:Number.parseInt(n),pubkey:s,identifier:r});break}case"e":e=nip19_exports$1.noteEncode(t[1]);break;case"r":this._article=t[1]}if(e){let t=await(this.ndk?.fetchEvent(e));t&&(30023===t.kind&&(t=NDKArticle.from(t)),this._article=t)}return this._article}}},NDKImage=class e extends NDKEvent{static kind=20;static kinds=[20];_imetas;constructor(e,t){super(e,t),this.kind??=20}static from(t){return new e(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas||(this._imetas=this.tags.filter(e=>"imeta"===e[0]).map(mapImetaTag).filter(e=>!!e.url)),this._imetas}set imetas(e){this._imetas=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),this.tags.push(...e.map(imetaTagToTag))}},NDKList=class e extends NDKEvent{_encryptedTags;static kinds=[30001,10004,10050,10030,10015,10001,10002,10007,10006,10003];encryptedTagsLength;constructor(e,t){super(e,t),this.kind??=30001}static from(t){return new e(t.ndk,t)}get title(){const e=this.tagValue("title")||this.tagValue("name");return e||(3===this.kind?"Contacts":1e4===this.kind?"Mute":10001===this.kind?"Pinned Notes":10002===this.kind?"Relay Metadata":10003===this.kind?"Bookmarks":10004===this.kind?"Communities":10005===this.kind?"Public Chats":10006===this.kind?"Blocked Relays":10007===this.kind?"Search Relays":10050===this.kind?"Direct Message Receive Relays":10015===this.kind?"Interests":10030===this.kind?"Emojis":this.tagValue("d"))}set title(e){this.removeTag(["title","name"]),e&&this.tags.push(["title",e])}get name(){return this.title}set name(e){this.title=e}get description(){return this.tagValue("description")}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}isEncryptedTagsCacheValid(){return!(!this._encryptedTags||this.encryptedTagsLength!==this.content.length)}async encryptedTags(e=!0){if(e&&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 t=await this.ndk.signer.user();try{if(this.content.length>0)try{const e=await this.ndk.signer.decrypt(t,this.content),n=JSON.parse(e);return n?.[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=n):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch(e){}}catch(e){}return[]}validateTag(e){return!0}getItems(e){return this.tags.filter(t=>t[0]===e)}get items(){return this.tags.filter(e=>!["d","L","l","title","name","description","published_at","summary","image","thumb","alt","expiration","subject","client"].includes(e[0]))}async addItem(e,t=void 0,n=!1,s="bottom"){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let r;if(e instanceof NDKEvent)r=[e.tagReference(t)];else if(e instanceof NDKUser)r=e.referenceTags();else if(e instanceof NDKRelay)r=e.referenceTags();else{if(!Array.isArray(e))throw new Error("Invalid object type");r=[e]}if(t&&r[0].push(t),n){const e=await this.ndk.signer.user(),t=await this.encryptedTags();"top"===s?t.unshift(...r):t.push(...r),this._encryptedTags=t,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(t),await this.encrypt(e)}else"top"===s?this.tags.unshift(...r):this.tags.push(...r);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItemByValue(e,t=!0){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const n=this.tags.findIndex(t=>t[1]===e);n>=0&&this.tags.splice(n,1);const s=await this.ndk.signer.user(),r=await this.encryptedTags(),i=r.findIndex(t=>t[1]===e);if(i>=0&&(r.splice(i,1),this._encryptedTags=r,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(r),await this.encrypt(s)),t)return this.publishReplaceable();this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(e,t){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(t){const t=await this.ndk.signer.user(),n=await this.encryptedTags();n.splice(e,1),this._encryptedTags=n,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(n),await this.encrypt(t)}else this.tags.splice(e,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}has(e){return this.items.some(t=>t[1]===e)}filterForItems(){const e=new Set,t=new Map,n=[];for(const n of this.items)if("e"===n[0]&&n[1])e.add(n[1]);else if("a"===n[0]&&n[1]){const[e,s,r]=n[1].split(":");if(!e||!s)continue;const i=`${e}:${s}`,o=t.get(i)||[];o.push(r||""),t.set(i,o)}if(e.size>0&&n.push({ids:Array.from(e)}),t.size>0)for(const[e,s]of t.entries()){const[t,r]=e.split(":");n.push({kinds:[Number.parseInt(t)],authors:[r],"#d":s})}return n}},NDKAppHandlerEvent=class e extends NDKEvent{profile;static kinds=[31990];constructor(e,t){super(e,t),this.kind??=31990}static from(t){const n=new e(t.ndk,t.rawEvent());return n.isValid?n:null}get isValid(){const e=new Map,t=e=>[e[0],e[2]].join(":").toLowerCase(),n=["web","android","ios"];for(const s of this.tags)if(n.includes(s[0])){const n=t(s);if(e.has(n)&&e.get(n)!==s[1].toLowerCase())return!1;e.set(n,s[1].toLowerCase())}return!0}async fetchProfile(){if(void 0===this.profile&&this.content.length>0)try{const e=JSON.parse(this.content);if(e?.name)return e;this.profile=null}catch(e){this.profile=null}return new Promise((e,t)=>{const n=this.author;n.fetchProfile().then(()=>{e(n.profile)}).catch(t)})}},NDKNutzap=class e extends NDKEvent{debug;_proofs=[];static kind=9321;static kinds=[e.kind];constructor(e,t){super(e,t),this.kind??=9321,this.debug=e?.debug.extend("nutzap")??createDebug5("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const e=this.getMatchingTags("proof");e.length?this._proofs=e.map(e=>JSON.parse(e[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(t){const n=new e(t.ndk,t);if(n._proofs&&n._proofs.length)return n}set comment(e){this.content=e??""}get comment(){const e=this.tagValue("comment");return e||this.content}set proofs(e){this._proofs=e,this.tags=this.tags.filter(e=>"proof"!==e[0]);for(const t of e)this.tags.push(["proof",JSON.stringify(t)])}get proofs(){return this._proofs}get rawP2pk(){const e=this.proofs[0];try{const t=JSON.parse(e.secret);let n;if("string"==typeof t?(n=JSON.parse(t),this.debug("stringified payload",e.secret)):"object"==typeof t&&(n=t),Array.isArray(n)&&"P2PK"===n[0]&&n.length>1&&"object"==typeof n[1]&&null!==n[1])return n[1].data;if("object"==typeof n&&null!==n&&"string"==typeof n[1]?.data)return n[1].data}catch(e){this.debug("error parsing p2pk pubkey",e,this.proofs[0])}}get p2pk(){const e=this.rawP2pk;if(e)return e.startsWith("02")?e.slice(2):e}get mint(){return this.tagValue("u")}set mint(e){this.replaceTag(["u",e])}get unit(){let e=this.tagValue("unit")??"sat";return e?.startsWith("msat")&&(e="sat"),e}set unit(e){if(this.removeTag("unit"),e?.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");e&&this.tag(["unit",e])}get amount(){return this.proofs.reduce((e,t)=>e+t.amount,0)}sender=this.author;set target(e){this.tags=this.tags.filter(e=>"p"!==e[0]),e instanceof NDKEvent&&this.tags.push(e.tagReference())}set recipientPubkey(e){this.removeTag("p"),this.tag(["p",e])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const e=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:e}):new NDKUser({pubkey:e})}async toNostrEvent(){"msat"===this.unit&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const e=await super.toNostrEvent();return e.content=this.comment,e}get isValid(){let e=0,t=0,n=0;for(const s of this.tags)"e"===s[0]&&e++,"p"===s[0]&&t++,"u"===s[0]&&n++;return 1===t&&1===n&&e<=1&&this.proofs.length>0}},NDKProject=class e extends NDKEvent{static kind=31933;static kinds=[31933];_signer;constructor(e,t){super(e,t),this.kind=31933}static from(t){return new e(t.ndk,t.rawEvent())}set repo(e){this.removeTag("repo"),e&&this.tags.push(["repo",e])}set hashtags(e){this.removeTag("hashtags"),e.filter(e=>e.length>0).length&&this.tags.push(["hashtags",...e])}get hashtags(){const e=this.tags.find(e=>"hashtags"===e[0]);return e?e.slice(1):[]}get repo(){return this.tagValue("repo")}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get picture(){return this.tagValue("picture")}set picture(e){this.removeTag("picture"),e&&this.tags.push(["picture",e])}set description(e){this.content=e}get description(){return this.content}get slug(){return this.dTag??"empty-dtag"}async getSigner(){if(this._signer)return this._signer;const e=this.tagValue("key");if(e){const t=await(this.ndk?.signer?.decrypt(this.ndk.activeUser,e));if(!t)throw new Error("Failed to decrypt project key or missing signer context.");this._signer=new NDKPrivateKeySigner(t)}else this._signer=NDKPrivateKeySigner.generate(),await this.encryptAndSaveNsec();return this._signer}async getNsec(){return(await this.getSigner()).privateKey}async setNsec(e){this._signer=new NDKPrivateKeySigner(e),await this.encryptAndSaveNsec()}async encryptAndSaveNsec(){if(!this._signer)throw new Error("Signer is not set.");const e=this._signer.privateKey,t=await(this.ndk?.signer?.encrypt(this.ndk.activeUser,e));t&&(this.removeTag("key"),this.tags.push(["key",t]))}},NDKProjectTemplate=class e extends NDKEvent{static kind=30717;static kinds=[30717];constructor(e,t){super(e,t),this.kind=30717}static from(t){return new e(t.ndk,t.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(e=>"t"!==e[0]),e.forEach(e=>{e&&this.tags.push(["t",e])})}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class e extends NDKEvent{static kinds=[10002];constructor(e,t){super(e,t),this.kind??=10002}static from(t){return new e(t.ndk,t.rawEvent())}get readRelayUrls(){return this.tags.filter(e=>"r"===e[0]||"relay"===e[0]).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=>"r"===e[0]||"relay"===e[0]).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=>"r"===e[0]||"relay"===e[0]).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=>"r"===e[0]||"relay"===e[0]).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=>this.ndk?.pool.getRelay(e)).filter(e=>!!e)),this.ndk)}};function relayListFromKind3(e,t){try{const n=JSON.parse(t.content),s=new NDKRelayList(e),r=new Set,i=new Set;for(let[e,t]of Object.entries(n)){try{e=normalizeRelayUrl(e)}catch{continue}if(t){const n=t;n.write&&i.add(e),n.read&&r.add(e)}else r.add(e),i.add(e)}return s.readRelayUrls=Array.from(r),s.writeRelayUrls=Array.from(i),s}catch{}}var NDKRepost=class e extends NDKEvent{_repostedEvents;static kinds=[6,16];static from(t){return new e(t.ndk,t.rawEvent())}async repostedEvents(e,t){const n=[];if(!this.ndk)throw new Error("NDK instance not set");if(void 0!==this._repostedEvents)return this._repostedEvents;for(const s of this.repostedEventIds()){const r=filterForId(s),i=await this.ndk.fetchEvent(r,t);i&&n.push(e?e.from(i):i)}return n}repostedEventIds(){return this.tags.filter(e=>"e"===e[0]||"a"===e[0]).map(e=>e[1])}};function filterForId(e){if(e.match(/:/)){const[t,n,s]=e.split(":");return{kinds:[Number.parseInt(t)],authors:[n],"#d":[s]}}return{ids:[e]}}var NDKSimpleGroupMemberList=class e extends NDKEvent{relaySet;memberSet=new Set;static kind=39002;static kinds=[39002];constructor(e,t){super(e,t),this.kind??=39002,this.memberSet=new Set(this.members)}static from(t){return new e(t.ndk,t)}get members(){return this.getMatchingTags("p").map(e=>e[1])}hasMember(e){return this.memberSet.has(e)}async publish(e,t,n){return e??=this.relaySet,super.publishReplaceable(e,t,n)}},NDKSimpleGroupMetadata=class e extends NDKEvent{static kind=39e3;static kinds=[39e3];constructor(e,t){super(e,t),this.kind??=39e3}static from(t){return new e(t.ndk,t)}get name(){return this.tagValue("name")}get picture(){return this.tagValue("picture")}get about(){return this.tagValue("about")}get scope(){return this.getMatchingTags("public").length>0?"public":this.getMatchingTags("public").length>0?"private":void 0}set scope(e){this.removeTag("public"),this.removeTag("private"),"public"===e?this.tags.push(["public",""]):"private"===e&&this.tags.push(["private",""])}get access(){return this.getMatchingTags("open").length>0?"open":this.getMatchingTags("closed").length>0?"closed":void 0}set access(e){this.removeTag("open"),this.removeTag("closed"),"open"===e?this.tags.push(["open",""]):"closed"===e&&this.tags.push(["closed",""])}};function strToPosition(e){const[t,n]=e.split(",").map(Number);return{x:t,y:n}}function strToDimension(e){const[t,n]=e.split("x").map(Number);return{width:t,height:n}}var NDKStorySticker=class e{static Text="text";static Pubkey="pubkey";static Event="event";static Prompt="prompt";static Countdown="countdown";type;value;position;dimension;properties;constructor(e){if(Array.isArray(e)){const t=e;if("sticker"!==t[0]||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 n={};for(let e=5;e<t.length;e++){const[s,...r]=t[e].split(" ");n[s]=r.join(" ")}Object.keys(n).length>0&&(this.properties=n)}else this.type=e,this.value=void 0,this.position={x:0,y:0},this.dimension={width:0,height:0}}static fromTag(t){try{return new e(t)}catch{return null}}get style(){return this.properties?.style}set style(e){e?this.properties={...this.properties,style:e}:delete this.properties?.style}get rotation(){return this.properties?.rot?Number.parseFloat(this.properties.rot):void 0}set rotation(e){void 0!==e?this.properties={...this.properties,rot:e.toString()}:delete this.properties?.rot}get isValid(){return this.hasValidDimensions()&&this.hasValidPosition()}hasValidDimensions=()=>"number"==typeof this.dimension.width&&"number"==typeof this.dimension.height&&!Number.isNaN(this.dimension.width)&&!Number.isNaN(this.dimension.height);hasValidPosition=()=>"number"==typeof this.position.x&&"number"==typeof this.position.y&&!Number.isNaN(this.position.x)&&!Number.isNaN(this.position.y);toTag(){if(!this.isValid){const e=[this.hasValidDimensions()?void 0:"dimensions is invalid",this.hasValidPosition()?void 0:"position is invalid"].filter(Boolean);throw new Error(`Invalid sticker: ${e.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[e,n]of Object.entries(this.properties))t.push(`${e} ${n}`);return t}},NDKStory=class e extends NDKEvent{static kind=23;static kinds=[23];_imeta;_dimensions;constructor(e,t){if(super(e,t),this.kind??=23,t)for(const e of t.tags)switch(e[0]){case"imeta":this._imeta=mapImetaTag(e);break;case"dim":this.dimensions=strToDimension(e[1])}}static from(t){return new e(t.ndk,t)}get isValid(){return!!this.imeta}get imeta(){return this._imeta}set imeta(e){this._imeta=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),e&&this.tags.push(imetaTagToTag(e))}get dimensions(){const e=this.tagValue("dim");if(e)return strToDimension(e)}set dimensions(e){this.removeTag("dim"),e&&this.tags.push(["dim",`${e.width}x${e.height}`])}get duration(){const e=this.tagValue("dur");if(e)return Number.parseInt(e)}set duration(e){this.removeTag("dur"),void 0!==e&&this.tags.push(["dur",e.toString()])}get stickers(){const e=[];for(const t of this.tags){if("sticker"!==t[0]||t.length<5)continue;const n=NDKStorySticker.fromTag(t);n&&e.push(n)}return e}addSticker(e){let t;if(e instanceof NDKStorySticker)t=e;else{const n=["sticker",e.type,"string"==typeof e.value?e.value:"",coordinates(e.position),dimension(e.dimension)];if(e.properties)for(const[t,s]of Object.entries(e.properties))n.push(`${t} ${s}`);t=new NDKStorySticker(n),t.value=e.value}("pubkey"===t.type||"event"===t.type)&&this.tag(t.value),this.tags.push(t.toTag())}removeSticker(e){const t=this.stickers;if(e<0||e>=t.length)return;let n=0;for(let t=0;t<this.tags.length;t++)if("sticker"===this.tags[t][0]){if(n===e){this.tags.splice(t,1);break}n++}}},coordinates=e=>`${e.x},${e.y}`,dimension=e=>`${e.width}x${e.height}`,NDKSubscriptionReceipt=class e extends NDKEvent{debug;static kinds=[7003];constructor(e,t){super(e,t),this.kind??=7003,this.debug=e?.debug.extend("subscription-start")??createDebug5("ndk:subscription-start")}static from(t){return new e(t.ndk,t.rawEvent())}get recipient(){const e=this.getMatchingTags("p")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set recipient(e){this.removeTag("p"),e&&this.tags.push(["p",e.pubkey])}get subscriber(){const e=this.getMatchingTags("P")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set subscriber(e){this.removeTag("P"),e&&this.tags.push(["P",e.pubkey])}set subscriptionStart(e){this.debug(`before setting subscription start: ${this.rawEvent}`),this.removeTag("e"),this.tag(e,"subscription",!0),this.debug(`after setting subscription start: ${this.rawEvent}`)}get tierName(){const e=this.getMatchingTags("tier")?.[0];return e?.[1]}get isValid(){const e=this.validPeriod;if(!e)return!1;if(e.start>e.end)return!1;const t=this.getMatchingTags("p"),n=this.getMatchingTags("P");return 1===t.length&&1===n.length}get validPeriod(){const e=this.getMatchingTags("valid")?.[0];if(e)try{return{start:new Date(1e3*Number.parseInt(e[1])),end:new Date(1e3*Number.parseInt(e[2]))}}catch{return}}set validPeriod(e){this.removeTag("valid"),e&&this.tags.push(["valid",Math.floor(e.start.getTime()/1e3).toString(),Math.floor(e.end.getTime()/1e3).toString()])}get startPeriod(){return this.validPeriod?.start}get endPeriod(){return this.validPeriod?.end}isActive(e){e??=new Date;const t=this.validPeriod;return!!t&&(!(e<t.start)&&!(e>t.end))}},possibleIntervalFrequencies=["daily","weekly","monthly","quarterly","yearly"];function newAmount(e,t,n){return["amount",e.toString(),t,n]}function parseTagToSubscriptionAmount(e){const t=Number.parseInt(e[1]);if(Number.isNaN(t)||null==t||t<=0)return;const n=e[2];if(void 0===n||""===n)return;const s=e[3];return void 0!==s&&possibleIntervalFrequencies.includes(s)?{amount:t,currency:n,term:s}:void 0}var NDKSubscriptionTier=class e extends NDKArticle{static kind=37001;static kinds=[37001];constructor(e,t){const n=t?.kind??37001;super(e,t),this.kind=n}static from(t){return new e(t.ndk,t)}get perks(){return this.getMatchingTags("perk").map(e=>e[1]).filter(e=>void 0!==e)}addPerk(e){this.tags.push(["perk",e])}get amounts(){return this.getMatchingTags("amount").map(e=>parseTagToSubscriptionAmount(e)).filter(e=>void 0!==e)}addAmount(e,t,n){this.tags.push(newAmount(e,t,n))}set relayUrl(e){this.tags.push(["r",e])}get relayUrls(){return this.getMatchingTags("r").map(e=>e[1]).filter(e=>void 0!==e)}get verifierPubkey(){return this.tagValue("p")}set verifierPubkey(e){this.removeTag("p"),e&&this.tags.push(["p",e])}get isValid(){return void 0!==this.title&&this.amounts.length>0}},NDKSubscriptionStart=class e extends NDKEvent{debug;static kinds=[7001];constructor(e,t){super(e,t),this.kind??=7001,this.debug=e?.debug.extend("subscription-start")??createDebug5("ndk:subscription-start")}static from(t){return new e(t.ndk,t.rawEvent())}get recipient(){const e=this.getMatchingTags("p")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set recipient(e){this.removeTag("p"),e&&this.tags.push(["p",e.pubkey])}get amount(){const e=this.getMatchingTags("amount")?.[0];if(e)return parseTagToSubscriptionAmount(e)}set amount(e){this.removeTag("amount"),e&&this.tags.push(newAmount(e.amount,e.currency,e.term))}get tierId(){const e=this.getMatchingTags("e")?.[0],t=this.getMatchingTags("a")?.[0];if(e&&t)return e[1]??t[1]}set tier(e){this.removeTag("e"),this.removeTag("a"),this.removeTag("event"),e&&(this.tag(e),this.removeTag("p"),this.tags.push(["p",e.pubkey]),this.tags.push(["event",JSON.stringify(e.rawEvent())]))}async fetchTier(){const e=this.tagValue("event");if(e)try{const t=JSON.parse(e);return new NDKSubscriptionTier(this.ndk,t)}catch{this.debug("Failed to parse event tag")}const t=this.tierId;if(!t)return;const n=await(this.ndk?.fetchEvent(t));return n?NDKSubscriptionTier.from(n):void 0}get isValid(){return 1!==this.getMatchingTags("amount").length?(this.debug("Invalid # of amount tag"),!1):this.amount?1!==this.getMatchingTags("p").length?(this.debug("Invalid # of p tag"),!1):!!this.recipient||(this.debug("Invalid p tag"),!1):(this.debug("Invalid amount tag"),!1)}},NDKTask=class e extends NDKEvent{static kind=1934;static kinds=[1934];constructor(e,t){super(e,t),this.kind=1934}static from(t){return new e(t.ndk,t.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(){const e=this.getMatchingTags("a")[0];return e?e[1].split(/:/)?.[2]:void 0}},NDKThread=class e extends NDKEvent{static kind=11;static kinds=[11];constructor(e,t){super(e,t),this.kind??=11}static from(t){return new e(t.ndk,t)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}},NDKVideo=class e extends NDKEvent{static kind=21;static kinds=[34235,34236,22,21];_imetas;static from(t){return new e(t.ndk,t.rawEvent())}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get thumbnail(){let e;return this.imetas&&this.imetas.length>0&&(e=this.imetas[0].image?.[0]),e??this.tagValue("thumb")}get imetas(){return this._imetas||(this._imetas=this.tags.filter(e=>"imeta"===e[0]).map(mapImetaTag)),this._imetas}set imetas(e){this._imetas=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),this.tags.push(...e.map(imetaTagToTag))}get url(){return this.imetas&&this.imetas.length>0?this.imetas[0].url:this.tagValue("url")}get published_at(){const e=this.tagValue("published_at");if(e)return Number.parseInt(e)}async generateTags(){if(super.generateTags(),!this.kind&&this.imetas?.[0]?.dim){const[e,t]=this.imetas[0].dim.split("x"),n=e&&t&&Number.parseInt(e)<Number.parseInt(t),s=this.duration&&this.duration<120;this.kind=s&&n?22:21}return super.generateTags()}get duration(){const e=this.tagValue("duration");if(e)return Number.parseInt(e)}set duration(e){this.removeTag("duration"),void 0!==e&&this.tags.push(["duration",Math.floor(e).toString()])}},NDKWiki=class e extends NDKArticle{static kind=30818;static kinds=[30818];static from(t){return new e(t.ndk,t.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")}},NDKWikiMergeRequest=class e extends NDKEvent{static kinds=[818];static from(t){return new e(t.ndk,t.rawEvent())}get targetId(){return this.tagValue("a")}set target(e){this.tags=this.tags.filter(e=>"a"===e[0]||("e"===e[0]&&"source"!==e[3]||void 0)),this.tag(e)}get sourceId(){return this.tagValue("e","source")}set source(e){this.removeTag("e","source"),this.tag(e,"source",!1,"e")}},registeredEventClasses=new Set;function wrapEvent(e){const t=new Map,n=[...[NDKImage,NDKVideo,NDKCashuMintList,NDKArticle,NDKHighlight,NDKDraft,NDKWiki,NDKWikiMergeRequest,NDKNutzap,NDKProject,NDKTask,NDKProjectTemplate,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKSubscriptionTier,NDKSubscriptionStart,NDKSubscriptionReceipt,NDKList,NDKRelayList,NDKStory,NDKBlossomList,NDKFollowPack,NDKThread,NDKRepost,NDKClassified,NDKAppHandlerEvent,NDKDVMJobFeedback,NDKCashuMintAnnouncement,NDKFedimintMint,NDKMintRecommendation],...registeredEventClasses];for(const e of n)for(const n of e.kinds)t.set(n,e);const s=t.get(e.kind);return s?s.from(e):e}function queryFullyFilled(e){return!(!filterIncludesIds(e.filter)||!resultHasAllRequestedIds(e))}function filterIncludesIds(e){return!!e.ids}function resultHasAllRequestedIds(e){const t=e.filter.ids;return!!t&&t.length===e.eventFirstSeen.size}function filterFromId(e){let t;if(e.match(NIP33_A_REGEX)){const[t,n,s]=e.split(":"),r={authors:[n],kinds:[Number.parseInt(t)]};return s&&(r["#d"]=[s]),r}if(e.match(BECH32_REGEX))try{switch(t=nip19_exports$1.decode(e),t.type){case"nevent":{const e={ids:[t.data.id]};return t.data.author&&(e.authors=[t.data.author]),t.data.kind&&(e.kinds=[t.data.kind]),e}case"note":return{ids:[t.data]};case"naddr":{const e={authors:[t.data.pubkey],kinds:[t.data.kind]};return t.data.identifier&&(e["#d"]=[t.data.identifier]),e}}}catch(t){console.error("Error decoding",e,t)}return{ids:[e]}}function isNip33AValue(e){return null!==e.match(NIP33_A_REGEX)}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/,BECH32_REGEX=/^n(event|ote|profile|pub|addr)1[\d\w]+$/;function relaysFromBech32(e,t){try{const n=nip19_exports$1.decode(e);if(["naddr","nevent"].includes(n?.type)){const e=n.data;if(e?.relays)return e.relays.map(e=>new NDKRelay(e,t.relayAuthDefaultPolicy,t))}}catch(e){}return[]}var defaultOpts={closeOnEose:!1,cacheUsage:"CACHE_FIRST",dontSaveToCache:!1,groupable:!0,groupableDelay:100,groupableDelayType:"at-most",cacheUnconstrainFilter:["limit","since","until"],includeMuted:!1},NDKSubscription=class extends lib$1.EventEmitter{subId;filters;opts;pool;skipVerification=!1;skipValidation=!1;relayFilters;relaySet;ndk;debug;eventFirstSeen=new Map;eosesSeen=new Set;lastEventReceivedAt;mostRecentCacheEventTimestamp;internalId;closeOnEose;poolMonitor;skipOptimisticPublishEvent=!1;cacheUnconstrainFilter;constructor(e,t,n,s){super(),this.ndk=e,this.opts={...defaultOpts,...n||{}},this.pool=this.opts.pool||e.pool;const r=Array.isArray(t)?t:[t],i="validate"===e.filterValidationMode?"validate":"fix"===e.filterValidationMode?"fix":"ignore";if(this.filters=processFilters(r,i,e.debug,e),0===this.filters.length)throw new Error("Subscription must have at least one filter");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,this.opts.onEvent&&this.on("event",this.opts.onEvent),this.opts.onEose&&this.on("eose",this.opts.onEose),this.opts.onClose&&this.on("close",this.opts.onClose)}relaysMissingEose(){if(!this.relayFilters)return[];return Array.from(this.relayFilters?.keys()).filter(e=>!this.eosesSeen.has(this.pool.getRelay(e,!1,!1)))}get filter(){return this.filters[0]}get groupableDelay(){if(this.isGroupable())return this.opts?.groupableDelay}get groupableDelayType(){return this.opts?.groupableDelayType||"at-most"}isGroupable(){return this.opts?.groupable||!1}shouldQueryCache(){if(this.opts.addSinceFromCache)return!0;if("ONLY_RELAY"===this.opts?.cacheUsage)return!1;this.filters.some(e=>e.kinds?.some(e=>kindIsEphemeral(e)));return!0}shouldQueryRelays(){return"ONLY_CACHE"!==this.opts?.cacheUsage}shouldWaitForCache(){return!!this.opts.addSinceFromCache||!!this.opts.closeOnEose&&!!this.ndk.cacheAdapter?.locking&&"PARALLEL"!==this.opts.cacheUsage}start(e=!0){let t;const n=n=>{for(const e of n)e.created_at&&(!this.mostRecentCacheEventTimestamp||e.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=e.created_at),this.eventReceived(e,void 0,!0,!1);e||(t=n)},s=()=>{this.shouldQueryRelays()?(this.startWithRelays(),this.startPoolMonitor()):this.emit("eose",this)};return this.shouldQueryCache()?(t=this.startWithCache(),t instanceof Promise?this.shouldWaitForCache()?(t.then(e=>{n(e),queryFullyFilled(this)?this.emit("eose",this):s()}),null):(t.then(e=>{n(e),this.shouldQueryRelays()||this.emit("eose",this)}),this.shouldQueryRelays()&&s(),null):(n(t),queryFullyFilled(this)?this.emit("eose",this):s(),t)):(s(),null)}startPoolMonitor(){this.debug.extend("pool-monitor"),this.poolMonitor=e=>{if(this.relayFilters?.has(e.url))return;calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool,this.opts.relayGoalPerAuthor).get(e.url)&&(this.relayFilters?.set(e.url,this.filters),e.subscribe(this,this.filters))},this.pool.on("relay:connect",this.poolMonitor)}onStopped;stop(){this.emit("close",this),this.poolMonitor&&this.pool.off("relay:connect",this.poolMonitor),this.onStopped?.()}hasAuthorsFilter(){return this.filters.some(e=>e.authors?.length)}startWithCache(){return this.ndk.cacheAdapter?.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(e=>({...e,since:Math.max(e.since||0,t)}))}if(this.relaySet&&0!==this.relaySet.relays.size){this.relayFilters=new Map;for(const t of this.relaySet.relays)this.relayFilters.set(t.url,e)}else this.relayFilters=calculateRelaySetsFromFilters(this.ndk,e,this.pool,this.opts.relayGoalPerAuthor);for(const[e,t]of this.relayFilters){this.pool.getRelay(e,!0,!0,t).subscribe(this,t)}}refreshRelayConnections(){if(this.relaySet&&this.relaySet.relays.size>0)return;const e=calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool,this.opts.relayGoalPerAuthor);for(const[t,n]of e)if(!this.relayFilters?.has(t)){this.relayFilters?.set(t,n);this.pool.getRelay(t,!0,!0,n).subscribe(this,n)}}eventReceived(e,t,n=!1,s=!1){const r=e.id,i=this.eventFirstSeen.has(r);let o;if(e instanceof NDKEvent&&(o=e),i){const i=Date.now()-(this.eventFirstSeen.get(r)||0);if(this.emit("event:dup",e,t,i,this,n,s),this.opts?.onEventDup&&this.opts.onEventDup(e,t,i,this,n,s),n||s||!t||!this.ndk.cacheAdapter?.setEventDup||this.opts.dontSaveToCache||(o??=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e),this.ndk.cacheAdapter.setEventDup(o,t)),t){const n=verifiedSignatures.get(r);if(n&&"string"==typeof n)if(e.sig===n)t.addValidatedEvent();else{const n=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e);this.ndk.reportInvalidSignature(n,t)}}}else{if(o??=new NDKEvent(this.ndk,e),o.ndk=this.ndk,o.relay=t,!n&&!s){if(!this.skipValidation&&!o.isValid)return void this.debug("Event failed validation %s from relay %s",r,t?.url);if(t){if(t.shouldValidateEvent()&&!this.skipVerification)if(o.relay=t,this.ndk.asyncSigVerification)o.verifySignature(!0);else{if(!o.verifySignature(!0))return this.debug("Event failed signature validation",e),void this.ndk.reportInvalidSignature(o,t);t.addValidatedEvent()}else t.addNonValidatedEvent()}this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(o,this.filters,t)}if(!this.opts.includeMuted&&this.ndk.muteFilter&&this.ndk.muteFilter(o))return void this.debug("Event muted, skipping");s&&!0===this.skipOptimisticPublishEvent||(this.emitEvent(this.opts?.wrap??!1,o,t,n,s),this.eventFirstSeen.set(r,Date.now()))}this.lastEventReceivedAt=Date.now()}emitEvent(e,t,n,s,r){const i=e?wrapEvent(t):t;i instanceof Promise?i.then(e=>this.emitEvent(!1,e,n,s,r)):i&&this.emit("event",i,n,this,s,r)}closedReceived(e,t){this.emit("closed",e,t)}eoseTimeout;eosed=!1;eoseReceived(e){this.debug("EOSE received from %s",e.url),this.eosesSeen.add(e);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const n=this.eosesSeen.size===this.relayFilters?.size,s=queryFullyFilled(this),r=e=>{this.debug("Performing EOSE: %s %d",e,this.eosed),this.eosed||(this.eoseTimeout&&clearTimeout(this.eoseTimeout),this.emit("eose",this),this.eosed=!0,this.opts?.closeOnEose&&this.stop())};if(s||n)r("query filled or seen all");else if(this.relayFilters){let e=1e3;const n=new Set(this.pool.connectedRelays().map(e=>e.url)),s=Array.from(this.relayFilters.keys()).filter(e=>n.has(e));if(0===s.length)return void this.debug("No connected relays, waiting for all relays to connect",Array.from(this.relayFilters.keys()).join(", "));const i=this.eosesSeen.size/s.length;if(this.debug("Percentage of relays that have sent EOSE",{subId:this.subId,percentageOfRelaysThatHaveSentEose:i,seen:this.eosesSeen.size,total:s.length}),this.eosesSeen.size>=2&&i>=.5){if(e*=1-i,0===e)return void r("time to wait was 0");this.eoseTimeout&&clearTimeout(this.eoseTimeout);const n=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,void 0!==t&&t<20?this.eoseTimeout=setTimeout(n,e):r(`send eose timeout: ${e}`)};this.eoseTimeout=setTimeout(n,e)}}}},kindIsEphemeral=e=>e>=2e4&&e<3e4;async function follows(e,t,n=3){if(!this.ndk)throw new Error("NDK not set");const s=await this.ndk.fetchEvent({kinds:[n],authors:[this.pubkey]},e||{groupable:!1});if(s){const e=new Set;return s.tags.forEach(t=>{"p"===t[0]&&t[1]&&isValidPubkey(t[1])&&e.add(t[1])}),t&&this.ndk?.outboxTracker?.trackUsers(Array.from(e)),[...e].reduce((e,t)=>{const n=new NDKUser({pubkey:t});return n.ndk=this.ndk,e.add(n),e},new Set)}return new Set}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(e,t,n=fetch,s={}){return await e.queuesNip05.add({id:t,func:async()=>{if(e.cacheAdapter?.loadNip05){const n=await e.cacheAdapter.loadNip05(t);if("missing"!==n){if(n){const t=new NDKUser({pubkey:n.pubkey,relayUrls:n.relays,nip46Urls:n.nip46});return t.ndk=e,t}if("no-cache"!==s.cache)return null}}const r=t.match(NIP05_REGEX);if(!r)return null;const[i,o="_",a]=r;try{const r=await n(`https://${a}/.well-known/nostr.json?name=${o}`,s),{names:i,relays:c,nip46:l}=parseNIP05Result(await r.json()),u=i[o.toLowerCase()];let d=null;return u&&(d={pubkey:u,relays:c?.[u],nip46:l?.[u]}),e?.cacheAdapter?.saveNip05&&e.cacheAdapter.saveNip05(t,d),d}catch(n){return e?.cacheAdapter?.saveNip05&&e?.cacheAdapter.saveNip05(t,null),console.error("Failed to fetch NIP05 for",t,n),null}}})}function parseNIP05Result(e){const t={names:{}};for(const[n,s]of Object.entries(e.names))"string"==typeof n&&"string"==typeof s&&(t.names[n.toLowerCase()]=s);if(e.relays){t.relays={};for(const[n,s]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(s)&&(t.relays[n]=s.filter(e=>"string"==typeof e))}if(e.nip46){t.nip46={};for(const[n,s]of Object.entries(e.nip46))"string"==typeof n&&Array.isArray(s)&&(t.nip46[n]=s.filter(e=>"string"==typeof e))}return t}function profileFromEvent(e){const t={};let n;try{n=JSON.parse(e.content)}catch(e){throw new Error(`Failed to parse profile event: ${e}`)}t.profileEvent=JSON.stringify(e.rawEvent());for(const e of Object.keys(n))switch(e){case"name":t.name=n.name;break;case"display_name":t.displayName=n.display_name;break;case"image":case"picture":t.picture=n.picture||n.image,t.image=t.picture;break;case"banner":t.banner=n.banner;break;case"bio":t.bio=n.bio;break;case"nip05":t.nip05=n.nip05;break;case"lud06":t.lud06=n.lud06;break;case"lud16":t.lud16=n.lud16;break;case"about":t.about=n.about;break;case"website":t.website=n.website;break;default:t[e]=n[e]}return t.created_at=e.created_at,t}function serializeProfile(e){const t={};for(const[n,s]of Object.entries(e))switch(n){case"username":case"name":t.name=s;break;case"displayName":t.display_name=s;break;case"image":case"picture":t.picture=s;break;case"bio":case"about":t.about=s;break;default:t[n]=s}return JSON.stringify(t)}var NDKUser=class e{ndk;profile;profileEvent;_npub;_pubkey;relayUrls=[];nip46Urls=[];constructor(e){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$1.decode(e.nprofile);"nprofile"===t.type&&(this._pubkey=t.data.pubkey,t.data.relays&&t.data.relays.length>0&&this.relayUrls.push(...t.data.relays))}catch(e){console.error("Failed to decode nprofile",e)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nip19_exports$1.npubEncode(this.pubkey)}return this._npub}get nprofile(){const e=this.profileEvent?.onRelays?.map(e=>e.url);return nip19_exports$1.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$1.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 t=>{if(!e)return t;let n;const s=new Promise((t,s)=>{n=setTimeout(()=>s(new Error("Timeout")),e)});try{const e=await Promise.race([t,s]);return n&&clearTimeout(n),e}catch(e){if(e instanceof Error&&"Timeout"===e.message)try{return await t}catch(e){return}return}},[n,s]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),r=new Map;if(s){const e=NDKCashuMintList.from(s);e.mints.length>0&&r.set("nip61",{mints:e.mints,relays:e.relays,p2pk:e.p2pk})}if(n){const{lud06:e,lud16:t}=n;r.set("nip57",{lud06:e,lud16:t})}return r}static async fromNip05(t,n,s=!1){if(!n)throw new Error("No NDK instance found");const r={};s&&(r.cache="no-cache");const i=await getNip05For(n,t,n?.httpFetch,r);if(i){const t=new e({pubkey:i.pubkey,relayUrls:i.relays,nip46Urls:i.nip46});return t.ndk=n,t}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let n=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&"ONLY_RELAY"!==e?.cacheUsage){let e=null;if(this.ndk.cacheAdapter.fetchProfileSync?e=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(e=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),e)return this.profile=e,e}return e??={},e.cacheUsage??="ONLY_RELAY",e.closeOnEose??=!0,e.groupable??=!0,e.groupableDelay??=250,n||(n=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),n?(this.profile=profileFromEvent(n),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}follows=follows.bind(this);async followSet(e,t,n=3){const s=await this.follows(e,t,n);return new Set(Array.from(s).map(e=>e.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e?(t[0].push("",e),t):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();const e=new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)});await e.publish()}async follow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n)),t.has(e))return!1;t.add(e);const s=new NDKEvent(this.ndk,{kind:n});for(const e of t)s.tag(e);return await s.publish(),!0}async unfollow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n));const s=new Set;let r=!1;for(const n of t)n.pubkey!==e.pubkey?s.add(n):r=!0;if(!r)return!1;const i=new NDKEvent(this.ndk,{kind:n});for(const e of s)i.tag(e);return await i.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return null===t?null:t.pubkey===this.pubkey}},signerRegistry=new Map;function registerSigner(e,t){signerRegistry.set(e,t)}var NDKPrivateKeySigner=class e{_user;_privateKey;_pubkey;constructor(e,t){if("string"==typeof e)if(e.startsWith("nsec1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nsec"!==t)throw new Error("Invalid private key provided.");this._privateKey=n}else{if(64!==e.length)throw new Error("Invalid private key provided.");this._privateKey=hexToBytes(e)}else this._privateKey=e;this._pubkey=getPublicKey(this._privateKey),t&&(this._user=t.getUser({pubkey:this._pubkey})),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$1.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nip19_exports$1.npubEncode(this._pubkey)}encryptToNcryptsec(e,t=16,n=2){if(!this._privateKey)throw new Error("Private key not available");return encrypt$1(this._privateKey,e,t,n)}static generate(){const t=generateSecretKey();return new e(t)}static fromNcryptsec(t,n,s){const r=decrypt$1(t,n);return new e(r,s)}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&&"nip04"!==e||t.push("nip04"),e&&"nip44"!==e||t.push("nip44"),t}async encrypt(e,t,n){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const s=e.pubkey;if("nip44"===n){const e=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.encrypt(t,e)}return await nip04_exports.encrypt(this._privateKey,s,t)}async decrypt(e,t,n){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const s=e.pubkey;if("nip44"===n){const e=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.decrypt(t,e)}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(t,n){const s=JSON.parse(t);if("private-key"!==s.type)throw new Error(`Invalid payload type: expected 'private-key', got ${s.type}`);if(!s.payload||"string"!=typeof s.payload)throw new Error("Invalid payload content for private-key signer");return new e(s.payload,n)}};function dedup(e,t){return e.created_at>t.created_at?e:t}async function getRelayListForUser(e,t){return(await getRelayListForUsers([e],t)).get(e)}async function getRelayListForUsers(e,t,n=!1,s=1e3,r){const i=t.outboxPool||t.pool,o=new Set;for(const e of i.relays.values())o.add(e);if(r)for(const e of r.values())for(const t of e){const e=i.getRelay(t,!0,!0);e&&o.add(e)}const a=new Map,c=new Map,l=new NDKRelaySet(o,t);if(t.cacheAdapter?.locking&&!n){const n=await t.fetchEvents({kinds:[3,10002],authors:Array.from(new Set(e))},{cacheUsage:"ONLY_CACHE",subId:"ndk-relay-list-fetch"});for(const e of n)10002===e.kind&&a.set(e.pubkey,NDKRelayList.from(e));for(const e of n)if(3===e.kind){if(a.has(e.pubkey))continue;const n=relayListFromKind3(t,e);n&&c.set(e.pubkey,n)}e=e.filter(e=>!a.has(e)&&!c.has(e))}if(0===e.length)return a;const u=new Map,d=new Map;return new Promise(n=>{let r=!1;(async()=>{const c={closeOnEose:!0,pool:i,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:l};l&&(c.relaySet=l),t.subscribe({kinds:[3,10002],authors:e},c,{onEvent:e=>{if(10002===e.kind){const t=u.get(e.pubkey);if(t&&t.created_at>e.created_at)return;u.set(e.pubkey,e)}else if(3===e.kind){const t=d.get(e.pubkey);if(t&&t.created_at>e.created_at)return;d.set(e.pubkey,e)}},onEose:()=>{if(!r){r=!0,t.debug(`[getRelayListForUsers] EOSE - relayListEvents: ${u.size}, contactListEvents: ${d.size}`);for(const e of u.values())a.set(e.pubkey,NDKRelayList.from(e));for(const n of e){if(a.has(n))continue;const e=d.get(n);if(!e)continue;const s=relayListFromKind3(t,e);s&&a.set(n,s)}t.debug(`[getRelayListForUsers] Returning ${a.size} relay lists for ${e.length} pubkeys`),n(a)}}});const h=Array.from(o).some(e=>e.status<=2),p=Array.from(o).some(e=>4===e.status);let f=s;(h||p)&&(f=s+3e3),t.debug(`[getRelayListForUsers] Setting fallback timeout to ${f}ms (disconnected: ${h}, connecting: ${p})`,{pubkeys:e}),setTimeout(()=>{r||(r=!0,t.debug(`[getRelayListForUsers] Timeout reached, returning ${a.size} relay lists`),n(a))},f)})()})}registerSigner("private-key",NDKPrivateKeySigner);var OutboxItem=class{type;relayUrlScores;readRelays;writeRelays;constructor(e){this.type=e,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{data;ndk;debug;constructor(e){super(),this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:12e4})}async trackUsers(e,t=!1){const n=[];for(let s=0;s<e.length;s+=400){const r=e.slice(s,s+400),i=r.map(e=>getKeyFromItem(e)).filter(e=>!this.data.has(e));if(0===i.length)continue;for(const e of i)this.data.set(e,new OutboxItem("user"));const o=new Map;for(const e of r)e instanceof NDKUser&&e.relayUrls.length>0&&o.set(e.pubkey,e.relayUrls);n.push(new Promise(e=>{getRelayListForUsers(i,this.ndk,t,1e3,o).then(e=>{this.debug(`Received relay lists for ${e.size} pubkeys out of ${i.length} requested`);for(const[t,n]of e){let e=this.data.get(t);if(e??=new OutboxItem("user"),n){if(e.readRelays=new Set(normalize(n.readRelayUrls)),e.writeRelays=new Set(normalize(n.writeRelayUrls)),this.ndk.relayConnectionFilter){for(const t of e.readRelays)this.ndk.relayConnectionFilter(t)||e.readRelays.delete(t);for(const t of e.writeRelays)this.ndk.relayConnectionFilter(t)||e.writeRelays.delete(t)}this.data.set(t,e),this.emit("user:relay-list-updated",t,e),this.debug(`Adding ${e.readRelays.size} read relays and ${e.writeRelays.size} write relays for ${t}`,n?.rawEvent())}}}).finally(e)}))}return Promise.all(n)}track(e,t,n=!0){const s=getKeyFromItem(e);t??=getTypeFromItem(e);let r=this.data.get(s);return r||(r=new OutboxItem(t),e instanceof NDKUser&&this.trackUsers([e])),r}};function getKeyFromItem(e){return e instanceof NDKUser?e.pubkey:e}function getTypeFromItem(e){return e instanceof NDKUser?"user":"kind"}function correctRelaySet(e,t){const n=t.connectedRelays();if(!Array.from(e.relays).some(e=>n.map(e=>e.url).includes(e.url)))for(const t of n)e.addRelay(t);if(0===n.length)for(const n of t.relays.values())e.addRelay(n);return e}var NDKSubscriptionManager=class{subscriptions;seenEvents=new dist.LRUCache({maxSize:1e4,entryExpirationTimeInMS:3e5});constructor(){this.subscriptions=new Map}add(e){this.subscriptions.set(e.internalId,e),e.onStopped,e.onStopped=()=>{this.subscriptions.delete(e.internalId)},e.on("close",()=>{this.subscriptions.delete(e.internalId)})}seenEvent(e,t){const n=this.seenEvents.get(e)||[];n.some(e=>e.url===t.url)||n.push(t),this.seenEvents.set(e,n)}dispatchEvent(e,t,n=!1){t&&this.seenEvent(e.id,t);const s=this.subscriptions.values(),r=[];for(const t of s)matchFilters(t.filters,e)&&r.push(t);for(const s of r)s.eventReceived(e,t,!1,n)}},debug6=createDebug5("ndk:active-user");async function getUserRelayList(e){if(!this.autoConnectUserRelays)return;const t=await getRelayListForUser(e.pubkey,this);if(t){for(const e of t.relays){let t=this.pool.relays.get(e);t||(t=new NDKRelay(e,this.relayAuthDefaultPolicy,this),this.pool.addRelay(t))}return debug6("Connected to %d user relays",t.relays.length),t}}async function setActiveUser(e){if(!this.autoConnectUserRelays)return;const t=this.outboxPool||this.pool;t.connectedRelays.length>0?await getUserRelayList.call(this,e):t.once("connect",async()=>{await getUserRelayList.call(this,e)})}function getEntity(e){try{const t=nip19_exports$1.decode(e);return"npub"===t.type?npub(this,t.data):"nprofile"===t.type?nprofile(this,t.data):t}catch(e){return null}}function npub(e,t){return e.getUser({pubkey:t})}function nprofile(e,t){const n=e.getUser({pubkey:t.pubkey});return t.relays&&(n.relayUrls=t.relays),n}function isValidHint(e){if(!e||""===e)return!1;try{return new URL(e),!0}catch(e){return!1}}async function fetchEventFromTag(e,t,n,s={type:"timeout"}){const r=this.debug.extend("fetch-event-from-tag"),[i,o,a]=e;r("fetching event from tag",e,n={},s);const c=getRelaysForSync(this,t.pubkey);if(c&&c.size>0){r("fetching event from author relays %o",Array.from(c));const e=NDKRelaySet.fromRelayUrls(Array.from(c),this),t=await this.fetchEvent(o,n,e);if(t)return t}else r("no author relays found for %s",t.pubkey,t);const l=calculateRelaySetsFromFilters(this,[{ids:[o]}],this.pool);r("fetching event without relay hint",l);const u=await this.fetchEvent(o,n);if(u)return u;if(a&&""!==a){const e=await this.fetchEvent(o,n,this.pool.getRelay(a,!0,!0,[{ids:[o]}]));if(e)return e}let d;const h=isValidHint(a)?this.pool.getRelay(a,!1,!0,[{ids:[o]}]):void 0,p=new Promise(e=>{this.fetchEvent(o,n,h).then(e)});if(!isValidHint(a)||"none"===s.type)return p;const f=new Promise(async e=>{const t=s.relaySet,i=s.timeout??1500,a=new Promise(e=>setTimeout(e,i));if("timeout"===s.type&&await a,d)e(d);else{r("fallback fetch triggered");e(await this.fetchEvent(o,n,t))}});switch(s.type){case"timeout":return Promise.race([p,f]);case"eose":return d=await p,d||f}}var Queue=class{queue=[];maxConcurrency;processing=new Set;promises=new Map;constructor(e,t){this.maxConcurrency=t}add(e){if(this.promises.has(e.id))return this.promises.get(e.id);const t=new Promise((t,n)=>{this.queue.push({...e,func:()=>e.func().then(e=>(t(e),e),e=>{throw n(e),e})}),this.process()});return this.promises.set(e.id,t),t.finally(()=>{this.promises.delete(e.id),this.processing.delete(e.id),this.process()}),t}process(){if(this.processing.size>=this.maxConcurrency||0===this.queue.length)return;const e=this.queue.shift();e&&!this.processing.has(e.id)&&(this.processing.add(e.id),e.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/"],NDK=class extends lib$1.EventEmitter{_explicitRelayUrls;pool;outboxPool;_signer;_activeUser;cacheAdapter;debug;devWriteRelaySet;outboxTracker;muteFilter;relayConnectionFilter;clientName;clientNip89;queuesZapConfig;queuesNip05;asyncSigVerification=!1;initialValidationRatio=1;lowestValidationRatio=.1;validationRatioFn;filterValidationMode="validate";subManager;aiGuardrails;_signatureVerificationFunction;_signatureVerificationWorker;signatureVerificationTimeMs=0;publishingFailureHandled=!1;pools=[];relayAuthDefaultPolicy;httpFetch;netDebug;autoConnectUserRelays=!0;walletConfig;constructor(e={}){super(),this.debug=e.debug||createDebug5("ndk"),this.netDebug=e.netDebug,this._explicitRelayUrls=e.explicitRelayUrls||[],this.subManager=new NDKSubscriptionManager,this.pool=new NDKPool(e.explicitRelayUrls||[],this),this.pool.name="Main",this.pool.on("relay:auth",async(e,t)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(e,t)}),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,!1!==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.outboxTracker.on("user:relay-list-updated",(e,t)=>{this.debug(`Outbox relay list updated for ${e}`);for(const t of this.subManager.subscriptions.values()){t.filters.some(t=>t.authors?.includes(e))&&"function"==typeof t.refreshRelayConnections&&(this.debug(`Refreshing relay connections for subscription ${t.internalId}`),t.refreshRelayConnections())}})),this.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.muteFilter=e.muteFilter,this.relayConnectionFilter=e.relayConnectionFilter,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.validationRatioFn=e.validationRatioFn||this.defaultValidationRatioFn,this.filterValidationMode=e.filterValidationMode||"validate",this.aiGuardrails=new AIGuardrails(e.aiGuardrails||!1),this.aiGuardrails.ndkInstantiated(this);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,n=!0){let s;return s="string"==typeof e?new NDKRelay(e,t,this):e,this.pool.addRelay(s,n),this.explicitRelayUrls?.push(s.url),s}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){const t=this._activeUser?.pubkey!==e?.pubkey;this._activeUser=e,t&&this.emit("activeUser:change",e),e&&t&&setActiveUser.call(this,e)}get signer(){return this._signer}set signer(e){this._signer=e,e&&this.emit("signer:ready",e),e?.user().then(e=>{e.ndk=this,this.activeUser=e})}async connect(e){if(this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer %o",await(this._signer.relays?.(this))),this._signer.relays)){(await this._signer.relays(this)).forEach(e=>this.pool.addRelay(e))}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)}defaultValidationRatioFn(e,t,n){if(t<10)return this.initialValidationRatio;const s=Math.min(t/100,1),r=this.initialValidationRatio*(1-s)+this.lowestValidationRatio*s;return Math.max(r,this.lowestValidationRatio)}getUser(e){if("string"==typeof e){if(e.startsWith("npub1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("npub"!==t)throw new Error(`Invalid npub: ${e}`);return this.getUser({pubkey:n})}if(e.startsWith("nprofile1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nprofile"!==t)throw new Error(`Invalid nprofile: ${e}`);return this.getUser({pubkey:n.pubkey,relayUrls:n.relays})}return this.getUser({pubkey:e})}const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}async fetchUser(e,t=!1){if(e.includes("@")||e.includes(".")&&!e.startsWith("n"))return NDKUser.fromNip05(e,this,t);if(e.startsWith("npub1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("npub"!==t)throw new Error(`Invalid npub: ${e}`);const s=new NDKUser({pubkey:n});return s.ndk=this,s}if(e.startsWith("nprofile1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nprofile"!==t)throw new Error(`Invalid nprofile: ${e}`);const s=new NDKUser({pubkey:n.pubkey,relayUrls:n.relays});return s.ndk=this,s}{const t=new NDKUser({pubkey:e});return t.ndk=this,t}}subscribe(e,t,n=!0,s=!0){let r,i=t?.relaySet,o=s;n instanceof NDKRelaySet?(console.warn("relaySet is deprecated, use opts.relaySet instead. This will be removed in version v2.14.0"),i=n,o=s):"boolean"!=typeof n&&"object"!=typeof n||(o=n);const a={relaySet:i,...t};o&&"object"==typeof o&&(o.onEvent&&(a.onEvent=o.onEvent),o.onEose&&(a.onEose=o.onEose),o.onClose&&(a.onClose=o.onClose),o.onEvents&&(r=o.onEvents));const c=new NDKSubscription(this,e,a);this.subManager.add(c);const l=c.pool;if(c.relaySet)for(const e of c.relaySet.relays)l.useTemporaryRelay(e,void 0,c.filters);if(this.outboxPool&&c.hasAuthorsFilter()){const e=c.filters.filter(e=>e.authors&&e.authors?.length>0).flatMap(e=>e.authors);this.outboxTracker?.trackUsers(e)}return o&&setTimeout(()=>{const e=c.start(!r);e&&e.length>0&&r&&r(e)},0),c}fetchEventFromTag=fetchEventFromTag.bind(this);fetchEventSync(e){if(!this.cacheAdapter)throw new Error("Cache adapter not set");let t;t="string"==typeof e?[filterFromId(e)]:e;const n=new NDKSubscription(this,t),s=this.cacheAdapter.query(n);if(s instanceof Promise)throw new Error("Cache adapter is async");return s.map(e=>(e.ndk=this,e))}async fetchEvent(e,t,n){let s,r;if(n instanceof NDKRelay?r=new NDKRelaySet(new Set([n]),this):n instanceof NDKRelaySet&&(r=n),!n&&"string"==typeof e&&!isNip33AValue(e)){const t=relaysFromBech32(e,this);t.length>0&&(r=new NDKRelaySet(new Set(t),this),r=correctRelaySet(r,this.pool))}if(s="string"==typeof e?[filterFromId(e)]:Array.isArray(e)?e:[e],"string"!=typeof e&&this.aiGuardrails?.ndk?.fetchingEvents(s),0===s.length)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise((e,n)=>{let i=null;const o={...t||{},closeOnEose:!0};r&&(o.relaySet=r);const a=setTimeout(()=>{c.stop(),this.aiGuardrails._nextCallDisabled=null,e(i)},1e4),c=this.subscribe(s,o,{onEvent:t=>{t.ndk=this,t.isReplaceable()?(!i||i.created_at<t.created_at)&&(i=t):(clearTimeout(a),this.aiGuardrails._nextCallDisabled=null,e(t))},onEose:()=>{clearTimeout(a),this.aiGuardrails._nextCallDisabled=null,e(i)}})})}async fetchEvents(e,t,n){return this.aiGuardrails?.ndk?.fetchingEvents(e,t),new Promise(s=>{const r=new Map,i={...t||{},closeOnEose:!0};n&&(i.relaySet=n);this.subscribe(e,{...i,onEvent:e=>{let t;t=e instanceof NDKEvent?e:new NDKEvent(void 0,e);const n=t.deduplicationKey(),s=r.get(n);s&&(t=dedup(s,t)),t.ndk=this,r.set(n,t)},onEose:()=>{this.aiGuardrails._nextCallDisabled=null,s(new Set(r.values()))}})})}assertSigner(){if(!this.signer)throw this.emit("signer:required"),new Error("Signer required")}getEntity=getEntity.bind(this);guardrailOff(e){return this.aiGuardrails._nextCallDisabled=e?"string"==typeof e?new Set([e]):new Set(e):"all",this}set wallet(e){e?(this.walletConfig??={},this.walletConfig.lnPay=e?.lnPay?.bind(e),this.walletConfig.cashuPay=e?.cashuPay?.bind(e)):this.walletConfig=void 0}},nip19_exports={};__reExport(nip19_exports,nip19_star);var nip49_exports={};function disconnect(e,t){return t??=createDebug5("ndk:relay:auth-policies:disconnect"),async n=>{t?.(`Relay ${n.url} requested authentication, disconnecting`),e.removeRelay(n.url)}}async function signAndAuth(e,t,n,s,r,i){try{await e.sign(n),r(e)}catch(n){s?.(`Failed to publish auth event to relay ${t.url}`,n),i(e)}}function signIn({ndk:e,signer:t,debug:n}={}){return n??=createDebug5("ndk:auth-policies:signIn"),async(s,r)=>{n?.(`Relay ${s.url} requested authentication, signing in`);const i=new NDKEvent(e);return i.kind=22242,i.tags=[["relay",s.url],["challenge",r]],t??=e?.signer,new Promise(async(r,o)=>{t?await signAndAuth(i,s,t,n,r,o):e?.once("signer:ready",async e=>{await signAndAuth(i,s,e,n,r,o)})})}}__reExport(nip49_exports,nip49_star);var NDKRelayAuthPolicies={disconnect:disconnect,signIn:signIn};async function ndkSignerFromPayload(e,t){let n;try{n=JSON.parse(e)}catch(t){return void console.error("Failed to parse signer payload string",e,t)}if(!n||"string"!=typeof n.type)return void console.error("Failed to parse signer payload string",e,new Error("Missing type field"));const s=signerRegistry.get(n.type);if(!s)throw new Error(`Unknown signer type: ${n.type}`);try{return await s.fromPayload(e,t)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to deserialize signer type ${n.type}: ${t}`)}}var NDKNip07Signer=class e{_userPromise;encryptionQueue=[];encryptionProcessing=!1;debug;waitTimeout;_pubkey;ndk;_user;constructor(e=1e3,t){this.debug=createDebug5("ndk:nip07"),this.waitTimeout=e,this.ndk=t}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}async blockUntilReady(){await this.waitForExtension();const e=await(window.nostr?.getPublicKey());if(!e)throw new Error("User rejected access");let t;return this._pubkey=e,t=this.ndk?this.ndk.getUser({pubkey:e}):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){await this.waitForExtension();const t=await(window.nostr?.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){await this.waitForExtension();const t=await(window.nostr?.getRelays?.())||{},n=[];for(const e of Object.keys(t))t[e].read&&t[e].write&&n.push(e);return n.map(t=>new NDKRelay(t,e?.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){const t=[];return e&&"nip04"!==e||!Boolean(window.nostr?.nip04)||t.push("nip04"),e&&"nip44"!==e||!Boolean(window.nostr?.nip44)||t.push("nip44"),t}async encrypt(e,t,n="nip04"){if(!await this.encryptionEnabled(n))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(n,"encrypt",s,t)}async decrypt(e,t,n="nip04"){if(!await this.encryptionEnabled(n))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(n,"decrypt",s,t)}async queueEncryption(e,t,n,s){return new Promise((r,i)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:n,value:s,resolve:r,reject:i}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){if(!e&&0===this.encryptionQueue.length)return void(this.encryptionProcessing=!1);this.encryptionProcessing=!0;const n=e||this.encryptionQueue.shift();if(!n)return void(this.encryptionProcessing=!1);const{scheme:s,method:r,counterpartyHexpubkey:i,value:o,resolve:a,reject:c}=n;this.debug("Processing encryption queue item",{method:r,counterpartyHexpubkey:i,value:o});try{const e=await(window.nostr?.[s]?.[r](i,o));if(!e)throw new Error("Failed to encrypt/decrypt");a(e)}catch(e){const s=e instanceof Error?e.message:String(e);if(s.includes("call already executing")&&t<5)return this.debug("Retrying encryption queue item",{method:r,counterpartyHexpubkey:i,value:o,retries:t}),void setTimeout(()=>{this.processEncryptionQueue(n,t+1)},50*t);c(e instanceof Error?e:new Error(s))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr)return void e();let n;const s=setInterval(()=>{window.nostr&&(clearTimeout(n),clearInterval(s),e())},100);n=setTimeout(()=>{clearInterval(s),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(t,n){const s=JSON.parse(t);if("nip07"!==s.type)throw new Error(`Invalid payload type: expected 'nip07', got ${s.type}`);return new e(void 0,n)}};registerSigner("nip07",NDKNip07Signer);var NDKNostrRpc=class extends lib$1.EventEmitter{ndk;signer;relaySet;debug;encryptionType="nip04";pool;constructor(e,t,n,s){if(super(),this.ndk=e,this.signer=t,s){this.pool=new NDKPool(s,e,{debug:n.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new NDKRelaySet(new Set,e,this.pool);for(const r of s){const s=this.pool.getRelay(r,!1,!1);s.authPolicy=NDKRelayAuthPolicies.signIn({ndk:e,signer:t,debug:n}),this.relaySet.addRelay(s),s.connect()}}this.debug=n.extend("rpc")}subscribe(e){return new Promise(t=>{const n=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1,cacheUsage:"ONLY_RELAY",pool:this.pool,relaySet:this.relaySet,onEvent:async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):(this.emit(`response-${t.id}`,t),this.emit("response",t))}catch(t){this.debug("error parsing event",t,e.rawEvent())}},onEose:()=>{this.debug("eosed"),t(n)}})})}async parseEvent(e){"nip44"===this.encryptionType&&e.content.includes("?iv=")?this.encryptionType="nip04":"nip04"!==this.encryptionType||e.content.includes("?iv=")||(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});let n;t.ndk=this.ndk;try{n=await this.signer.decrypt(t,e.content,this.encryptionType)}catch(s){const r="nip04"===this.encryptionType?"nip44":"nip04";n=await this.signer.decrypt(t,e.content,r),this.encryptionType=r}const s=JSON.parse(n),{id:r,method:i,params:o,result:a,error:c}=s;return i?{id:r,pubkey:e.pubkey,method:i,params:o,event:e}:{id:r,result:a,error:c,event:e}}async sendResponse(e,t,n,s=24133,r){const i={id:e,result:n};r&&(i.error=r);const o=await this.signer.user(),a=this.ndk.getUser({pubkey:t}),c=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(i),tags:[["p",t]],pubkey:o.pubkey});c.content=await this.signer.encrypt(a,c.content,this.encryptionType),await c.sign(this.signer),await c.publish(this.relaySet)}async sendRequest(e,t,n=[],s=24133,r){const i=Math.random().toString(36).substring(7),o=await this.signer.user(),a=this.ndk.getUser({pubkey:e}),c={id:i,method:t,params:n},l=new Promise(()=>{const e=t=>{"auth_url"===t.result?(this.once(`response-${i}`,e),this.emit("authUrl",t.error)):r&&r(t)};this.once(`response-${i}`,e)}),u=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(c),tags:[["p",e]],pubkey:o.pubkey});return u.content=await this.signer.encrypt(a,u.content,this.encryptionType),await u.sign(this.signer),await u.publish(this.relaySet),l}};function nostrConnectGenerateSecret(){return Math.random().toString(36).substring(2,15)}function generateNostrConnectUri(e,t,n,s){const r=s?.name?encodeURIComponent(s.name):"",i=s?.url?encodeURIComponent(s.url):"";let o=`nostrconnect://${e}?image=${s?.image?encodeURIComponent(s.image):""}&url=${i}&name=${r}&perms=${s?.perms?encodeURIComponent(s.perms):""}&secret=${encodeURIComponent(t)}`;return n&&(o+=`&relay=${encodeURIComponent(n)}`),o}var NDKNip46Signer=class e extends lib$1.EventEmitter{ndk;_user;bunkerPubkey;userPubkey;get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}secret;localSigner;nip05;rpc;debug;relayUrls;subscription;nostrConnectUri;nostrConnectSecret;constructor(e,t,n,s,r){super(),this.ndk=e,this.debug=e.debug.extend("nip46:signer"),this.relayUrls=s,this.localSigner=n?"string"==typeof n?new NDKPrivateKeySigner(n):n:NDKPrivateKeySigner.generate(),!1===t||(t?t.startsWith("bunker://")?this.bunkerFlowInit(t):this.nip05Init(t):this.nostrconnectFlowInit(r)),this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls)}static bunker(t,n,s){return new e(t,n,s)}static nostrconnect(t,n,s,r){return new e(t,void 0,s,[n],r)}nostrconnectFlowInit(e){this.nostrConnectSecret=nostrConnectGenerateSecret();const t=this.localSigner.pubkey;this.nostrConnectUri=generateNostrConnectUri(t,this.nostrConnectSecret,this.relayUrls?.[0],e)}bunkerFlowInit(e){const t=new URL(e),n=t.hostname||t.pathname.replace(/^\/\//,""),s=t.searchParams.get("pubkey"),r=t.searchParams.getAll("relay"),i=t.searchParams.get("secret");this.bunkerPubkey=n,this.userPubkey=s,this.relayUrls=r,this.secret=i}nip05Init(e){this.nip05=e}async startListening(){if(this.subscription)return;const e=await this.localSigner.user();if(!e)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[e.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((e,t)=>{const n=t=>{t.result===this.nostrConnectSecret&&(this._user=t.event.author,this.userPubkey=t.event.pubkey,this.bunkerPubkey=t.event.pubkey,this.rpc.off("response",n),e(this._user))};this.startListening(),this.rpc.on("response",n)})}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 e=await NDKUser.fromNip05(this.nip05,this.ndk);e&&(this._user=e,this.userPubkey=e.pubkey,this.relayUrls=e.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",(...e)=>{this.emit("authUrl",...e)}),new Promise((e,t)=>{const n=[this.userPubkey??""];if(this.secret&&n.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",n,24133,n=>{"ack"===n.result?this.getPublicKey().then(t=>{this.userPubkey=t,this._user=this.ndk.getUser({pubkey:t}),e(this._user)}):t(n.error)})})}stop(){this.subscription?.stop(),this.subscription=void 0}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,t=>{e(t.result)})})}async encryptionEnabled(e){return e?[e]:Promise.resolve(["nip04","nip44"])}async encrypt(e,t,n="nip04"){return this.encryption(e,t,n,"encrypt")}async decrypt(e,t,n="nip04"){return this.encryption(e,t,n,"decrypt")}async encryption(e,t,n,s){return new Promise((r,i)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${n}_${s}`,[e.pubkey,t],24133,e=>{e.error?i(e.error):r(e.result)})})}async sign(e){return new Promise((t,n)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(e)],24133,e=>{if(e.error)n(e.error);else{const n=JSON.parse(e.result);t(n.sig)}})})}async createAccount(e,t,n){await this.startListening();const s=[];return e&&s.push(e),t&&s.push(t),n&&s.push(n),new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",s,24133,n=>{if(n.error)t(n.error);else{const t=n.result;e(t)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const e={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(e)}static async fromPayload(t,n){if(!n)throw new Error("NDK instance is required to deserialize NIP-46 signer");const s=JSON.parse(t);if("nip46"!==s.type)throw new Error(`Invalid payload type: expected 'nip46', got ${s.type}`);const r=s.payload;if(!r||"object"!=typeof r||!r.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const i=await ndkSignerFromPayload(r.localSignerPayload,n);if(!i)throw new Error("Failed to deserialize local signer for NIP-46");if(!(i instanceof NDKPrivateKeySigner))throw new Error("Local signer must be an instance of NDKPrivateKeySigner");let o;return o=new e(n,!1,i,r.relayUrls),o.userPubkey=r.userPubkey,o.bunkerPubkey=r.bunkerPubkey,o.relayUrls=r.relayUrls,o.secret=r.secret,r.userPubkey&&(o._user=new NDKUser({pubkey:r.userPubkey}),o._user&&(o._user.ndk=n)),o}};registerSigner("nip46",NDKNip46Signer),createDebug5("ndk:zapper:ln"),createDebug5("ndk:zapper");const{window:window_1}=globals;function create_if_block$2(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b;function v(e,t){return"extension"===e[2]?create_if_block_3$2:create_else_block$2}let _=v(e),w=_(e),k=e[5]&&create_if_block_2$2(e),E=e[6]&&create_if_block_1$2(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=element("h2"),r.textContent="Login to Nostr",i=space(),o=element("button"),o.textContent="×",a=space(),c=element("div"),l=element("div"),u=element("button"),u.textContent="Extension",d=space(),h=element("button"),h.textContent="Nsec",p=space(),f=element("div"),w.c(),g=space(),k&&k.c(),y=space(),E&&E.c(),attr(r,"class","svelte-9yzcwg"),attr(o,"class","close-btn svelte-9yzcwg"),attr(s,"class","modal-header svelte-9yzcwg"),attr(u,"class","tab-btn svelte-9yzcwg"),toggle_class(u,"active","extension"===e[2]),attr(h,"class","tab-btn svelte-9yzcwg"),toggle_class(h,"active","nsec"===e[2]),attr(l,"class","tabs svelte-9yzcwg"),attr(f,"class","tab-content svelte-9yzcwg"),attr(c,"class","tab-container svelte-9yzcwg"),attr(n,"class","modal svelte-9yzcwg"),toggle_class(n,"dark-theme",e[1]),attr(t,"class","modal-overlay svelte-9yzcwg"),attr(t,"role","button"),attr(t,"tabindex","0")},m(v,_){insert(v,t,_),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),append(c,l),append(l,u),append(l,d),append(l,h),append(c,p),append(c,f),w.m(f,null),append(f,g),k&&k.m(f,null),append(f,y),E&&E.m(f,null),m||(b=[listen(o,"click",e[7]),listen(u,"click",e[14]),listen(h,"click",e[15]),listen(n,"click",stop_propagation(e[12])),listen(n,"keydown",stop_propagation(e[13])),listen(t,"click",e[7]),listen(t,"keydown",e[17])],m=!0)},p(e,t){4&t&&toggle_class(u,"active","extension"===e[2]),4&t&&toggle_class(h,"active","nsec"===e[2]),_===(_=v(e))&&w?w.p(e,t):(w.d(1),w=_(e),w&&(w.c(),w.m(f,g))),e[5]?k?k.p(e,t):(k=create_if_block_2$2(e),k.c(),k.m(f,y)):k&&(k.d(1),k=null),e[6]?E?E.p(e,t):(E=create_if_block_1$2(e),E.c(),E.m(f,null)):E&&(E.d(1),E=null),2&t&&toggle_class(n,"dark-theme",e[1])},d(e){e&&detach(t),w.d(),k&&k.d(),E&&E.d(),m=!1,run_all(b)}}}function create_else_block$2(e){let t,n,s,r,i,o,a,c,l,u,d=e[4]?"Logging in...":"Log in with nsec";return{c(){t=element("div"),n=element("p"),n.textContent="Enter your nsec (private key) to login. This will be stored securely in your browser.",s=space(),r=element("input"),i=space(),o=element("button"),a=text(d),attr(n,"class","svelte-9yzcwg"),attr(r,"type","password"),attr(r,"placeholder","nsec1..."),r.disabled=e[4],attr(r,"class","nsec-input svelte-9yzcwg"),attr(o,"class","login-nsec-btn svelte-9yzcwg"),o.disabled=c=e[4]||!e[3].trim(),attr(t,"class","nsec-login svelte-9yzcwg")},m(c,d){insert(c,t,d),append(t,n),append(t,s),append(t,r),set_input_value(r,e[3]),append(t,i),append(t,o),append(o,a),l||(u=[listen(r,"input",e[16]),listen(o,"click",e[10])],l=!0)},p(e,t){16&t&&(r.disabled=e[4]),8&t&&r.value!==e[3]&&set_input_value(r,e[3]),16&t&&d!==(d=e[4]?"Logging in...":"Log in with nsec")&&set_data(a,d),24&t&&c!==(c=e[4]||!e[3].trim())&&(o.disabled=c)},d(e){e&&detach(t),l=!1,run_all(u)}}}function create_if_block_3$2(e){let t,n,s,r,i,o,a,c=e[4]?"Connecting...":"Log in using extension";return{c(){t=element("div"),n=element("p"),n.textContent="Login using a NIP-07 compatible browser extension like nos2x or Alby.",s=space(),r=element("button"),i=text(c),attr(n,"class","svelte-9yzcwg"),attr(r,"class","login-extension-btn svelte-9yzcwg"),r.disabled=e[4],attr(t,"class","extension-login svelte-9yzcwg")},m(c,l){insert(c,t,l),append(t,n),append(t,s),append(t,r),append(r,i),o||(a=listen(r,"click",e[9]),o=!0)},p(e,t){16&t&&c!==(c=e[4]?"Connecting...":"Log in using extension")&&set_data(i,c),16&t&&(r.disabled=e[4])},d(e){e&&detach(t),o=!1,a()}}}function create_if_block_2$2(e){let t,n;return{c(){t=element("div"),n=text(e[5]),attr(t,"class","message error-message svelte-9yzcwg")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){32&t&&set_data(n,e[5])},d(e){e&&detach(t)}}}function create_if_block_1$2(e){let t,n;return{c(){t=element("div"),n=text(e[6]),attr(t,"class","message success-message svelte-9yzcwg")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){64&t&&set_data(n,e[6])},d(e){e&&detach(t)}}}function create_fragment$2(e){let t,n,s,r=e[0]&&create_if_block$2(e);return{c(){r&&r.c(),t=empty()},m(i,o){r&&r.m(i,o),insert(i,t,o),n||(s=listen(window_1,"keydown",e[11]),n=!0)},p(e,[n]){e[0]?r?r.p(e,n):(r=create_if_block$2(e),r.c(),r.m(t.parentNode,t)):r&&(r.d(1),r=null)},i:noop,o:noop,d(e){r&&r.d(e),e&&detach(t),n=!1,s()}}}function validateNsec(e){return!!e.startsWith("nsec1")&&!(e.length<60||e.length>70)}function instance$2(e,t,n){const s=createEventDispatcher();let{showModal:r=!1}=t,{isDarkTheme:i=!1}=t,o="extension",a="",c=!1,l="",u="";function d(){n(0,r=!1),n(3,a=""),n(5,l=""),n(6,u=""),s("close")}function h(e){n(2,o=e),n(5,l=""),n(6,u="")}async function p(){n(4,c=!0),n(5,l=""),n(6,u="");try{if(!a.trim())throw new Error("Please enter your nsec");if(!validateNsec(a.trim()))throw new Error('Invalid nsec format. Must start with "nsec1"');const e=new NDKPrivateKeySigner(a.trim()),t=await e.user().then(e=>e.pubkey);localStorage.setItem("nostr_auth_method","nsec"),localStorage.setItem("nostr_pubkey",t),localStorage.setItem("nostr_privkey",a.trim()),n(6,u="Successfully logged in with nsec!"),s("login",{method:"nsec",pubkey:t,privateKey:a.trim(),signer:e}),setTimeout(()=>{d()},1500)}catch(e){n(5,l=e.message)}finally{n(4,c=!1)}}return e.$$set=e=>{"showModal"in e&&n(0,r=e.showModal),"isDarkTheme"in e&&n(1,i=e.isDarkTheme)},[r,i,o,a,c,l,u,d,h,async function(){n(4,c=!0),n(5,l=""),n(6,u="");try{if(!window.nostr)throw new Error("No Nostr extension found. Please install a NIP-07 compatible extension like nos2x or Alby.");const e=await window.nostr.getPublicKey();e&&(localStorage.setItem("nostr_auth_method","extension"),localStorage.setItem("nostr_pubkey",e),n(6,u="Successfully logged in with extension!"),s("login",{method:"extension",pubkey:e,signer:window.nostr}),setTimeout(()=>{d()},1500))}catch(e){n(5,l=e.message)}finally{n(4,c=!1)}},p,function(e){"Escape"===e.key&&d(),"Enter"===e.key&&"nsec"===o&&p()},function(t){bubble.call(this,e,t)},function(t){bubble.call(this,e,t)},()=>h("extension"),()=>h("nsec"),function(){a=this.value,n(3,a)},e=>"Escape"===e.key&&d()]}class LoginModal extends SvelteComponent{constructor(e){super(),init(this,e,instance$2,create_fragment$2,safe_not_equal,{showModal:0,isDarkTheme:1})}}function get_each_context$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_1$1(e,t,n){const s=e.slice();return s[75]=t[n],s}function get_each_context_2$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_3$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_4$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_5$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_6$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function create_if_block_20$1(e){let t,n,s;return{c(){t=element("div"),n=text(e[3]),attr(t,"class",s="message "+e[4]+" svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,r){8&r[0]&&set_data(n,e[3]),16&r[0]&&s!==(s="message "+e[4]+" svelte-1smaj3x")&&attr(t,"class",s)},d(e){e&&detach(t)}}}function create_if_block_15$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A;function R(e,t){return e[5]&&e[5].length>0?create_if_block_18$1:create_else_block_7$1}let N=R(e),C=N(e);function I(e,t){return e[8]&&e[8].length>0?create_if_block_16$1:create_else_block_6$1}let B=I(e),P=B(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Banned Pubkeys",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Ban Pubkey"),h=space(),p=element("div"),C.c(),f=space(),g=element("div"),y=element("h3"),y.textContent="Allowed Pubkeys",m=space(),b=element("div"),v=element("input"),_=space(),w=element("input"),k=space(),E=element("button"),x=text("Allow Pubkey"),$=space(),S=element("div"),P.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","Pubkey (64 hex chars)"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(v,"type","text"),attr(v,"placeholder","Pubkey (64 hex chars)"),attr(v,"class","svelte-1smaj3x"),attr(w,"type","text"),attr(w,"placeholder","Reason (optional)"),attr(w,"class","svelte-1smaj3x"),E.disabled=e[2],attr(E,"class","svelte-1smaj3x"),attr(b,"class","add-form svelte-1smaj3x"),attr(S,"class","list svelte-1smaj3x"),attr(g,"class","section svelte-1smaj3x"),attr(t,"class","pubkeys-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[6]),append(i,a),append(i,c),set_input_value(c,e[7]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),C.m(p,null),append(t,f),append(t,g),append(g,y),append(g,m),append(g,b),append(b,v),set_input_value(v,e[9]),append(b,_),append(b,w),set_input_value(w,e[10]),append(b,k),append(b,E),append(E,x),append(g,$),append(g,S),P.m(S,null),T||(A=[listen(o,"input",e[43]),listen(c,"input",e[44]),listen(u,"click",e[25]),listen(v,"input",e[45]),listen(w,"input",e[46]),listen(E,"click",e[26])],T=!0)},p(e,t){64&t[0]&&o.value!==e[6]&&set_input_value(o,e[6]),128&t[0]&&c.value!==e[7]&&set_input_value(c,e[7]),4&t[0]&&(u.disabled=e[2]),N===(N=R(e))&&C?C.p(e,t):(C.d(1),C=N(e),C&&(C.c(),C.m(p,null))),512&t[0]&&v.value!==e[9]&&set_input_value(v,e[9]),1024&t[0]&&w.value!==e[10]&&set_input_value(w,e[10]),4&t[0]&&(E.disabled=e[2]),B===(B=I(e))&&P?P.p(e,t):(P.d(1),P=B(e),P&&(P.c(),P.m(S,null)))},d(e){e&&detach(t),C.d(),P.d(),T=!1,run_all(A)}}}function create_else_block_7$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No banned pubkeys configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_18$1(e){let t,n=e[5],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_6$1(get_each_context_6$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(32&r[0]){let i;for(n=e[5],i=0;i<n.length;i+=1){const o=get_each_context_6$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_6$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_19$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){32&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_6$1(e){let t,n,s,r,i,o=e[72].pubkey+"",a=e[72].reason&&create_if_block_19$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","pubkey svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){32&n[0]&&o!==(o=e[72].pubkey+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_19$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_else_block_6$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed pubkeys configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_16$1(e){let t,n=e[8],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_5$1(get_each_context_5$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(256&r[0]){let i;for(n=e[8],i=0;i<n.length;i+=1){const o=get_each_context_5$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_5$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_17$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){256&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_5$1(e){let t,n,s,r,i,o=e[72].pubkey+"",a=e[72].reason&&create_if_block_17$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","pubkey svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){256&n[0]&&o!==(o=e[72].pubkey+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_17$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_10$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A;function R(e,t){return e[11]&&e[11].length>0?create_if_block_13$1:create_else_block_5$1}let N=R(e),C=N(e);let I=function(e){return e[22]&&e[22].length>0?create_if_block_11$1:create_else_block_4$1}(e),B=I(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Banned Events",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Ban Event"),h=space(),p=element("div"),C.c(),f=space(),g=element("div"),y=element("h3"),y.textContent="Allowed Events",m=space(),b=element("div"),v=element("input"),_=space(),w=element("input"),k=space(),E=element("button"),x=text("Allow Event"),$=space(),S=element("div"),B.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","Event ID (64 hex chars)"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(v,"type","text"),attr(v,"placeholder","Event ID (64 hex chars)"),attr(v,"class","svelte-1smaj3x"),attr(w,"type","text"),attr(w,"placeholder","Reason (optional)"),attr(w,"class","svelte-1smaj3x"),E.disabled=e[2],attr(E,"class","svelte-1smaj3x"),attr(b,"class","add-form svelte-1smaj3x"),attr(S,"class","list svelte-1smaj3x"),attr(g,"class","section svelte-1smaj3x"),attr(t,"class","events-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[12]),append(i,a),append(i,c),set_input_value(c,e[13]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),C.m(p,null),append(t,f),append(t,g),append(g,y),append(g,m),append(g,b),append(b,v),set_input_value(v,e[14]),append(b,_),append(b,w),set_input_value(w,e[15]),append(b,k),append(b,E),append(E,x),append(g,$),append(g,S),B.m(S,null),T||(A=[listen(o,"input",e[47]),listen(c,"input",e[48]),listen(u,"click",e[27]),listen(v,"input",e[49]),listen(w,"input",e[50]),listen(E,"click",e[28])],T=!0)},p(e,t){4096&t[0]&&o.value!==e[12]&&set_input_value(o,e[12]),8192&t[0]&&c.value!==e[13]&&set_input_value(c,e[13]),4&t[0]&&(u.disabled=e[2]),N===(N=R(e))&&C?C.p(e,t):(C.d(1),C=N(e),C&&(C.c(),C.m(p,null))),16384&t[0]&&v.value!==e[14]&&set_input_value(v,e[14]),32768&t[0]&&w.value!==e[15]&&set_input_value(w,e[15]),4&t[0]&&(E.disabled=e[2]),B.p(e,t)},d(e){e&&detach(t),C.d(),B.d(),T=!1,run_all(A)}}}function create_else_block_5$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No banned events configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_13$1(e){let t,n=e[11],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_4$1(get_each_context_4$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(2048&r[0]){let i;for(n=e[11],i=0;i<n.length;i+=1){const o=get_each_context_4$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_4$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_14$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){2048&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_4$1(e){let t,n,s,r,i,o=e[72].id+"",a=e[72].reason&&create_if_block_14$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){2048&n[0]&&o!==(o=e[72].id+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_14$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_else_block_4$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed events configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_11$1(e){let t,n=e[22],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_3$1(get_each_context_3$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(4194304&r[0]){let i;for(n=e[22],i=0;i<n.length;i+=1){const o=get_each_context_3$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_3$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_12$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p:noop,d(e){e&&detach(t)}}}function create_each_block_3$1(e){let t,n,s,r,i,o=e[72].id+"",a=e[72].reason&&create_if_block_12$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,t){e[72].reason&&a.p(e,t)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_7$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g;function y(e,t){return e[16]&&e[16].length>0?create_if_block_8$1:create_else_block_3$1}let m=y(e),b=m(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Blocked IPs",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Block IP"),h=space(),p=element("div"),b.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","IP Address"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","ips-section")},m(y,m){insert(y,t,m),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[17]),append(i,a),append(i,c),set_input_value(c,e[18]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),b.m(p,null),f||(g=[listen(o,"input",e[51]),listen(c,"input",e[52]),listen(u,"click",e[29])],f=!0)},p(e,t){131072&t[0]&&o.value!==e[17]&&set_input_value(o,e[17]),262144&t[0]&&c.value!==e[18]&&set_input_value(c,e[18]),4&t[0]&&(u.disabled=e[2]),m===(m=y(e))&&b?b.p(e,t):(b.d(1),b=m(e),b&&(b.c(),b.m(p,null)))},d(e){e&&detach(t),b.d(),f=!1,run_all(g)}}}function create_else_block_3$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No blocked IPs configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_8$1(e){let t,n=e[16],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_2$1(get_each_context_2$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(65536&r[0]){let i;for(n=e[16],i=0;i<n.length;i+=1){const o=get_each_context_2$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_2$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_9$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){65536&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_2$1(e){let t,n,s,r,i,o=e[72].ip+"",a=e[72].reason&&create_if_block_9$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","ip svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){65536&n[0]&&o!==(o=e[72].ip+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_9$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_5$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p;function f(e,t){return e[19]&&e[19].length>0?create_if_block_6$1:create_else_block_2$1}let g=f(e),y=g(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Allowed Event Kinds",r=space(),i=element("div"),o=element("input"),a=space(),c=element("button"),l=text("Allow Kind"),u=space(),d=element("div"),y.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","number"),attr(o,"placeholder","Kind number"),attr(o,"class","svelte-1smaj3x"),c.disabled=e[2],attr(c,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(d,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","kinds-section")},m(f,g){insert(f,t,g),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[20]),append(i,a),append(i,c),append(c,l),append(n,u),append(n,d),y.m(d,null),h||(p=[listen(o,"input",e[53]),listen(c,"click",e[30])],h=!0)},p(e,t){1048576&t[0]&&to_number(o.value)!==e[20]&&set_input_value(o,e[20]),4&t[0]&&(c.disabled=e[2]),g===(g=f(e))&&y?y.p(e,t):(y.d(1),y=g(e),y&&(y.c(),y.m(d,null)))},d(e){e&&detach(t),y.d(),h=!1,run_all(p)}}}function create_else_block_2$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed kinds configured. All kinds are\n allowed by default.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_6$1(e){let t,n=e[19],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_1$1(get_each_context_1$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(524288&r[0]|1&r[1]){let i;for(n=e[19],i=0;i<n.length;i+=1){const o=get_each_context_1$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_1$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_each_block_1$1(e){let t,n,s,r,i,o,a,c,l,u=e[75]+"";function d(){return e[54](e[75])}return{c(){t=element("div"),n=element("span"),s=text("Kind "),r=text(u),i=space(),o=element("button"),o.textContent="Remove",a=space(),attr(n,"class","kind svelte-1smaj3x"),attr(o,"class","remove-btn svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,u){insert(e,t,u),append(t,n),append(n,s),append(n,r),append(t,i),append(t,o),append(t,a),c||(l=listen(o,"click",d),c=!0)},p(t,n){e=t,524288&n[0]&&u!==(u=e[75]+"")&&set_data(r,u)},d(e){e&&detach(t),c=!1,l()}}}function create_if_block_2$1(e){let t,n,s,r,i,o,a,c,l,u;function d(e,t){return e[21]&&e[21].length>0?create_if_block_3$1:create_else_block_1$1}let h=d(e),p=h(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Events Needing Moderation",r=space(),i=element("button"),o=text("Refresh"),a=space(),c=element("div"),p.c(),attr(s,"class","svelte-1smaj3x"),i.disabled=e[2],attr(c,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","moderation-section")},m(d,h){insert(d,t,h),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(n,a),append(n,c),p.m(c,null),l||(u=listen(i,"click",e[24]),l=!0)},p(e,t){4&t[0]&&(i.disabled=e[2]),h===(h=d(e))&&p?p.p(e,t):(p.d(1),p=h(e),p&&(p.c(),p.m(c,null)))},d(e){e&&detach(t),p.d(),l=!1,u()}}}function create_else_block_1$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No events need moderation at this time.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_3$1(e){let t,n=e[21],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block$1(get_each_context$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(2097152&r[0]|12&r[1]){let i;for(n=e[21],i=0;i<n.length;i+=1){const o=get_each_context$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_4$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){2097152&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p=e[72].id+"",f=e[72].reason&&create_if_block_4$1(e);function g(){return e[55](e[72])}function y(){return e[56](e[72])}return{c(){t=element("div"),n=element("span"),s=text(p),r=space(),f&&f.c(),i=space(),o=element("div"),a=element("button"),a.textContent="Allow",c=space(),l=element("button"),l.textContent="Ban",u=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(a,"class","svelte-1smaj3x"),attr(l,"class","svelte-1smaj3x"),attr(o,"class","actions svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,p){insert(e,t,p),append(t,n),append(n,s),append(t,r),f&&f.m(t,null),append(t,i),append(t,o),append(o,a),append(o,c),append(o,l),append(t,u),d||(h=[listen(a,"click",g),listen(l,"click",y)],d=!0)},p(n,r){e=n,2097152&r[0]&&p!==(p=e[72].id+"")&&set_data(s,p),e[72].reason?f?f.p(e,r):(f=create_if_block_4$1(e),f.c(),f.m(t,i)):f&&(f.d(1),f=null)},d(e){e&&detach(t),f&&f.d(),d=!1,run_all(h)}}}function create_if_block$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A;function R(e,t){return e[2]?create_if_block_1$1:create_else_block$1}let N=R(e),C=N(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Relay Configuration",r=space(),i=element("div"),o=element("button"),a=text("🔄 Refresh from Relay Info"),c=space(),l=element("div"),u=element("div"),d=element("label"),d.textContent="Relay Name",h=space(),p=element("input"),f=space(),g=element("div"),y=element("label"),y.textContent="Relay Description",m=space(),b=element("textarea"),v=space(),_=element("div"),w=element("label"),w.textContent="Relay Icon URL",k=space(),E=element("input"),x=space(),$=element("div"),S=element("button"),C.c(),attr(s,"class","svelte-1smaj3x"),o.disabled=e[2],attr(o,"class","refresh-btn svelte-1smaj3x"),attr(i,"class","config-actions svelte-1smaj3x"),attr(d,"class","svelte-1smaj3x"),attr(p,"type","text"),attr(p,"placeholder","Enter relay name"),attr(p,"class","svelte-1smaj3x"),attr(u,"class","form-group svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(b,"placeholder","Enter relay description"),attr(b,"class","svelte-1smaj3x"),attr(g,"class","form-group svelte-1smaj3x"),attr(w,"class","svelte-1smaj3x"),attr(E,"type","url"),attr(E,"placeholder","Enter icon URL"),attr(E,"class","svelte-1smaj3x"),attr(_,"class","form-group svelte-1smaj3x"),S.disabled=e[2],attr(S,"class","update-all-btn svelte-1smaj3x"),attr($,"class","config-update-section svelte-1smaj3x"),attr(l,"class","config-form svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","relay-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(n,c),append(n,l),append(l,u),append(u,d),append(u,h),append(u,p),set_input_value(p,e[0].relay_name),append(l,f),append(l,g),append(g,y),append(g,m),append(g,b),set_input_value(b,e[0].relay_description),append(l,v),append(l,_),append(_,w),append(_,k),append(_,E),set_input_value(E,e[0].relay_icon),append(l,x),append(l,$),append($,S),C.m(S,null),T||(A=[listen(o,"click",e[23]),listen(p,"input",e[57]),listen(b,"input",e[58]),listen(E,"input",e[59]),listen(S,"click",e[32])],T=!0)},p(e,t){4&t[0]&&(o.disabled=e[2]),1&t[0]&&p.value!==e[0].relay_name&&set_input_value(p,e[0].relay_name),1&t[0]&&set_input_value(b,e[0].relay_description),1&t[0]&&E.value!==e[0].relay_icon&&set_input_value(E,e[0].relay_icon),N!==(N=R(e))&&(C.d(1),C=N(e),C&&(C.c(),C.m(S,null))),4&t[0]&&(S.disabled=e[2])},d(e){e&&detach(t),C.d(),T=!1,run_all(A)}}}function create_else_block$1(e){let t;return{c(){t=text("💾 Update Configuration")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_1$1(e){let t;return{c(){t=text("⏳ Updating...")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_fragment$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A,R,N,C,I,B,P,D,L,F,O=e[3]&&create_if_block_20$1(e),U="pubkeys"===e[1]&&create_if_block_15$1(e),M="events"===e[1]&&create_if_block_10$1(e),K="ips"===e[1]&&create_if_block_7$1(e),H="kinds"===e[1]&&create_if_block_5$1(e),j="moderation"===e[1]&&create_if_block_2$1(e),V="relay"===e[1]&&create_if_block$1(e);return{c(){t=element("div"),n=element("div"),n.innerHTML='<h2 class="svelte-1smaj3x">Managed ACL Configuration</h2> \n <p class="svelte-1smaj3x">Configure access control using NIP-86 management API</p> \n <div class="owner-only-notice svelte-1smaj3x"><strong>Owner Only:</strong> This interface is restricted to relay owners\n only.</div>',s=space(),O&&O.c(),r=space(),i=element("div"),o=element("button"),a=text("Pubkeys"),l=space(),u=element("button"),d=text("Events"),p=space(),f=element("button"),g=text("IPs"),m=space(),b=element("button"),v=text("Kinds"),w=space(),k=element("button"),E=text("Moderation"),$=space(),S=element("button"),T=text("Relay Config"),R=space(),N=element("div"),U&&U.c(),C=space(),M&&M.c(),I=space(),K&&K.c(),B=space(),H&&H.c(),P=space(),j&&j.c(),D=space(),V&&V.c(),attr(n,"class","header svelte-1smaj3x"),attr(o,"class",c="tab "+("pubkeys"===e[1]?"active":"")+" svelte-1smaj3x"),attr(u,"class",h="tab "+("events"===e[1]?"active":"")+" svelte-1smaj3x"),attr(f,"class",y="tab "+("ips"===e[1]?"active":"")+" svelte-1smaj3x"),attr(b,"class",_="tab "+("kinds"===e[1]?"active":"")+" svelte-1smaj3x"),attr(k,"class",x="tab "+("moderation"===e[1]?"active":"")+" svelte-1smaj3x"),attr(S,"class",A="tab "+("relay"===e[1]?"active":"")+" svelte-1smaj3x"),attr(i,"class","tabs svelte-1smaj3x"),attr(N,"class","tab-content svelte-1smaj3x")},m(c,h){insert(c,t,h),append(t,n),append(t,s),O&&O.m(t,null),append(t,r),append(t,i),append(i,o),append(o,a),append(i,l),append(i,u),append(u,d),append(i,p),append(i,f),append(f,g),append(i,m),append(i,b),append(b,v),append(i,w),append(i,k),append(k,E),append(i,$),append(i,S),append(S,T),append(t,R),append(t,N),U&&U.m(N,null),append(N,C),M&&M.m(N,null),append(N,I),K&&K.m(N,null),append(N,B),H&&H.m(N,null),append(N,P),j&&j.m(N,null),append(N,D),V&&V.m(N,null),L||(F=[listen(o,"click",e[37]),listen(u,"click",e[38]),listen(f,"click",e[39]),listen(b,"click",e[40]),listen(k,"click",e[41]),listen(S,"click",e[42])],L=!0)},p(e,n){e[3]?O?O.p(e,n):(O=create_if_block_20$1(e),O.c(),O.m(t,r)):O&&(O.d(1),O=null),2&n[0]&&c!==(c="tab "+("pubkeys"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(o,"class",c),2&n[0]&&h!==(h="tab "+("events"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(u,"class",h),2&n[0]&&y!==(y="tab "+("ips"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(f,"class",y),2&n[0]&&_!==(_="tab "+("kinds"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(b,"class",_),2&n[0]&&x!==(x="tab "+("moderation"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(k,"class",x),2&n[0]&&A!==(A="tab "+("relay"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(S,"class",A),"pubkeys"===e[1]?U?U.p(e,n):(U=create_if_block_15$1(e),U.c(),U.m(N,C)):U&&(U.d(1),U=null),"events"===e[1]?M?M.p(e,n):(M=create_if_block_10$1(e),M.c(),M.m(N,I)):M&&(M.d(1),M=null),"ips"===e[1]?K?K.p(e,n):(K=create_if_block_7$1(e),K.c(),K.m(N,B)):K&&(K.d(1),K=null),"kinds"===e[1]?H?H.p(e,n):(H=create_if_block_5$1(e),H.c(),H.m(N,P)):H&&(H.d(1),H=null),"moderation"===e[1]?j?j.p(e,n):(j=create_if_block_2$1(e),j.c(),j.m(N,D)):j&&(j.d(1),j=null),"relay"===e[1]?V?V.p(e,n):(V=create_if_block$1(e),V.c(),V.m(N,null)):V&&(V.d(1),V=null)},i:noop,o:noop,d(e){e&&detach(t),O&&O.d(),U&&U.d(),M&&M.d(),K&&K.d(),H&&H.d(),j&&j.d(),V&&V.d(),L=!1,run_all(F)}}}function instance$1(e,t,n){let{userSigner:s}=t,{userPubkey:r}=t,i="pubkeys",o=!1,a="",c="info",l=[],u="",d="",h=[],p="",f="",g=[],y="",m="",b="",v="",_=[],w="",k="",E=[],x="",$=[],S={relay_name:"",relay_description:"",relay_icon:""};async function T(){try{n(2,o=!0),console.log("Fetching relay info from /");const e=await fetch(window.location.origin+"/",{headers:{Accept:"application/nostr+json"}});if(console.log("Response status:",e.status),console.log("Response headers:",e.headers),e.ok){const t=await e.json();console.log("Raw relay info:",t),n(0,S={relay_name:t.name||"",relay_description:t.description||"",relay_icon:t.icon||""}),console.log("Updated relayConfig:",S),console.log("Loaded relay info:",t),n(3,a="Relay configuration loaded successfully"),n(4,c="success")}else console.error("Failed to fetch relay info, status:",e.status),n(3,a=`Failed to fetch relay info: ${e.status}`),n(4,c="error")}catch(e){console.error("Failed to fetch relay info:",e),n(3,a=`Failed to fetch relay info: ${e.message}`),n(4,c="error")}finally{n(2,o=!1)}}async function A(e,t=[]){try{n(2,o=!0),n(3,a="");const i={method:e,params:t},c=await async function(e,t){if(!s)throw new Error("No signer available for authentication. Please log in with a Nostr extension.");if(!r)throw new Error("No user pubkey available for authentication.");const n=window.location.origin+t,i={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",n],["method",e]],content:"",pubkey:r},o=await s.signEvent(i),a=JSON.stringify(o);return`Nostr ${btoa(a)}`}("POST","/api/nip86"),l=await fetch("/api/nip86",{method:"POST",headers:{"Content-Type":"application/nostr+json+rpc",Authorization:c},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);const u=await l.json();if(u.error)throw new Error(u.error);return u.result}catch(e){throw console.error("NIP-86 API error:",e),n(3,a=e.message),n(4,c="error"),e}finally{n(2,o=!1)}}async function R(){try{n(5,l=await A("listbannedpubkeys"))}catch(e){console.error("Failed to load banned pubkeys:",e)}}async function N(){try{n(8,h=await A("listallowedpubkeys"))}catch(e){console.error("Failed to load allowed pubkeys:",e)}}async function C(){try{n(11,g=await A("listbannedevents"))}catch(e){console.error("Failed to load banned events:",e)}}async function I(){try{n(16,_=await A("listblockedips"))}catch(e){console.error("Failed to load blocked IPs:",e)}}async function B(){try{n(19,E=await A("listallowedkinds"))}catch(e){console.error("Failed to load allowed kinds:",e)}}async function P(){try{n(2,o=!0),n(21,$=await A("listeventsneedingmoderation")),console.log("Loaded events needing moderation:",$)}catch(e){console.error("Failed to load events needing moderation:",e),n(3,a=`Failed to load moderation events: ${e.message}`),n(4,c="error"),n(21,$=[])}finally{n(2,o=!1)}}async function D(e){try{await A("disallowkind",[e]),n(3,a="Kind disallowed successfully"),n(4,c="success"),await B()}catch(e){console.error("Failed to disallow kind:",e)}}async function L(e){try{await A("allowevent",[e,"Approved from moderation queue"]),n(3,a="Event allowed successfully"),n(4,c="success"),await P()}catch(e){console.error("Failed to allow event from moderation:",e)}}async function F(e){try{await A("banevent",[e,"Banned from moderation queue"]),n(3,a="Event banned successfully"),n(4,c="success"),await P()}catch(e){console.error("Failed to ban event from moderation:",e)}}onMount(()=>{setTimeout(()=>{T()},100)}),async function(){await Promise.all([R(),N(),C(),I(),B()])}();return e.$$set=e=>{"userSigner"in e&&n(35,s=e.userSigner),"userPubkey"in e&&n(36,r=e.userPubkey)},e.$$.update=()=>{1&e.$$.dirty[0]&&console.log("relayConfig changed:",S)},[S,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,[],T,P,async function(){if(u)try{await A("banpubkey",[u,d]),n(3,a="Pubkey banned successfully"),n(4,c="success"),n(6,u=""),n(7,d=""),await R()}catch(e){console.error("Failed to ban pubkey:",e)}},async function(){if(p)try{await A("allowpubkey",[p,f]),n(3,a="Pubkey allowed successfully"),n(4,c="success"),n(9,p=""),n(10,f=""),await N()}catch(e){console.error("Failed to allow pubkey:",e)}},async function(){if(y)try{await A("banevent",[y,m]),n(3,a="Event banned successfully"),n(4,c="success"),n(12,y=""),n(13,m=""),await C()}catch(e){console.error("Failed to ban event:",e)}},async function(){if(b)try{await A("allowevent",[b,v]),n(3,a="Event allowed successfully"),n(4,c="success"),n(14,b=""),n(15,v="")}catch(e){console.error("Failed to allow event:",e)}},async function(){if(w)try{await A("blockip",[w,k]),n(3,a="IP blocked successfully"),n(4,c="success"),n(17,w=""),n(18,k=""),await I()}catch(e){console.error("Failed to block IP:",e)}},async function(){if(!x)return;const e=parseInt(x);if(isNaN(e))return n(3,a="Invalid kind number"),void n(4,c="error");try{await A("allowkind",[e]),n(3,a="Kind allowed successfully"),n(4,c="success"),n(20,x=""),await B()}catch(e){console.error("Failed to allow kind:",e)}},D,async function(){try{n(2,o=!0),n(3,a="");const e=[];if(S.relay_name&&e.push(A("changerelayname",[S.relay_name])),S.relay_description&&e.push(A("changerelaydescription",[S.relay_description])),S.relay_icon&&e.push(A("changerelayicon",[S.relay_icon])),0===e.length)return n(3,a="No changes to update"),void n(4,c="info");await Promise.all(e),n(3,a="Relay configuration updated successfully"),n(4,c="success"),await T()}catch(e){console.error("Failed to update relay configuration:",e),n(3,a=`Failed to update relay configuration: ${e.message}`),n(4,c="error")}finally{n(2,o=!1)}},L,F,s,r,()=>n(1,i="pubkeys"),()=>n(1,i="events"),()=>n(1,i="ips"),()=>n(1,i="kinds"),()=>{n(1,i="moderation"),$&&0!==$.length||P()},()=>n(1,i="relay"),function(){u=this.value,n(6,u)},function(){d=this.value,n(7,d)},function(){p=this.value,n(9,p)},function(){f=this.value,n(10,f)},function(){y=this.value,n(12,y)},function(){m=this.value,n(13,m)},function(){b=this.value,n(14,b)},function(){v=this.value,n(15,v)},function(){w=this.value,n(17,w)},function(){k=this.value,n(18,k)},function(){x=to_number(this.value),n(20,x)},e=>D(e),e=>L(e.id),e=>F(e.id),function(){S.relay_name=this.value,n(0,S)},function(){S.relay_description=this.value,n(0,S)},function(){S.relay_icon=this.value,n(0,S)}]}class ManagedACL extends SvelteComponent{constructor(e){super(),init(this,e,instance$1,create_fragment$1,safe_not_equal,{userSigner:35,userPubkey:36},null,[-1,-1,-1])}}const DEFAULT_RELAYS$1=[`wss://${window.location.host}/`];class NostrClient{constructor(){this.ndk=new NDK({explicitRelayUrls:DEFAULT_RELAYS$1}),this.isConnected=!1}async connect(){console.log("Starting NDK connection to",DEFAULT_RELAYS$1.length,"relays...");try{await this.ndk.connect(),this.isConnected=!0,console.log("✓ NDK successfully connected to relays"),await new Promise(e=>setTimeout(e,1e3))}catch(e){throw console.error("✗ NDK connection failed:",e),e}}async connectToRelay(e){console.log(`Adding relay to NDK: ${e}`);try{return DEFAULT_RELAYS$1.push(e),await this.connect(),console.log(`✓ Successfully added relay ${e}`),!0}catch(t){return console.error(`✗ Failed to add relay ${e}:`,t),!1}}subscribe(e,t){console.log("Creating NDK subscription with filters:",e);const n=this.ndk.subscribe(e,{closeOnEose:!0});return n.on("event",e=>{console.log("Event received via NDK:",e),t(e.rawEvent())}),n.on("eose",()=>{console.log("EOSE received via NDK"),window.dispatchEvent(new CustomEvent("nostr-eose",{detail:{subscriptionId:n.id}}))}),n.id}unsubscribe(e){console.log(`Closing NDK subscription: ${e}`)}disconnect(){console.log("Disconnecting NDK"),this.ndk&&"function"==typeof this.ndk.disconnect&&this.ndk.disconnect(),this.isConnected=!1}async publish(e){console.log("Publishing event via NDK:",e);try{const t=new NDKEvent(this.ndk,e);return await t.publish(),console.log("✓ Event published successfully via NDK"),{success:!0,okCount:1,errorCount:0}}catch(e){throw console.error("✗ Failed to publish event via NDK:",e),e}}getNDK(){return this.ndk}getSigner(){return this.ndk.signer}setSigner(e){this.ndk.signer=e}}const nostrClient=new NostrClient,DB_NAME="nostrCache",DB_VERSION=1,STORE_EVENTS="events";function openDB(){return new Promise((e,t)=>{try{const n=indexedDB.open(DB_NAME,DB_VERSION);n.onupgradeneeded=()=>{const e=n.result;if(!e.objectStoreNames.contains(STORE_EVENTS)){const t=e.createObjectStore(STORE_EVENTS,{keyPath:"id"});t.createIndex("byKindAuthor",["kind","pubkey"],{unique:!1}),t.createIndex("byKindAuthorCreated",["kind","pubkey","created_at"],{unique:!1})}},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}catch(e){t(e)}})}async function getLatestProfileEvent(e){try{const t=await openDB();return await new Promise((n,s)=>{const r=t.transaction(STORE_EVENTS,"readonly").objectStore(STORE_EVENTS).index("byKindAuthorCreated"),i=IDBKeyRange.bound([0,e,-1/0],[0,e,1/0]),o=r.openCursor(i,"prev");o.onsuccess=()=>{const e=o.result;n(e?e.value:null)},o.onerror=()=>s(o.error)})}catch(e){return console.warn("IDB getLatestProfileEvent failed",e),null}}async function putEvent(e){try{const t=await openDB();await new Promise((n,s)=>{const r=t.transaction(STORE_EVENTS,"readwrite");r.oncomplete=()=>n(),r.onerror=()=>s(r.error),r.objectStore(STORE_EVENTS).put(e)})}catch(e){console.warn("IDB putEvent failed",e)}}function parseProfileFromEvent(e){try{const t=JSON.parse(e.content||"{}");return{name:t.name||t.display_name||"",picture:t.picture||"",banner:t.banner||"",about:t.about||"",nip05:t.nip05||"",lud16:t.lud16||t.lud06||""}}catch(e){return{name:"",picture:"",banner:"",about:"",nip05:"",lud16:""}}}async function fetchUserProfile(e){console.log(`Starting profile fetch for pubkey: ${e}`);try{const t=await getLatestProfileEvent(e);if(t){console.log("Using cached profile event");return parseProfileFromEvent(t)}}catch(e){console.warn("Failed to load cached profile",e)}try{const t=nostrClient.getNDK().getUser({hexpubkey:e}),n=await t.fetchProfile();if(n){console.log("Profile fetched via NDK:",n),await putEvent(n.rawEvent());const t=parseProfileFromEvent(n.rawEvent());try{"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("profile-updated",{detail:{pubkey:e,profile:t,event:n.rawEvent()}}))}catch(e){console.warn("Failed to dispatch profile-updated event",e)}return t}throw new Error("No profile found")}catch(e){throw console.error("Failed to fetch profile via NDK:",e),e}}async function fetchEvents(e,t={}){console.log("Starting event fetch with filters:",e);const{timeout:n=3e4,limit:s=null}=t;try{const t=nostrClient.getNDK(),r={...e};s&&(r.limit=s),console.log("Fetching events via NDK with filters:",r);const i=await t.fetchEvents(r,{timeout:n});console.log(`Fetched ${i.size} events via NDK`);return Array.from(i).map(e=>e.rawEvent())}catch(e){throw console.error("Failed to fetch events via NDK:",e),e}}async function fetchAllEvents(e={}){const{limit:t=100,since:n=null,until:s=null,authors:r=null,kinds:i=null,tags:o=null}=e,a={};n&&(a.since=n),s&&(a.until=s),r&&(a.authors=r),i&&(a.kinds=i),o&&(a.tags=o);return await fetchEvents(a,{limit:t,timeout:3e4})}async function searchEvents(e,t={}){const{limit:n=100,since:s=null,until:r=null,kinds:i=null}=t,o={search:e};s&&(o.since=s),r&&(o.until=r),i&&(o.kinds=i);return await fetchEvents(o,{limit:n,timeout:3e4})}async function fetchEventById(e,t={}){const{timeout:n=1e4,relays:s=null}=t;console.log(`Fetching event by ID: ${e}`);try{const t=nostrClient.getNDK(),s={ids:[e]};console.log("Fetching event via NDK with filters:",s);const r=await t.fetchEvents(s,{timeout:n});console.log(`Fetched ${r.size} events via NDK`);const i=Array.from(r).map(e=>e.rawEvent());return i.length>0?i[0]:null}catch(e){throw console.error("Failed to fetch event by ID via NDK:",e),e}}async function fetchDeleteEventsByTarget(e,t={}){const{timeout:n=1e4}=t;console.log(`Fetching delete events for target: ${e}`);try{const t=nostrClient.getNDK(),s={kinds:[5],"#e":[e]};console.log("Fetching delete events via NDK with filters:",s);const r=await t.fetchEvents(s,{timeout:n});console.log(`Fetched ${r.size} delete events via NDK`);return Array.from(r).map(e=>e.rawEvent())}catch(e){throw console.error("Failed to fetch delete events via NDK:",e),e}}async function initializeNostrClient(){await nostrClient.connect()}class NostrWebSocketAuth{constructor(e,t,n){this.relayUrl=e,this.userSigner=t,this.userPubkey=n,this.ws=null,this.challenge=null,this.isAuthenticated=!1,this.authPromise=null}async connect(){return new Promise((e,t)=>{this.ws=new WebSocket(this.relayUrl),this.ws.onopen=()=>{console.log("WebSocket connected to relay:",this.relayUrl),e()},this.ws.onmessage=async e=>{try{const t=JSON.parse(e.data);await this.handleMessage(t)}catch(e){console.error("Error parsing relay message:",e)}},this.ws.onerror=e=>{console.error("WebSocket error:",e),t(new Error("Failed to connect to relay"))},this.ws.onclose=()=>{console.log("WebSocket connection closed"),this.isAuthenticated=!1,this.challenge=null},setTimeout(()=>{this.ws.readyState!==WebSocket.OPEN&&t(new Error("Connection timeout"))},1e4)})}async handleMessage(e){const[t,...n]=e;switch(t){case"AUTH":this.challenge=n[0],console.log("Received AUTH challenge:",this.challenge),await this.authenticate();break;case"OK":const[e,s,r]=n;e&&s?(console.log("Authentication successful for event:",e),this.isAuthenticated=!0,this.authPromise&&(this.authPromise.resolve(),this.authPromise=null)):e&&!s&&(console.error("Authentication failed:",r),this.authPromise&&(this.authPromise.reject(new Error(r||"Authentication failed")),this.authPromise=null));break;case"NOTICE":console.log("Relay notice:",n[0]);break;default:console.log("Unhandled message type:",t,n)}}async authenticate(){if(!this.challenge)throw new Error("No challenge received from relay");if(!this.userSigner)throw new Error("No signer available for authentication");try{const e={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["relay",this.relayUrl],["challenge",this.challenge]],content:"",pubkey:this.userPubkey},t=["AUTH",await this.userSigner.signEvent(e)];return this.ws.send(JSON.stringify(t)),console.log("Sent authentication event to relay"),new Promise((e,t)=>{this.authPromise={resolve:e,reject:t},setTimeout(()=>{this.authPromise&&(this.authPromise.reject(new Error("Authentication timeout")),this.authPromise=null)},1e4)})}catch(e){throw console.error("Authentication error:",e),e}}async publishEvent(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");return new Promise((t,n)=>{const s=["EVENT",e];this.ws.send(JSON.stringify(s));const r=this.ws.onmessage,i=setTimeout(()=>{this.ws.onmessage=r,n(new Error("Publish timeout"))},15e3);this.ws.onmessage=async s=>{try{const o=JSON.parse(s.data),[a,c,l,u]=o;if("OK"===a&&c===e.id)if(clearTimeout(i),this.ws.onmessage=r,l)console.log("Event published successfully:",c),t({success:!0,eventId:c,reason:u});else{if(console.error("Event publish failed:",u),u&&u.includes("auth-required")){console.log("Authentication required, attempting to authenticate...");try{await this.authenticate();const t=["EVENT",e];return void this.ws.send(JSON.stringify(t))}catch(e){return void n(new Error(`Authentication failed: ${e.message}`))}}n(new Error(`Publish failed: ${u}`))}else await this.handleMessage(o)}catch(e){clearTimeout(i),this.ws.onmessage=r,n(e)}}})}close(){this.ws&&(this.ws.close(),this.ws=null),this.isAuthenticated=!1,this.challenge=null}getAuthenticated(){return this.isAuthenticated}}async function publishEventWithAuth(e,t,n,s){const r=new NostrWebSocketAuth(e,n,s);try{await r.connect();return await r.publishEvent(t)}finally{r.close()}}function get_each_context_7(e,t,n){const s=e.slice();return s[165]=t[n],s}function get_each_context_8(e,t,n){const s=e.slice();return s[145]=t[n],s}function get_each_context_3(e,t,n){const s=e.slice();s[145]=t[n];const r=s[45](s[145]);return s[154]=r,s}function get_each_context_4(e,t,n){const s=e.slice();return s[157]=t[n],s}function get_each_context_5(e,t,n){const s=e.slice();return s[157]=t[n],s}function get_each_context_6(e,t,n){const s=e.slice();return s[162]=t[n],s}function get_each_context_2(e,t,n){const s=e.slice();return s[151]=t[n],s}function get_each_context(e,t,n){const s=e.slice();return s[145]=t[n],s}function get_each_context_1(e,t,n){const s=e.slice();return s[148]=t[n],s}function get_each_context_9(e,t,n){const s=e.slice();return s[170]=t[n],s}function create_else_block_14(e){let t,n,s,r=e[1]&&e[4]&&create_if_block_58(e);return{c(){t=element("div"),n=element("span"),s=text("ORLY? dashboard\n "),r&&r.c(),attr(n,"class","app-title svelte-1a66x6i"),attr(t,"class","header-title svelte-1a66x6i")},m(e,i){insert(e,t,i),append(t,n),append(n,s),r&&r.m(n,null)},p(e,t){e[1]&&e[4]?r?r.p(e,t):(r=create_if_block_58(e),r.c(),r.m(n,null)):r&&(r.d(1),r=null)},d(e){e&&detach(t),r&&r.d()}}}function create_if_block_57(e){let t,n,s,r;return{c(){t=element("div"),n=element("input"),attr(n,"type","text"),attr(n,"class","search-input svelte-1a66x6i"),attr(n,"placeholder","Search..."),attr(t,"class","search-input-container svelte-1a66x6i")},m(i,o){insert(i,t,o),append(t,n),set_input_value(n,e[15]),s||(r=[listen(n,"input",e[83]),listen(n,"keydown",e[64])],s=!0)},p(e,t){32768&t[0]&&n.value!==e[15]&&set_input_value(n,e[15])},d(e){e&&detach(t),s=!1,run_all(r)}}}function create_if_block_58(e){let t,n;return{c(){t=element("span"),n=text(e[4]),attr(t,"class","permission-badge svelte-1a66x6i")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){16&t[0]&&set_data(n,e[4])},d(e){e&&detach(t)}}}function create_else_block_13(e){let t,n,s;return{c(){t=element("button"),t.textContent="Log in",attr(t,"class","login-btn svelte-1a66x6i")},m(r,i){insert(r,t,i),n||(s=listen(t,"click",e[57]),n=!0)},p:noop,d(e){e&&detach(t),n=!1,s()}}}function create_if_block_55(e){let t,n,s,r,i,o,a,c=(e[3]?.name||e[2].slice(0,8)+"...")+"";function l(e,t){return e[3]?.picture?create_if_block_56:create_else_block_12}let u=l(e),d=u(e);return{c(){t=element("div"),n=element("button"),d.c(),s=space(),r=element("span"),i=text(c),attr(r,"class","user-name svelte-1a66x6i"),attr(n,"class","user-profile-btn svelte-1a66x6i"),attr(t,"class","user-info svelte-1a66x6i")},m(c,l){insert(c,t,l),append(t,n),d.m(n,null),append(n,s),append(n,r),append(r,i),o||(a=listen(n,"click",e[61]),o=!0)},p(e,t){u===(u=l(e))&&d?d.p(e,t):(d.d(1),d=u(e),d&&(d.c(),d.m(n,s))),12&t[0]&&c!==(c=(e[3]?.name||e[2].slice(0,8)+"...")+"")&&set_data(i,c)},d(e){e&&detach(t),d.d(),o=!1,a()}}}function create_else_block_12(e){let t;return{c(){t=element("div"),t.textContent="👤",attr(t,"class","user-avatar-placeholder svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_56(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].picture)||attr(t,"src",n),attr(t,"alt","User avatar"),attr(t,"class","user-avatar svelte-1a66x6i")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].picture)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_if_block_54(e){let t,n,s;function r(){return e[84](e[170])}function i(...t){return e[85](e[170],...t)}return{c(){t=element("span"),t.textContent="✕",attr(t,"class","tab-close-icon svelte-1a66x6i"),attr(t,"role","button"),attr(t,"tabindex","0")},m(e,o){insert(e,t,o),n||(s=[listen(t,"click",stop_propagation(r)),listen(t,"keydown",i)],n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,run_all(s)}}}function create_each_block_9(e){let t,n,s,r,i,o,a,c,l,u,d=e[170].icon+"",h=e[170].label+"",p=e[170].isSearchTab&&create_if_block_54(e);function f(){return e[86](e[170])}return{c(){t=element("button"),n=element("span"),s=text(d),r=space(),i=element("span"),o=text(h),a=space(),p&&p.c(),c=space(),attr(n,"class","tab-icon svelte-1a66x6i"),attr(i,"class","tab-label svelte-1a66x6i"),attr(t,"class","tab svelte-1a66x6i"),toggle_class(t,"active",e[5]===e[170].id)},m(e,d){insert(e,t,d),append(t,n),append(n,s),append(t,r),append(t,i),append(i,o),append(t,a),p&&p.m(t,null),append(t,c),l||(u=listen(t,"click",f),l=!0)},p(n,r){e=n,1024&r[0]&&d!==(d=e[170].icon+"")&&set_data(s,d),1024&r[0]&&h!==(h=e[170].label+"")&&set_data(o,h),e[170].isSearchTab?p?p.p(e,r):(p=create_if_block_54(e),p.c(),p.m(t,c)):p&&(p.d(1),p=null),1056&r[0]&&toggle_class(t,"active",e[5]===e[170].id)},d(e){e&&detach(t),p&&p.d(),l=!1,u()}}}function create_else_block_10(e){let t;function n(e,t){return e[1]?create_if_block_53:create_else_block_11}let s=n(e),r=s(e);return{c(){t=element("div"),r.c(),attr(t,"class","welcome-message svelte-1a66x6i")},m(e,n){insert(e,t,n),r.m(t,null)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),r.d()}}}function create_if_block_45(e){let t,n=e[6],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_7(get_each_context_7(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(131188&r[0]|720&r[1]|48&r[2]){let i;for(n=e[6],i=0;i<n.length;i+=1){const o=get_each_context_7(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_7(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},i:noop,o:noop,d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_36(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b=e[36],v=[];for(let t=0;t<b.length;t+=1)v[t]=create_each_block_6(get_each_context_6(e,b,t));let _=(e[28]||e[29])&&create_if_block_37(e);return{c(){t=element("div"),n=element("div"),n.innerHTML='<h2 class="svelte-1a66x6i">🔄 Event Recovery</h2> \n <p class="svelte-1a66x6i">Search and recover old versions of replaceable events</p>',s=space(),r=element("div"),i=element("div"),o=element("label"),o.textContent="Select Event Kind:",a=space(),c=element("select"),l=element("option"),l.textContent="Choose a replaceable kind...";for(let e=0;e<v.length;e+=1)v[e].c();u=space(),d=element("div"),h=element("label"),h.textContent="Or enter custom kind number:",p=space(),f=element("input"),g=space(),_&&_.c(),attr(n,"class","recovery-header svelte-1a66x6i"),attr(o,"for","recovery-kind"),attr(o,"class","svelte-1a66x6i"),l.__value=null,l.value=l.__value,attr(c,"id","recovery-kind"),attr(c,"class","svelte-1a66x6i"),void 0===e[28]&&add_render_callback(()=>e[99].call(c)),attr(i,"class","kind-selector svelte-1a66x6i"),attr(h,"for","custom-kind"),attr(h,"class","svelte-1a66x6i"),attr(f,"id","custom-kind"),attr(f,"type","number"),attr(f,"placeholder","e.g., 10001"),attr(f,"min","0"),attr(f,"class","svelte-1a66x6i"),attr(d,"class","custom-kind-input svelte-1a66x6i"),attr(r,"class","recovery-controls svelte-1a66x6i"),attr(t,"class","recovery-tab svelte-1a66x6i")},m(b,w){insert(b,t,w),append(t,n),append(t,s),append(t,r),append(r,i),append(i,o),append(i,a),append(i,c),append(c,l);for(let e=0;e<v.length;e+=1)v[e]&&v[e].m(c,null);select_option(c,e[28],!0),append(r,u),append(r,d),append(d,h),append(d,p),append(d,f),set_input_value(f,e[29]),append(t,g),_&&_.m(t,null),y||(m=[listen(c,"change",e[99]),listen(c,"change",e[100]),listen(f,"input",e[101]),listen(f,"input",e[44])],y=!0)},p(e,n){if(32&n[1]){let t;for(b=e[36],t=0;t<b.length;t+=1){const s=get_each_context_6(e,b,t);v[t]?v[t].p(s,n):(v[t]=create_each_block_6(s),v[t].c(),v[t].m(c,null))}for(;t<v.length;t+=1)v[t].d(1);v.length=b.length}268435456&n[0]|32&n[1]&&select_option(c,e[28]),536870912&n[0]&&to_number(f.value)!==e[29]&&set_input_value(f,e[29]),e[28]||e[29]?_?_.p(e,n):(_=create_if_block_37(e),_.c(),_.m(t,null)):_&&(_.d(1),_=null)},i:noop,o:noop,d(e){e&&detach(t),destroy_each(v,e),_&&_.d(),y=!1,run_all(m)}}}function create_if_block_29(e){let t,n,s;function r(e,t){return e[1]&&"owner"===e[4]?create_if_block_30:e[1]?create_if_block_35:create_else_block_7}let i=r(e),o=i(e);return{c(){t=element("div"),n=element("h2"),n.textContent="Sprocket Script Management",s=space(),o.c(),attr(t,"class","sprocket-view svelte-1a66x6i")},m(e,r){insert(e,t,r),append(t,n),append(t,s),o.m(t,null)},p(e,n){i===(i=r(e))&&o?o.p(e,n):(o.d(1),o=i(e),o&&(o.c(),o.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),o.d()}}}function create_if_block_26(e){let t,n,s,r;const i=[create_if_block_27,create_if_block_28,create_else_block_6],o=[];function a(e,t){return"managed"!==e[9]?0:e[1]&&"owner"===e[4]?1:2}return n=a(e),s=o[n]=i[n](e),{c(){t=element("div"),s.c(),attr(t,"class","managed-acl-view svelte-1a66x6i")},m(e,s){insert(e,t,s),o[n].m(t,null),r=!0},p(e,r){let c=n;n=a(e),n===c?o[n].p(e,r):(group_outros(),transition_out(o[c],1,1,()=>{o[c]=null}),check_outros(),s=o[n],s?s.p(e,r):(s=o[n]=i[n](e),s.c()),transition_in(s,1),s.m(t,null))},i(e){r||(transition_in(s),r=!0)},o(e){transition_out(s),r=!1},d(e){e&&detach(t),o[n].d()}}}function create_if_block_25(e){let t,n,s,r,i,o,a,c,l,u,d,h;return{c(){t=element("div"),n=element("div"),s=element("button"),s.textContent="Reformat",r=space(),i=element("button"),i.textContent="Sign",o=space(),a=element("button"),a.textContent="Publish",c=space(),l=element("div"),u=element("textarea"),attr(s,"class","compose-btn reformat-btn svelte-1a66x6i"),attr(i,"class","compose-btn sign-btn svelte-1a66x6i"),attr(a,"class","compose-btn publish-btn svelte-1a66x6i"),attr(n,"class","compose-header svelte-1a66x6i"),attr(u,"class","compose-textarea svelte-1a66x6i"),attr(u,"placeholder","Enter your Nostr event JSON here..."),attr(u,"spellcheck","false"),attr(l,"class","compose-editor svelte-1a66x6i"),attr(t,"class","compose-view svelte-1a66x6i")},m(p,f){insert(p,t,f),append(t,n),append(n,s),append(n,r),append(n,i),append(n,o),append(n,a),append(t,c),append(t,l),append(l,u),set_input_value(u,e[27]),d||(h=[listen(s,"click",e[75]),listen(i,"click",e[76]),listen(a,"click",e[77]),listen(u,"input",e[95])],d=!0)},p(e,t){134217728&t[0]&&set_input_value(u,e[27])},i:noop,o:noop,d(e){e&&detach(t),d=!1,run_all(h)}}}function create_if_block_13(e){let t,n;function s(e,t){return!e[1]||"write"!==e[4]&&"admin"!==e[4]&&"owner"!==e[4]?create_else_block_5:create_if_block_16}let r=s(e),i=r(e),o=e[1]&&("write"===e[4]||"admin"===e[4]||"owner"===e[4])&&create_if_block_14(e);return{c(){t=element("div"),i.c(),n=space(),o&&o.c(),attr(t,"class","events-view-container svelte-1a66x6i")},m(e,s){insert(e,t,s),i.m(t,null),append(t,n),o&&o.m(t,null)},p(e,a){r===(r=s(e))&&i?i.p(e,a):(i.d(1),i=r(e),i&&(i.c(),i.m(t,n))),!e[1]||"write"!==e[4]&&"admin"!==e[4]&&"owner"!==e[4]?o&&(o.d(1),o=null):o?o.p(e,a):(o=create_if_block_14(e),o.c(),o.m(t,null))},i:noop,o:noop,d(e){e&&detach(t),i.d(),o&&o.d()}}}function create_if_block_10(e){let t;function n(e,t){return!e[1]||"admin"!==e[4]&&"owner"!==e[4]?e[1]?create_if_block_12:create_else_block_2:create_if_block_11}let s=n(e),r=s(e);return{c(){t=element("div"),r.c(),attr(t,"class","import-view svelte-1a66x6i")},m(e,n){insert(e,t,n),r.m(t,null)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),r.d()}}}function create_if_block_7(e){let t;function n(e,t){return e[1]?create_if_block_8:create_else_block_1}let s=n(e),r=s(e);return{c(){r.c(),t=empty()},m(e,n){r.m(e,n),insert(e,t,n)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t.parentNode,t)))},i:noop,o:noop,d(e){r.d(e),e&&detach(t)}}}function create_else_block_11(e){let t;return{c(){t=element("p"),t.textContent="Log in to access your user dashboard",attr(t,"class","svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_53(e){let t,n,s,r=(e[3]?.name||e[2].slice(0,8)+"...")+"";return{c(){t=element("p"),n=text("Welcome "),s=text(r),attr(t,"class","svelte-1a66x6i")},m(e,r){insert(e,t,r),append(t,n),append(t,s)},p(e,t){12&t[0]&&r!==(r=(e[3]?.name||e[2].slice(0,8)+"...")+"")&&set_data(s,r)},d(e){e&&detach(t)}}}function create_if_block_46(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_=e[165].query+"",w=e[35].get(e[165].id)?.isLoading,k=!e[35].get(e[165].id)?.hasMore&&e[35].get(e[165].id)?.events?.length>0;function E(){return e[103](e[165])}function x(e,t){return 64&t[0]&&(p=null),64&t[0]&&(f=null),null==p&&(p=!!(e[35].get(e[165].id)?.events?.length>0)),p?create_if_block_49:(null==f&&(f=!e[35].get(e[165].id)?.isLoading),f?create_if_block_52:void 0)}let $=x(e,[-1,-1,-1,-1,-1,-1]),S=$&&$(e),T=w&&create_if_block_48(),A=k&&create_if_block_47();function R(...t){return e[108](e[165],...t)}return{c(){t=element("div"),n=element("div"),s=element("h2"),r=text('🔍 Search Results: "'),i=text(_),o=text('"'),a=space(),c=element("button"),l=text("🔄 Refresh"),d=space(),h=element("div"),S&&S.c(),g=space(),T&&T.c(),y=space(),A&&A.c(),m=space(),attr(s,"class","svelte-1a66x6i"),attr(c,"class","refresh-btn svelte-1a66x6i"),c.disabled=u=e[35].get(e[165].id)?.isLoading,attr(n,"class","search-results-header svelte-1a66x6i"),attr(h,"class","search-results-content svelte-1a66x6i"),attr(t,"class","search-results-view svelte-1a66x6i")},m(e,u){insert(e,t,u),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),append(c,l),append(t,d),append(t,h),S&&S.m(h,null),append(h,g),T&&T.m(h,null),append(h,y),A&&A.m(h,null),append(t,m),b||(v=[listen(c,"click",E),listen(h,"scroll",R)],b=!0)},p(t,n){e=t,64&n[0]&&_!==(_=e[165].query+"")&&set_data(i,_),64&n[0]&&u!==(u=e[35].get(e[165].id)?.isLoading)&&(c.disabled=u),$===($=x(e,n))&&S?S.p(e,n):(S&&S.d(1),S=$&&$(e),S&&(S.c(),S.m(h,g))),64&n[0]&&(w=e[35].get(e[165].id)?.isLoading),w?T||(T=create_if_block_48(),T.c(),T.m(h,y)):T&&(T.d(1),T=null),64&n[0]&&(k=!e[35].get(e[165].id)?.hasMore&&e[35].get(e[165].id)?.events?.length>0),k?A||(A=create_if_block_47(),A.c(),A.m(h,null)):A&&(A.d(1),A=null)},d(e){e&&detach(t),S&&S.d(),T&&T.d(),A&&A.d(),b=!1,run_all(v)}}}function create_if_block_52(e){let t,n,s,r,i,o=e[165].query+"";return{c(){t=element("div"),n=element("p"),s=text('No search results found for "'),r=text(o),i=text('".'),attr(n,"class","svelte-1a66x6i"),attr(t,"class","no-search-results svelte-1a66x6i")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(n,r),append(n,i)},p(e,t){64&t[0]&&o!==(o=e[165].query+"")&&set_data(r,o)},d(e){e&&detach(t)}}}function create_if_block_49(e){let t,n=e[35].get(e[165].id).events,s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_8(get_each_context_8(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(131156&r[0]|720&r[1]){let i;for(n=e[35].get(e[165].id).events,i=0;i<n.length;i+=1){const o=get_each_context_8(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_8(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_51(e){let t,n,s;function r(){return e[104](e[145])}return{c(){t=element("button"),t.textContent="🗑️",attr(t,"class","delete-btn svelte-1a66x6i")},m(e,i){insert(e,t,i),n||(s=listen(t,"click",stop_propagation(r)),n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,s()}}}function create_if_block_50(e){let t,n,s,r,i,o,a,c,l=JSON.stringify(e[145],null,2)+"";function u(...t){return e[107](e[145],...t)}return{c(){t=element("div"),n=element("div"),s=element("pre"),r=text(l),i=space(),o=element("button"),o.textContent="📋",attr(s,"class","event-json svelte-1a66x6i"),attr(o,"class","copy-json-btn svelte-1a66x6i"),attr(o,"title","Copy minified JSON to clipboard"),attr(n,"class","json-container svelte-1a66x6i"),attr(t,"class","search-result-details svelte-1a66x6i")},m(e,l){insert(e,t,l),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),a||(c=listen(o,"click",stop_propagation(u)),a=!0)},p(t,n){e=t,64&n[0]&&l!==(l=JSON.stringify(e[145],null,2)+"")&&set_data(r,l)},d(e){e&&detach(t),a=!1,c()}}}function create_each_block_8(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T=truncatePubkey(e[145].pubkey)+"",A=e[145].kind+"",R=e[37](e[145].kind)+"",N=formatTimestamp(e[145].created_at)+"",C=truncateContent(e[145].content)+"",I=e[17].has(e[145].id),B=5!==e[145].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[145].pubkey&&e[145].pubkey===e[2])&&create_if_block_51(e);function P(){return e[105](e[145])}function D(...t){return e[106](e[145],...t)}let L=I&&create_if_block_50(e);return{c(){t=element("div"),n=element("div"),s=element("div"),s.innerHTML='<div class="avatar-placeholder svelte-1a66x6i">👤</div>',r=space(),i=element("div"),o=element("div"),a=text(T),c=space(),l=element("div"),u=element("span"),d=text(A),h=space(),p=element("span"),f=text(R),g=space(),y=element("div"),m=element("div"),b=text(N),v=space(),_=element("div"),w=text(C),k=space(),B&&B.c(),E=space(),L&&L.c(),x=space(),attr(s,"class","search-result-avatar svelte-1a66x6i"),attr(o,"class","search-result-author svelte-1a66x6i"),attr(u,"class","kind-number svelte-1a66x6i"),attr(p,"class","kind-name svelte-1a66x6i"),attr(l,"class","search-result-kind svelte-1a66x6i"),attr(i,"class","search-result-info svelte-1a66x6i"),attr(m,"class","event-timestamp svelte-1a66x6i"),attr(_,"class","event-content-single-line svelte-1a66x6i"),attr(y,"class","search-result-content svelte-1a66x6i"),attr(n,"class","search-result-row svelte-1a66x6i"),attr(n,"role","button"),attr(n,"tabindex","0"),attr(t,"class","search-result-item svelte-1a66x6i"),toggle_class(t,"expanded",e[17].has(e[145].id))},m(e,T){insert(e,t,T),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(u,d),append(l,h),append(l,p),append(p,f),append(n,g),append(n,y),append(y,m),append(m,b),append(y,v),append(y,_),append(_,w),append(n,k),B&&B.m(n,null),append(t,E),L&&L.m(t,null),append(t,x),$||(S=[listen(n,"click",P),listen(n,"keydown",D)],$=!0)},p(s,r){e=s,64&r[0]&&T!==(T=truncatePubkey(e[145].pubkey)+"")&&set_data(a,T),64&r[0]&&A!==(A=e[145].kind+"")&&set_data(d,A),64&r[0]&&R!==(R=e[37](e[145].kind)+"")&&set_data(f,R),64&r[0]&&N!==(N=formatTimestamp(e[145].created_at)+"")&&set_data(b,N),64&r[0]&&C!==(C=truncateContent(e[145].content)+"")&&set_data(w,C),5!==e[145].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[145].pubkey&&e[145].pubkey===e[2])?B?B.p(e,r):(B=create_if_block_51(e),B.c(),B.m(n,null)):B&&(B.d(1),B=null),131136&r[0]&&(I=e[17].has(e[145].id)),I?L?L.p(e,r):(L=create_if_block_50(e),L.c(),L.m(t,x)):L&&(L.d(1),L=null),131136&r[0]|16&r[1]&&toggle_class(t,"expanded",e[17].has(e[145].id))},d(e){e&&detach(t),B&&B.d(),L&&L.d(),$=!1,run_all(S)}}}function create_if_block_48(e){let t;return{c(){t=element("div"),t.innerHTML='<div class="loading-spinner svelte-1a66x6i"></div> \n <p class="svelte-1a66x6i">Searching...</p>',attr(t,"class","loading-search-results svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_47(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-1a66x6i">No more search results to load.</p>',attr(t,"class","end-of-search-results svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_each_block_7(e){let t,n=e[165].id===e[5]&&create_if_block_46(e);return{c(){n&&n.c(),t=empty()},m(e,s){n&&n.m(e,s),insert(e,t,s)},p(e,s){e[165].id===e[5]?n?n.p(e,s):(n=create_if_block_46(e),n.c(),n.m(t.parentNode,t)):n&&(n.d(1),n=null)},d(e){n&&n.d(e),e&&detach(t)}}}function create_each_block_6(e){let t,n,s=e[162].label+"";return{c(){t=element("option"),n=text(s),t.__value=e[162].value,t.value=t.__value},m(e,s){insert(e,t,s),append(t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_37(e){let t;function n(e,t){return e[31]?create_if_block_38:0===e[30].length?create_if_block_39:create_else_block_8}let s=n(e),r=s(e);return{c(){t=element("div"),r.c(),attr(t,"class","recovery-results svelte-1a66x6i")},m(e,n){insert(e,t,n),r.m(t,null)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t,null)))},d(e){e&&detach(t),r.d()}}}function create_else_block_8(e){let t,n,s,r=e[30],i=[];for(let t=0;t<r.length;t+=1)i[t]=create_each_block_3(get_each_context_3(e,r,t));let o=e[32]&&create_if_block_40(e);return{c(){t=element("div");for(let e=0;e<i.length;e+=1)i[e].c();n=space(),o&&o.c(),s=empty(),attr(t,"class","events-list svelte-1a66x6i")},m(e,r){insert(e,t,r);for(let e=0;e<i.length;e+=1)i[e]&&i[e].m(t,null);insert(e,n,r),o&&o.m(e,r),insert(e,s,r)},p(e,n){if(1073741824&n[0]|18432&n[1]){let s;for(r=e[30],s=0;s<r.length;s+=1){const o=get_each_context_3(e,r,s);i[s]?i[s].p(o,n):(i[s]=create_each_block_3(o),i[s].c(),i[s].m(t,null))}for(;s<i.length;s+=1)i[s].d(1);i.length=r.length}e[32]?o?o.p(e,n):(o=create_if_block_40(e),o.c(),o.m(s.parentNode,s)):o&&(o.d(1),o=null)},d(e){e&&detach(t),destroy_each(i,e),e&&detach(n),o&&o.d(e),e&&detach(s)}}}function create_if_block_39(e){let t;return{c(){t=element("div"),t.textContent="No events found for this kind",attr(t,"class","no-events svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_38(e){let t;return{c(){t=element("div"),t.textContent="Loading events...",attr(t,"class","loading svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_44(e){let t,n,s;function r(){return e[102](e[145])}return{c(){t=element("button"),t.textContent="🔄 Repost",attr(t,"class","repost-button svelte-1a66x6i")},m(e,i){insert(e,t,i),n||(s=listen(t,"click",r),n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,s()}}}function create_else_block_9(e){let t,n,s,r=e[145].content+"";return{c(){t=element("div"),n=element("pre"),s=text(r),attr(n,"class","svelte-1a66x6i"),attr(t,"class","generic-content svelte-1a66x6i")},m(e,r){insert(e,t,r),append(t,n),append(n,s)},p(e,t){1073741824&t[0]&&r!==(r=e[145].content+"")&&set_data(s,r)},d(e){e&&detach(t)}}}function create_if_block_43(e){let t,n,s,r,i,o,a,c=e[145].tags.filter(func_2).length+"",l=e[145].tags.filter(func_3),u=[];for(let t=0;t<l.length;t+=1)u[t]=create_each_block_5(get_each_context_5(e,l,t));return{c(){t=element("div"),n=element("p"),s=text("Follows "),r=text(c),i=text(" people"),o=space(),a=element("div");for(let e=0;e<u.length;e+=1)u[e].c();attr(n,"class","svelte-1a66x6i"),attr(a,"class","follow-tags svelte-1a66x6i"),attr(t,"class","follow-list svelte-1a66x6i")},m(e,c){insert(e,t,c),append(t,n),append(n,s),append(n,r),append(n,i),append(t,o),append(t,a);for(let e=0;e<u.length;e+=1)u[e]&&u[e].m(a,null)},p(e,t){if(1073741824&t[0]&&c!==(c=e[145].tags.filter(func_2).length+"")&&set_data(r,c),1073741824&t[0]){let n;for(l=e[145].tags.filter(func_3),n=0;n<l.length;n+=1){const s=get_each_context_5(e,l,n);u[n]?u[n].p(s,t):(u[n]=create_each_block_5(s),u[n].c(),u[n].m(a,null))}for(;n<u.length;n+=1)u[n].d(1);u.length=l.length}},d(e){e&&detach(t),destroy_each(u,e)}}}function create_if_block_41(e){let t,n=e[145].content&&create_if_block_42(e);return{c(){n&&n.c(),t=empty()},m(e,s){n&&n.m(e,s),insert(e,t,s)},p(e,s){e[145].content?n?n.p(e,s):(n=create_if_block_42(e),n.c(),n.m(t.parentNode,t)):n&&(n.d(1),n=null)},d(e){n&&n.d(e),e&&detach(t)}}}function create_each_block_5(e){let t,n,s,r=e[157][1].substring(0,8)+"";return{c(){t=element("span"),n=text(r),s=text("..."),attr(t,"class","pubkey-tag svelte-1a66x6i")},m(e,r){insert(e,t,r),append(t,n),append(t,s)},p(e,t){1073741824&t[0]&&r!==(r=e[157][1].substring(0,8)+"")&&set_data(n,r)},d(e){e&&detach(t)}}}function create_if_block_42(e){let t,n,s,r=JSON.stringify(JSON.parse(e[145].content),null,2)+"";return{c(){t=element("div"),n=element("pre"),s=text(r),attr(n,"class","svelte-1a66x6i"),attr(t,"class","profile-content svelte-1a66x6i")},m(e,r){insert(e,t,r),append(t,n),append(n,s)},p(e,t){1073741824&t[0]&&r!==(r=JSON.stringify(JSON.parse(e[145].content),null,2)+"")&&set_data(s,r)},d(e){e&&detach(t)}}}function create_each_block_4(e){let t,n,s,r,i=e[157][0]+"",o=e[157][1]+"";return{c(){t=element("span"),n=text(i),s=text(": "),r=text(o),attr(t,"class","tag svelte-1a66x6i")},m(e,i){insert(e,t,i),append(t,n),append(t,s),append(t,r)},p(e,t){1073741824&t[0]&&i!==(i=e[157][0]+"")&&set_data(n,i),1073741824&t[0]&&o!==(o=e[157][1]+"")&&set_data(r,o)},d(e){e&&detach(t)}}}function create_each_block_3(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g=e[145].kind+"",y=new Date(1e3*e[145].created_at).toLocaleString()+"",m=!e[154]&&create_if_block_44(e);function b(e,t){return 0===e[145].kind?create_if_block_41:3===e[145].kind?create_if_block_43:create_else_block_9}let v=b(e),_=v(e),w=e[145].tags,k=[];for(let t=0;t<w.length;t+=1)k[t]=create_each_block_4(get_each_context_4(e,w,t));return{c(){t=element("div"),n=element("div"),s=element("span"),r=text("Kind "),i=text(g),o=space(),a=element("span"),c=text(y),l=space(),m&&m.c(),u=space(),d=element("div"),_.c(),h=space(),p=element("div");for(let e=0;e<k.length;e+=1)k[e].c();f=space(),attr(s,"class","event-kind svelte-1a66x6i"),attr(a,"class","event-timestamp svelte-1a66x6i"),attr(n,"class","event-header svelte-1a66x6i"),attr(d,"class","event-content svelte-1a66x6i"),attr(p,"class","event-tags svelte-1a66x6i"),attr(t,"class","event-item svelte-1a66x6i"),toggle_class(t,"old-version",!e[154])},m(e,g){insert(e,t,g),append(t,n),append(n,s),append(s,r),append(s,i),append(n,o),append(n,a),append(a,c),append(n,l),m&&m.m(n,null),append(t,u),append(t,d),_.m(d,null),append(t,h),append(t,p);for(let e=0;e<k.length;e+=1)k[e]&&k[e].m(p,null);append(t,f)},p(e,s){if(1073741824&s[0]&&g!==(g=e[145].kind+"")&&set_data(i,g),1073741824&s[0]&&y!==(y=new Date(1e3*e[145].created_at).toLocaleString()+"")&&set_data(c,y),e[154]?m&&(m.d(1),m=null):m?m.p(e,s):(m=create_if_block_44(e),m.c(),m.m(n,null)),v===(v=b(e))&&_?_.p(e,s):(_.d(1),_=v(e),_&&(_.c(),_.m(d,null))),1073741824&s[0]){let t;for(w=e[145].tags,t=0;t<w.length;t+=1){const n=get_each_context_4(e,w,t);k[t]?k[t].p(n,s):(k[t]=create_each_block_4(n),k[t].c(),k[t].m(p,null))}for(;t<k.length;t+=1)k[t].d(1);k.length=w.length}1073741824&s[0]|16384&s[1]&&toggle_class(t,"old-version",!e[154])},d(e){e&&detach(t),m&&m.d(),_.d(),destroy_each(k,e)}}}function create_if_block_40(e){let t,n,s,r;return{c(){t=element("button"),n=text("Load More Events"),attr(t,"class","load-more svelte-1a66x6i"),t.disabled=e[31]},m(i,o){insert(i,t,o),append(t,n),s||(r=listen(t,"click",e[41]),s=!0)},p(e,n){1&n[1]&&(t.disabled=e[31])},d(e){e&&detach(t),s=!1,r()}}}function create_else_block_7(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access sprocket management.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-1a66x6i"),attr(r,"class","login-btn svelte-1a66x6i"),attr(t,"class","login-prompt svelte-1a66x6i")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[57]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_35(e){let t,n,s,r,i,o,a,c,l,u=(e[4]||"none")+"";return{c(){t=element("div"),n=element("p"),n.textContent="❌ Owner permission required for sprocket\n management.",s=space(),r=element("p"),r.innerHTML="To enable sprocket functionality, set the <code>ORLY_OWNERS</code> environment variable with your npub when starting the\n relay.",i=space(),o=element("p"),a=text("Current user role: "),c=element("strong"),l=text(u),attr(n,"class","svelte-1a66x6i"),attr(r,"class","svelte-1a66x6i"),attr(o,"class","svelte-1a66x6i"),attr(t,"class","permission-denied svelte-1a66x6i")},m(e,u){insert(e,t,u),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(o,a),append(o,c),append(c,l)},p(e,t){16&t[0]&&u!==(u=(e[4]||"none")+"")&&set_data(l,u)},d(e){e&&detach(t)}}}function create_if_block_30(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A,R,N,C,I,B,P,D,L,F,O,U,M,K,H,j,V,z,q,W,G,J,Z,Y,X,Q,ee,te,ne,se=e[21]?.is_running?"🟢 Running":"🔴 Stopped",re=e[21]?.script_exists?"✅ Exists":"❌ Not found",ie=e[21]?.pid&&create_if_block_34(e),oe=e[24]&&create_if_block_33(e),ae=e[22],ce=[];for(let t=0;t<ae.length;t+=1)ce[t]=create_each_block_2(get_each_context_2(e,ae,t));return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Script Editor",r=space(),i=element("div"),o=element("button"),a=text("🔄 Restart"),c=space(),l=element("button"),u=text("🗑️ Delete Script"),h=space(),p=element("div"),f=element("h4"),f.textContent="Upload Script",g=space(),y=element("div"),m=element("input"),b=space(),v=element("button"),_=text("📤 Upload & Update"),k=space(),E=element("div"),x=element("div"),$=element("span"),$.textContent="Status:",S=space(),T=element("span"),A=text(se),R=space(),ie&&ie.c(),N=space(),C=element("div"),I=element("span"),I.textContent="Script:",B=space(),P=element("span"),D=text(re),L=space(),F=element("div"),O=element("textarea"),U=space(),M=element("div"),K=element("button"),H=text("💾 Save & Update"),j=space(),V=element("button"),z=text("📥 Load Current"),q=space(),oe&&oe.c(),W=space(),G=element("div"),J=element("h3"),J.textContent="Script Versions",Z=space(),Y=element("div");for(let e=0;e<ce.length;e+=1)ce[e].c();X=space(),Q=element("button"),ee=text("🔄 Refresh Versions"),attr(o,"class","sprocket-btn restart-btn svelte-1a66x6i"),o.disabled=e[23],attr(l,"class","sprocket-btn delete-btn svelte-1a66x6i"),l.disabled=d=e[23]||!e[21]?.script_exists,attr(i,"class","sprocket-controls svelte-1a66x6i"),attr(n,"class","sprocket-header svelte-1a66x6i"),attr(f,"class","svelte-1a66x6i"),attr(m,"type","file"),attr(m,"id","sprocket-upload-file"),attr(m,"accept",".sh,.bash"),m.disabled=e[23],attr(m,"class","svelte-1a66x6i"),attr(v,"class","sprocket-btn upload-btn svelte-1a66x6i"),v.disabled=w=e[23]||!e[26],attr(y,"class","upload-controls svelte-1a66x6i"),attr(p,"class","sprocket-upload-section svelte-1a66x6i"),attr($,"class","status-label svelte-1a66x6i"),attr(T,"class","status-value svelte-1a66x6i"),toggle_class(T,"running",e[21]?.is_running),attr(x,"class","status-item svelte-1a66x6i"),attr(I,"class","status-label svelte-1a66x6i"),attr(P,"class","status-value svelte-1a66x6i"),attr(C,"class","status-item svelte-1a66x6i"),attr(E,"class","sprocket-status svelte-1a66x6i"),attr(O,"class","script-editor svelte-1a66x6i"),attr(O,"placeholder","#!/bin/bash # Enter your sprocket script here..."),O.disabled=e[23],attr(F,"class","script-editor-container svelte-1a66x6i"),attr(K,"class","sprocket-btn save-btn svelte-1a66x6i"),K.disabled=e[23],attr(V,"class","sprocket-btn load-btn svelte-1a66x6i"),V.disabled=e[23],attr(M,"class","script-actions svelte-1a66x6i"),attr(t,"class","sprocket-section svelte-1a66x6i"),attr(Y,"class","versions-list svelte-1a66x6i"),attr(Q,"class","sprocket-btn refresh-btn svelte-1a66x6i"),Q.disabled=e[23],attr(G,"class","sprocket-section svelte-1a66x6i")},m(d,w){insert(d,t,w),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(t,h),append(t,p),append(p,f),append(p,g),append(p,y),append(y,m),append(y,b),append(y,v),append(v,_),append(t,k),append(t,E),append(E,x),append(x,$),append(x,S),append(x,T),append(T,A),append(E,R),ie&&ie.m(E,null),append(E,N),append(E,C),append(C,I),append(C,B),append(C,P),append(P,D),append(t,L),append(t,F),append(F,O),set_input_value(O,e[20]),append(t,U),append(t,M),append(M,K),append(K,H),append(M,j),append(M,V),append(V,z),append(t,q),oe&&oe.m(t,null),insert(d,W,w),insert(d,G,w),append(G,J),append(G,Z),append(G,Y);for(let e=0;e<ce.length;e+=1)ce[e]&&ce[e].m(Y,null);append(G,X),append(G,Q),append(Q,ee),te||(ne=[listen(o,"click",e[48]),listen(l,"click",e[49]),listen(m,"change",e[53]),listen(v,"click",e[54]),listen(O,"input",e[96]),listen(K,"click",e[47]),listen(V,"click",e[46]),listen(Q,"click",e[50])],te=!0)},p(e,n){if(8388608&n[0]&&(o.disabled=e[23]),10485760&n[0]&&d!==(d=e[23]||!e[21]?.script_exists)&&(l.disabled=d),8388608&n[0]&&(m.disabled=e[23]),75497472&n[0]&&w!==(w=e[23]||!e[26])&&(v.disabled=w),2097152&n[0]&&se!==(se=e[21]?.is_running?"🟢 Running":"🔴 Stopped")&&set_data(A,se),2097152&n[0]&&toggle_class(T,"running",e[21]?.is_running),e[21]?.pid?ie?ie.p(e,n):(ie=create_if_block_34(e),ie.c(),ie.m(E,N)):ie&&(ie.d(1),ie=null),2097152&n[0]&&re!==(re=e[21]?.script_exists?"✅ Exists":"❌ Not found")&&set_data(D,re),8388608&n[0]&&(O.disabled=e[23]),1048576&n[0]&&set_input_value(O,e[20]),8388608&n[0]&&(K.disabled=e[23]),8388608&n[0]&&(V.disabled=e[23]),e[24]?oe?oe.p(e,n):(oe=create_if_block_33(e),oe.c(),oe.m(t,null)):oe&&(oe.d(1),oe=null),12582912&n[0]|3145728&n[1]){let t;for(ae=e[22],t=0;t<ae.length;t+=1){const s=get_each_context_2(e,ae,t);ce[t]?ce[t].p(s,n):(ce[t]=create_each_block_2(s),ce[t].c(),ce[t].m(Y,null))}for(;t<ce.length;t+=1)ce[t].d(1);ce.length=ae.length}8388608&n[0]&&(Q.disabled=e[23])},d(e){e&&detach(t),ie&&ie.d(),oe&&oe.d(),e&&detach(W),e&&detach(G),destroy_each(ce,e),te=!1,run_all(ne)}}}function create_if_block_34(e){let t,n,s,r,i,o=e[21].pid+"";return{c(){t=element("div"),n=element("span"),n.textContent="PID:",s=space(),r=element("span"),i=text(o),attr(n,"class","status-label svelte-1a66x6i"),attr(r,"class","status-value svelte-1a66x6i"),attr(t,"class","status-item svelte-1a66x6i")},m(e,o){insert(e,t,o),append(t,n),append(t,s),append(t,r),append(r,i)},p(e,t){2097152&t[0]&&o!==(o=e[21].pid+"")&&set_data(i,o)},d(e){e&&detach(t)}}}function create_if_block_33(e){let t,n;return{c(){t=element("div"),n=text(e[24]),attr(t,"class","sprocket-message svelte-1a66x6i"),toggle_class(t,"error","error"===e[25])},m(e,s){insert(e,t,s),append(t,n)},p(e,s){16777216&s[0]&&set_data(n,e[24]),33554432&s[0]&&toggle_class(t,"error","error"===e[25])},d(e){e&&detach(t)}}}function create_if_block_32(e){let t;return{c(){t=element("span"),t.textContent="Current",attr(t,"class","current-badge svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_31(e){let t,n,s,r;function i(){return e[98](e[151])}return{c(){t=element("button"),n=text("🗑️ Delete"),attr(t,"class","version-btn delete-btn svelte-1a66x6i"),t.disabled=e[23]},m(e,o){insert(e,t,o),append(t,n),s||(r=listen(t,"click",i),s=!0)},p(n,s){e=n,8388608&s[0]&&(t.disabled=e[23])},d(e){e&&detach(t),s=!1,r()}}}function create_each_block_2(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m=e[151].name+"",b=new Date(e[151].modified).toLocaleString()+"",v=e[151].is_current&&create_if_block_32();function _(){return e[97](e[151])}let w=!e[151].is_current&&create_if_block_31(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=text(m),i=space(),o=element("div"),a=text(b),c=space(),v&&v.c(),l=space(),u=element("div"),d=element("button"),h=text("📥 Load"),p=space(),w&&w.c(),f=space(),attr(s,"class","version-name svelte-1a66x6i"),attr(o,"class","version-date svelte-1a66x6i"),attr(n,"class","version-info svelte-1a66x6i"),attr(d,"class","version-btn load-btn svelte-1a66x6i"),d.disabled=e[23],attr(u,"class","version-actions svelte-1a66x6i"),attr(t,"class","version-item svelte-1a66x6i"),toggle_class(t,"current",e[151].is_current)},m(e,m){insert(e,t,m),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),append(o,a),append(o,c),v&&v.m(o,null),append(t,l),append(t,u),append(u,d),append(d,h),append(u,p),w&&w.m(u,null),append(t,f),g||(y=listen(d,"click",_),g=!0)},p(n,s){e=n,4194304&s[0]&&m!==(m=e[151].name+"")&&set_data(r,m),4194304&s[0]&&b!==(b=new Date(e[151].modified).toLocaleString()+"")&&set_data(a,b),e[151].is_current?v||(v=create_if_block_32(),v.c(),v.m(o,null)):v&&(v.d(1),v=null),8388608&s[0]&&(d.disabled=e[23]),e[151].is_current?w&&(w.d(1),w=null):w?w.p(e,s):(w=create_if_block_31(e),w.c(),w.m(u,null)),4194304&s[0]&&toggle_class(t,"current",e[151].is_current)},d(e){e&&detach(t),v&&v.d(),w&&w.d(),g=!1,y()}}}function create_else_block_6(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in with owner permissions to access\n managed ACL configuration.",s=space(),r=element("button"),r.textContent="Log In",attr(r,"class","login-btn svelte-1a66x6i"),attr(t,"class","access-denied")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[57]),i=!0)},p:noop,i:noop,o:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_28(e){let t,n;return t=new ManagedACL({props:{userSigner:e[12],userPubkey:e[2]}}),{c(){create_component(t.$$.fragment)},m(e,s){mount_component(t,e,s),n=!0},p(e,n){const s={};4096&n[0]&&(s.userSigner=e[12]),4&n[0]&&(s.userPubkey=e[2]),t.$set(s)},i(e){n||(transition_in(t.$$.fragment,e),n=!0)},o(e){transition_out(t.$$.fragment,e),n=!1},d(e){destroy_component(t,e)}}}function create_if_block_27(e){let t,n,s,r,i,o,a,c,l,u,d,h=(e[9]||"unknown")+"";return{c(){t=element("div"),n=element("h3"),n.textContent="⚠️ Managed ACL Mode Not Active",s=space(),r=element("p"),r.textContent='To use the Managed ACL interface, you need to set\n the ACL mode to "managed" in your relay\n configuration.',i=space(),o=element("p"),a=text("Current ACL mode: "),c=element("strong"),l=text(h),u=space(),d=element("p"),d.innerHTML='Please set <code class="svelte-1a66x6i">ORLY_ACL_MODE=managed</code> in your\n environment variables and restart the relay.',attr(n,"class","svelte-1a66x6i"),attr(r,"class","svelte-1a66x6i"),attr(o,"class","svelte-1a66x6i"),attr(d,"class","svelte-1a66x6i"),attr(t,"class","acl-mode-warning svelte-1a66x6i")},m(e,h){insert(e,t,h),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(o,a),append(o,c),append(c,l),append(t,u),append(t,d)},p(e,t){512&t[0]&&h!==(h=(e[9]||"unknown")+"")&&set_data(l,h)},i:noop,o:noop,d(e){e&&detach(t)}}}function create_else_block_5(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-1a66x6i">❌ Write, admin, or owner permission required to\n view all events.</p>',attr(t,"class","permission-denied svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_16(e){let t,n,s,r,i;function o(e,t){return e[34].length>0?create_if_block_19:e[18]?void 0:create_if_block_24}let a=o(e),c=a&&a(e),l=e[18]&&create_if_block_18(),u=!e[19]&&e[7].length>0&&create_if_block_17();return{c(){t=element("div"),c&&c.c(),n=space(),l&&l.c(),s=space(),u&&u.c(),attr(t,"class","events-view-content svelte-1a66x6i")},m(o,a){insert(o,t,a),c&&c.m(t,null),append(t,n),l&&l.m(t,null),append(t,s),u&&u.m(t,null),r||(i=listen(t,"scroll",e[74]),r=!0)},p(e,r){a===(a=o(e))&&c?c.p(e,r):(c&&c.d(1),c=a&&a(e),c&&(c.c(),c.m(t,n))),e[18]?l||(l=create_if_block_18(),l.c(),l.m(t,s)):l&&(l.d(1),l=null),!e[19]&&e[7].length>0?u||(u=create_if_block_17(),u.c(),u.m(t,null)):u&&(u.d(1),u=null)},d(e){e&&detach(t),c&&c.d(),l&&l.d(),u&&u.d(),r=!1,i()}}}function create_if_block_24(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-1a66x6i">No events found.</p>',attr(t,"class","no-events svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_19(e){let t,n=e[34],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block(get_each_context(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(131092&r[0]|712&r[1]){let i;for(n=e[34],i=0;i<n.length;i+=1){const o=get_each_context(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_else_block_4(e){let t,n,s=truncateContent(e[145].content)+"";return{c(){t=element("div"),n=text(s),attr(t,"class","event-content-single-line svelte-1a66x6i")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){8&t[1]&&s!==(s=truncateContent(e[145].content)+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_if_block_22(e){let t,n,s,r=e[145].tags&&e[145].tags.length>0&&create_if_block_23(e);return{c(){t=element("div"),n=element("span"),n.textContent="🗑️ Delete Event",s=space(),r&&r.c(),attr(n,"class","delete-event-label svelte-1a66x6i"),attr(t,"class","delete-event-info svelte-1a66x6i")},m(e,i){insert(e,t,i),append(t,n),append(t,s),r&&r.m(t,null)},p(e,n){e[145].tags&&e[145].tags.length>0?r?r.p(e,n):(r=create_if_block_23(e),r.c(),r.m(t,null)):r&&(r.d(1),r=null)},d(e){e&&detach(t),r&&r.d()}}}function create_if_block_23(e){let t,n=e[145].tags.filter(func_1),s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_1(get_each_context_1(e,n,t));return{c(){t=element("div");for(let e=0;e<s.length;e+=1)s[e].c();attr(t,"class","delete-targets svelte-1a66x6i")},m(e,n){insert(e,t,n);for(let e=0;e<s.length;e+=1)s[e]&&s[e].m(t,null)},p(e,r){if(8&r[1]){let i;for(n=e[145].tags.filter(func_1),i=0;i<n.length;i+=1){const o=get_each_context_1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_1(o),s[i].c(),s[i].m(t,null))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){e&&detach(t),destroy_each(s,e)}}}function create_each_block_1(e){let t,n,s,r,i,o=e[148][1].slice(0,8)+"",a=e[148][1].slice(-8)+"";return{c(){t=element("span"),n=text("Target: "),s=text(o),r=text("..."),i=text(a),attr(t,"class","delete-target svelte-1a66x6i")},m(e,o){insert(e,t,o),append(t,n),append(t,s),append(t,r),append(t,i)},p(e,t){8&t[1]&&o!==(o=e[148][1].slice(0,8)+"")&&set_data(s,o),8&t[1]&&a!==(a=e[148][1].slice(-8)+"")&&set_data(i,a)},d(e){e&&detach(t)}}}function create_if_block_21(e){let t,n,s;function r(){return e[87](e[145])}return{c(){t=element("button"),t.textContent="🗑️",attr(t,"class","delete-btn svelte-1a66x6i")},m(e,i){insert(e,t,i),n||(s=listen(t,"click",stop_propagation(r)),n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,s()}}}function create_if_block_20(e){let t,n,s,r,i,o,a,c,l=JSON.stringify(e[145],null,2)+"";function u(...t){return e[90](e[145],...t)}return{c(){t=element("div"),n=element("div"),s=element("pre"),r=text(l),i=space(),o=element("button"),o.textContent="📋",attr(s,"class","event-json svelte-1a66x6i"),attr(o,"class","copy-json-btn svelte-1a66x6i"),attr(o,"title","Copy minified JSON to clipboard"),attr(n,"class","json-container svelte-1a66x6i"),attr(t,"class","events-view-details svelte-1a66x6i")},m(e,l){insert(e,t,l),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),a||(c=listen(o,"click",stop_propagation(u)),a=!0)},p(t,n){e=t,8&n[1]&&l!==(l=JSON.stringify(e[145],null,2)+"")&&set_data(r,l)},d(e){e&&detach(t),a=!1,c()}}}function create_each_block(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$=truncatePubkey(e[145].pubkey)+"",S=e[145].kind+"",T=e[37](e[145].kind)+"",A=formatTimestamp(e[145].created_at)+"",R=e[17].has(e[145].id);function N(e,t){return 5===e[145].kind?create_if_block_22:create_else_block_4}let C=N(e),I=C(e),B=5!==e[145].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[145].pubkey&&e[145].pubkey===e[2])&&create_if_block_21(e);function P(){return e[88](e[145])}function D(...t){return e[89](e[145],...t)}let L=R&&create_if_block_20(e);return{c(){t=element("div"),n=element("div"),s=element("div"),s.innerHTML='<div class="avatar-placeholder svelte-1a66x6i">👤</div>',r=space(),i=element("div"),o=element("div"),a=text($),c=space(),l=element("div"),u=element("span"),d=text(S),h=space(),p=element("span"),f=text(T),g=space(),y=element("div"),m=element("div"),b=text(A),v=space(),I.c(),_=space(),B&&B.c(),w=space(),L&&L.c(),k=space(),attr(s,"class","events-view-avatar svelte-1a66x6i"),attr(o,"class","events-view-author svelte-1a66x6i"),attr(u,"class","kind-number svelte-1a66x6i"),toggle_class(u,"delete-event",5===e[145].kind),attr(p,"class","kind-name svelte-1a66x6i"),attr(l,"class","events-view-kind svelte-1a66x6i"),attr(i,"class","events-view-info svelte-1a66x6i"),attr(m,"class","event-timestamp svelte-1a66x6i"),attr(y,"class","events-view-content svelte-1a66x6i"),attr(n,"class","events-view-row svelte-1a66x6i"),attr(n,"role","button"),attr(n,"tabindex","0"),attr(t,"class","events-view-item svelte-1a66x6i"),toggle_class(t,"expanded",e[17].has(e[145].id))},m(e,$){insert(e,t,$),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(u,d),append(l,h),append(l,p),append(p,f),append(n,g),append(n,y),append(y,m),append(m,b),append(y,v),I.m(y,null),append(n,_),B&&B.m(n,null),append(t,w),L&&L.m(t,null),append(t,k),E||(x=[listen(n,"click",P),listen(n,"keydown",D)],E=!0)},p(s,r){e=s,8&r[1]&&$!==($=truncatePubkey(e[145].pubkey)+"")&&set_data(a,$),8&r[1]&&S!==(S=e[145].kind+"")&&set_data(d,S),8&r[1]&&toggle_class(u,"delete-event",5===e[145].kind),8&r[1]&&T!==(T=e[37](e[145].kind)+"")&&set_data(f,T),8&r[1]&&A!==(A=formatTimestamp(e[145].created_at)+"")&&set_data(b,A),C===(C=N(e))&&I?I.p(e,r):(I.d(1),I=C(e),I&&(I.c(),I.m(y,null))),5!==e[145].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[145].pubkey&&e[145].pubkey===e[2])?B?B.p(e,r):(B=create_if_block_21(e),B.c(),B.m(n,null)):B&&(B.d(1),B=null),131072&r[0]|8&r[1]&&(R=e[17].has(e[145].id)),R?L?L.p(e,r):(L=create_if_block_20(e),L.c(),L.m(t,k)):L&&(L.d(1),L=null),131072&r[0]|8&r[1]&&toggle_class(t,"expanded",e[17].has(e[145].id))},d(e){e&&detach(t),I.d(),B&&B.d(),L&&L.d(),E=!1,run_all(x)}}}function create_if_block_18(e){let t;return{c(){t=element("div"),t.innerHTML='<div class="loading-spinner svelte-1a66x6i"></div> \n <p class="svelte-1a66x6i">Loading events...</p>',attr(t,"class","loading-events svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_17(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-1a66x6i">No more events to load.</p>',attr(t,"class","end-of-events svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_14(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y;function m(e,t){return e[18]?create_if_block_15:create_else_block_3}let b=m(e),v=b(e);return{c(){t=element("div"),n=element("div"),s=element("label"),r=element("input"),i=space(),o=element("span"),a=space(),c=element("span"),c.textContent="Only show my events",l=space(),u=element("div"),d=element("button"),h=text("🔄 Load More"),p=space(),f=element("button"),v.c(),attr(r,"type","checkbox"),attr(r,"class","svelte-1a66x6i"),attr(o,"class","toggle-slider svelte-1a66x6i"),attr(c,"class","toggle-label svelte-1a66x6i"),attr(s,"class","toggle-container svelte-1a66x6i"),attr(n,"class","events-view-toggle svelte-1a66x6i"),attr(d,"class","refresh-btn svelte-1a66x6i"),d.disabled=e[18],attr(f,"class","reload-btn svelte-1a66x6i"),f.disabled=e[18],attr(u,"class","events-view-buttons svelte-1a66x6i"),attr(t,"class","events-view-header svelte-1a66x6i")},m(m,b){insert(m,t,b),append(t,n),append(n,s),append(s,r),r.checked=e[8],append(s,i),append(s,o),append(s,a),append(s,c),append(t,l),append(t,u),append(u,d),append(d,h),append(u,p),append(u,f),v.m(f,null),g||(y=[listen(r,"change",e[91]),listen(r,"change",e[92]),listen(d,"click",e[93]),listen(f,"click",e[94])],g=!0)},p(e,t){256&t[0]&&(r.checked=e[8]),262144&t[0]&&(d.disabled=e[18]),b!==(b=m(e))&&(v.d(1),v=b(e),v&&(v.c(),v.m(f,null))),262144&t[0]&&(f.disabled=e[18])},d(e){e&&detach(t),v.d(),g=!1,run_all(y)}}}function create_else_block_3(e){let t;return{c(){t=text("🔄")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_15(e){let t;return{c(){t=element("div"),attr(t,"class","spinner svelte-1a66x6i")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_else_block_2(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access import functionality.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-1a66x6i"),attr(r,"class","login-btn svelte-1a66x6i"),attr(t,"class","login-prompt svelte-1a66x6i")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[57]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_12(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-1a66x6i">❌ Admin or owner permission required for import\n functionality.</p>',attr(t,"class","permission-denied svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_11(e){let t,n,s,r,i,o,a,c,l,u,d;return{c(){t=element("h2"),t.textContent="Import Events",n=space(),s=element("p"),s.textContent="Upload a JSONL file to import events into the database.",r=space(),i=element("input"),o=space(),a=element("button"),c=text("📥 Import Events"),attr(t,"class","svelte-1a66x6i"),attr(i,"type","file"),attr(i,"id","import-file"),attr(i,"accept",".jsonl,.txt"),attr(i,"class","svelte-1a66x6i"),attr(a,"class","import-btn svelte-1a66x6i"),a.disabled=l=!e[16]},m(l,h){insert(l,t,h),insert(l,n,h),insert(l,s,h),insert(l,r,h),insert(l,i,h),insert(l,o,h),insert(l,a,h),append(a,c),u||(d=[listen(i,"change",e[71]),listen(a,"click",e[72])],u=!0)},p(e,t){65536&t[0]&&l!==(l=!e[16])&&(a.disabled=l)},d(e){e&&detach(t),e&&detach(n),e&&detach(s),e&&detach(r),e&&detach(i),e&&detach(o),e&&detach(a),u=!1,run_all(d)}}}function create_else_block_1(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access export functionality.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-1a66x6i"),attr(r,"class","login-btn svelte-1a66x6i"),attr(t,"class","login-prompt svelte-1a66x6i")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[57]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_8(e){let t,n,s,r,i,o,a,c,l,u,d=("admin"===e[4]||"owner"===e[4])&&create_if_block_9(e);return{c(){t=element("div"),n=element("h2"),n.textContent="Export My Events",s=space(),r=element("p"),r.textContent="Download your personal events as a JSONL file.",i=space(),o=element("button"),o.textContent="📤 Export My Events",a=space(),d&&d.c(),c=empty(),attr(r,"class","svelte-1a66x6i"),attr(o,"class","export-btn svelte-1a66x6i"),attr(t,"class","export-section svelte-1a66x6i")},m(h,p){insert(h,t,p),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),insert(h,a,p),d&&d.m(h,p),insert(h,c,p),l||(u=listen(o,"click",e[70]),l=!0)},p(e,t){"admin"===e[4]||"owner"===e[4]?d?d.p(e,t):(d=create_if_block_9(e),d.c(),d.m(c.parentNode,c)):d&&(d.d(1),d=null)},d(e){e&&detach(t),e&&detach(a),d&&d.d(e),e&&detach(c),l=!1,u()}}}function create_if_block_9(e){let t,n,s,r,i,o,a,c;return{c(){t=element("div"),n=element("h3"),n.textContent="Export All Events",s=space(),r=element("p"),r.textContent="Download the complete database as a JSONL file. This\n includes all events from all users.",i=space(),o=element("button"),o.textContent="📤 Export All Events",attr(n,"class","svelte-1a66x6i"),attr(r,"class","svelte-1a66x6i"),attr(o,"class","export-btn svelte-1a66x6i"),attr(t,"class","export-section svelte-1a66x6i")},m(l,u){insert(l,t,u),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),a||(c=listen(o,"click",e[69]),a=!0)},p:noop,d(e){e&&detach(t),a=!1,c()}}}function create_if_block(e){let t,n,s,r,i,o,a,c,l,u;function d(e,t){return e[3]?create_if_block_1:e[1]&&e[2]?create_if_block_6:void 0}let h=d(e),p=h&&h(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=element("h2"),r.textContent="Settings",i=space(),o=element("button"),o.textContent="✕",a=space(),c=element("div"),p&&p.c(),attr(r,"class","svelte-1a66x6i"),attr(o,"class","close-btn svelte-1a66x6i"),attr(s,"class","drawer-header svelte-1a66x6i"),attr(c,"class","drawer-content"),attr(n,"class","settings-drawer svelte-1a66x6i"),toggle_class(n,"dark-theme",e[0]),attr(t,"class","drawer-overlay svelte-1a66x6i"),attr(t,"role","button"),attr(t,"tabindex","0")},m(d,h){insert(d,t,h),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),p&&p.m(c,null),l||(u=[listen(o,"click",e[62]),listen(n,"click",stop_propagation(e[80])),listen(n,"keydown",stop_propagation(e[81])),listen(t,"click",e[62]),listen(t,"keydown",e[109])],l=!0)},p(e,t){h===(h=d(e))&&p?p.p(e,t):(p&&p.d(1),p=h&&h(e),p&&(p.c(),p.m(c,null))),1&t[0]&&toggle_class(n,"dark-theme",e[0])},d(e){e&&detach(t),p&&p.d(),l=!1,run_all(u)}}}function create_if_block_6(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y=e[2].slice(0,16)+"",m=e[2].slice(-8)+"";return{c(){t=element("div"),n=element("h3"),n.textContent="Profile Loading",s=space(),r=element("p"),r.textContent="Your profile metadata is being loaded...",i=space(),o=element("button"),o.textContent="Retry Loading Profile",a=space(),c=element("div"),l=element("strong"),l.textContent="Public Key:",u=space(),d=text(y),h=text("..."),p=text(m),attr(n,"class","svelte-1a66x6i"),attr(r,"class","svelte-1a66x6i"),attr(o,"class","retry-profile-btn svelte-1a66x6i"),attr(c,"class","user-pubkey-display svelte-1a66x6i"),attr(t,"class","profile-loading-section svelte-1a66x6i")},m(y,m){insert(y,t,m),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(t,a),append(t,c),append(c,l),append(c,u),append(c,d),append(c,h),append(c,p),f||(g=listen(o,"click",e[68]),f=!0)},p(e,t){4&t[0]&&y!==(y=e[2].slice(0,16)+"")&&set_data(d,y),4&t[0]&&m!==(m=e[2].slice(-8)+"")&&set_data(p,m)},d(e){e&&detach(t),f=!1,g()}}}function create_if_block_1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f=(e[3].name||"Unknown User")+"",g=e[3].banner&&create_if_block_5(e);function y(e,t){return e[3].picture?create_if_block_4:create_else_block}let m=y(e),b=m(e),v=e[3].nip05&&create_if_block_3(e),_=e[3].about&&create_if_block_2(e);return{c(){t=element("div"),n=element("div"),g&&g.c(),s=space(),r=element("button"),r.textContent="Log out",i=space(),b.c(),o=space(),a=element("div"),c=element("h3"),l=text(f),u=space(),v&&v.c(),d=space(),_&&_.c(),attr(r,"class","logout-btn floating svelte-1a66x6i"),attr(c,"class","profile-username svelte-1a66x6i"),attr(a,"class","name-row svelte-1a66x6i"),attr(n,"class","profile-hero svelte-1a66x6i"),attr(t,"class","profile-section svelte-1a66x6i")},m(f,y){insert(f,t,y),append(t,n),g&&g.m(n,null),append(n,s),append(n,r),append(n,i),b.m(n,null),append(n,o),append(n,a),append(a,c),append(c,l),append(a,u),v&&v.m(a,null),append(t,d),_&&_.m(t,null),h||(p=listen(r,"click",e[59]),h=!0)},p(e,r){e[3].banner?g?g.p(e,r):(g=create_if_block_5(e),g.c(),g.m(n,s)):g&&(g.d(1),g=null),m===(m=y(e))&&b?b.p(e,r):(b.d(1),b=m(e),b&&(b.c(),b.m(n,o))),8&r[0]&&f!==(f=(e[3].name||"Unknown User")+"")&&set_data(l,f),e[3].nip05?v?v.p(e,r):(v=create_if_block_3(e),v.c(),v.m(a,null)):v&&(v.d(1),v=null),e[3].about?_?_.p(e,r):(_=create_if_block_2(e),_.c(),_.m(t,null)):_&&(_.d(1),_=null)},d(e){e&&detach(t),g&&g.d(),b.d(),v&&v.d(),_&&_.d(),h=!1,p()}}}function create_if_block_5(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].banner)||attr(t,"src",n),attr(t,"alt","Profile banner"),attr(t,"class","profile-banner svelte-1a66x6i")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].banner)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_else_block(e){let t;return{c(){t=element("div"),t.textContent="👤",attr(t,"class","profile-avatar-placeholder overlap svelte-1a66x6i")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_4(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].picture)||attr(t,"src",n),attr(t,"alt","User avatar"),attr(t,"class","profile-avatar overlap svelte-1a66x6i")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].picture)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_if_block_3(e){let t,n,s=e[3].nip05+"";return{c(){t=element("span"),n=text(s),attr(t,"class","profile-nip05-inline svelte-1a66x6i")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){8&t[0]&&s!==(s=e[3].nip05+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_if_block_2(e){let t,n;return{c(){t=element("div"),n=element("p"),attr(n,"class","profile-about svelte-1a66x6i"),attr(t,"class","about-card svelte-1a66x6i")},m(s,r){insert(s,t,r),append(t,n),n.innerHTML=e[33]},p(e,t){4&t[1]&&(n.innerHTML=e[33])},d(e){e&&detach(t)}}}function create_fragment(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,_,w,k,E,x,$,S,T,A,R=e[0]?"☀️":"🌙";function N(e,t){return e[14]?create_if_block_57:create_else_block_14}let C=N(e),I=C(e);function B(e,t){return e[1]?create_if_block_55:create_else_block_13}let P=B(e),D=P(e),L=e[10],F=[];for(let t=0;t<L.length;t+=1)F[t]=create_each_block_9(get_each_context_9(e,L,t));const O=[create_if_block_7,create_if_block_10,create_if_block_13,create_if_block_25,create_if_block_26,create_if_block_29,create_if_block_36,create_if_block_45,create_else_block_10],U=[];function M(e,t){return 96&t[0]&&(v=null),"export"===e[5]?0:"import"===e[5]?1:"events"===e[5]?2:"compose"===e[5]?3:"managed-acl"===e[5]?4:"sprocket"===e[5]?5:"recovery"===e[5]?6:(null==v&&(v=!!e[6].some(e[82])),v?7:8)}_=M(e,[-1,-1,-1,-1,-1,-1]),w=U[_]=O[_](e);let K=e[13]&&create_if_block(e);function H(t){e[110](t)}let j={isDarkTheme:e[0]};return void 0!==e[11]&&(j.showModal=e[11]),x=new LoginModal({props:j}),binding_callbacks.push(()=>bind(x,"showModal",H)),x.$on("login",e[58]),x.$on("close",e[60]),{c(){t=element("header"),n=element("div"),s=element("img"),i=space(),I.c(),o=space(),a=element("button"),a.textContent="🔍",c=space(),l=element("button"),u=text(R),d=space(),D.c(),h=space(),p=element("div"),f=element("aside"),g=element("div"),y=element("div");for(let e=0;e<F.length;e+=1)F[e].c();m=space(),b=element("main"),w.c(),k=space(),K&&K.c(),E=space(),create_component(x.$$.fragment),src_url_equal(s.src,r="/orly.png")||attr(s,"src","/orly.png"),attr(s,"alt","ORLY Logo"),attr(s,"class","logo svelte-1a66x6i"),attr(a,"class","search-btn svelte-1a66x6i"),attr(l,"class","theme-toggle-btn svelte-1a66x6i"),attr(n,"class","header-content svelte-1a66x6i"),attr(t,"class","main-header svelte-1a66x6i"),toggle_class(t,"dark-theme",e[0]),attr(y,"class","tabs svelte-1a66x6i"),attr(g,"class","sidebar-content svelte-1a66x6i"),attr(f,"class","sidebar svelte-1a66x6i"),toggle_class(f,"dark-theme",e[0]),attr(b,"class","main-content svelte-1a66x6i"),attr(p,"class","app-container svelte-1a66x6i"),toggle_class(p,"dark-theme",e[0])},m(r,v){insert(r,t,v),append(t,n),append(n,s),append(n,i),I.m(n,null),append(n,o),append(n,a),append(n,c),append(n,l),append(l,u),append(n,d),D.m(n,null),insert(r,h,v),insert(r,p,v),append(p,f),append(f,g),append(g,y);for(let e=0;e<F.length;e+=1)F[e]&&F[e].m(y,null);append(p,m),append(p,b),U[_].m(b,null),insert(r,k,v),K&&K.m(r,v),insert(r,E,v),mount_component(x,r,v),S=!0,T||(A=[listen(a,"click",e[63]),listen(l,"click",e[56])],T=!0)},p(e,s){if(C===(C=N(e))&&I?I.p(e,s):(I.d(1),I=C(e),I&&(I.c(),I.m(n,o))),(!S||1&s[0])&&R!==(R=e[0]?"☀️":"🌙")&&set_data(u,R),P===(P=B(e))&&D?D.p(e,s):(D.d(1),D=P(e),D&&(D.c(),D.m(n,null))),(!S||1&s[0])&&toggle_class(t,"dark-theme",e[0]),1056&s[0]|16777216&s[1]|8&s[2]){let t;for(L=e[10],t=0;t<L.length;t+=1){const n=get_each_context_9(e,L,t);F[t]?F[t].p(n,s):(F[t]=create_each_block_9(n),F[t].c(),F[t].m(y,null))}for(;t<F.length;t+=1)F[t].d(1);F.length=L.length}(!S||1&s[0])&&toggle_class(f,"dark-theme",e[0]);let r=_;_=M(e,s),_===r?U[_].p(e,s):(group_outros(),transition_out(U[r],1,1,()=>{U[r]=null}),check_outros(),w=U[_],w?w.p(e,s):(w=U[_]=O[_](e),w.c()),transition_in(w,1),w.m(b,null)),(!S||1&s[0])&&toggle_class(p,"dark-theme",e[0]),e[13]?K?K.p(e,s):(K=create_if_block(e),K.c(),K.m(E.parentNode,E)):K&&(K.d(1),K=null);const i={};1&s[0]&&(i.isDarkTheme=e[0]),!$&&2048&s[0]&&($=!0,i.showModal=e[11],add_flush_callback(()=>$=!1)),x.$set(i)},i(e){S||(transition_in(w),transition_in(x.$$.fragment,e),S=!0)},o(e){transition_out(w),transition_out(x.$$.fragment,e),S=!1},d(e){e&&detach(t),I.d(),D.d(),e&&detach(h),e&&detach(p),destroy_each(F,e),U[_].d(),e&&detach(k),K&&K.d(e),e&&detach(E),destroy_component(x,e),T=!1,run_all(A)}}}function truncatePubkey(e){return e?e.slice(0,8)+"..."+e.slice(-8):"unknown"}function truncateContent(e,t=100){return e?e.length>t?e.slice(0,t)+"...":e:""}function formatTimestamp(e){return e?new Date(1e3*e).toLocaleString():""}async function copyEventToClipboard(e,t){try{const n=JSON.stringify(e);await navigator.clipboard.writeText(n);const s=t.target.closest(".copy-json-btn");if(s){const e=s.textContent;s.textContent="✅",s.style.backgroundColor="#4CAF50",setTimeout(()=>{s.textContent=e,s.style.backgroundColor=""},2e3)}}catch(n){console.error("Failed to copy to clipboard:",n);try{const n=document.createElement("textarea");n.value=JSON.stringify(e),document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n);const s=t.target.closest(".copy-json-btn");if(s){const e=s.textContent;s.textContent="✅",s.style.backgroundColor="#4CAF50",setTimeout(()=>{s.textContent=e,s.style.backgroundColor=""},2e3)}}catch(e){console.error("Fallback copy also failed:",e),alert("Failed to copy to clipboard. Please copy manually.")}}}function escapeHtml(e){return String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const func_1=e=>"e"===e[0],func_2=e=>"p"===e[0],func_3=e=>"p"===e[0];function instance(e,t,n){let s,r,i,o,a=!1,c=!1,l=!1,u="",d="",h=null,p="",f=null,g=!1,y="export",m=!1,b="",v=[],_=[],w=null,k=new Set,E=!1,x=!0,$=null,S=new Map,T=[],A=0;const R=3e5;let N=!1,C=[],I=!0,B=null,P="",D=null,L=[],F=!1,O="",U="info",M=!1,K=null,H="",j="",V=null,z="",q=[],W=!1,G=!0,J=null;const Z=[{value:0,label:"Profile Metadata (0)"},{value:3,label:"Follow List (3)"},{value:1e4,label:"Relay List Metadata (10000)"},{value:10001,label:"Mute List (10001)"},{value:10002,label:"Pin List (10002)"},{value:10003,label:"Bookmark List (10003)"},{value:10004,label:"Communities List (10004)"},{value:10005,label:"Public Chats List (10005)"},{value:10006,label:"Blocked Relays List (10006)"},{value:10007,label:"Search Relays List (10007)"},{value:10015,label:"Interests List (10015)"},{value:10030,label:"Emoji Sets (10030)"},{value:3e4,label:"Categorized People List (30000)"},{value:30001,label:"Categorized Bookmark List (30001)"},{value:30002,label:"Relay Sets (30002)"},{value:30003,label:"Bookmark Sets (30003)"},{value:30004,label:"Curation Sets (30004)"},{value:30008,label:"Profile Badges (30008)"},{value:30009,label:"Badge Definition (30009)"},{value:30015,label:"Interest Sets (30015)"},{value:30017,label:"Stall Definition (30017)"},{value:30018,label:"Product Definition (30018)"},{value:30019,label:"Marketplace UI/UX (30019)"},{value:30020,label:"Product Sold as Auction (30020)"},{value:30023,label:"Article (30023)"},{value:30024,label:"Draft Long-form Content (30024)"},{value:30030,label:"Emoji Sets (30030)"},{value:30078,label:"Application Specific Data (30078)"},{value:30311,label:"Live Event (30311)"},{value:30315,label:"User Statuses (30315)"},{value:30402,label:"Classified Listing (30402)"},{value:30403,label:"Draft Classified Listing (30403)"},{value:31922,label:"Date-based Calendar Event (31922)"},{value:31923,label:"Time-based Calendar Event (31923)"},{value:31924,label:"Calendar (31924)"},{value:31925,label:"Calendar Event RSVP (31925)"},{value:31989,label:"Handler Recommendation (31989)"},{value:31990,label:"Handler Information (31990)"},{value:32123,label:"WaveLake Track (32123)"},{value:34550,label:"Community Definition (34550)"}],Y={0:"ProfileMetadata",1:"TextNote",2:"RecommendRelay",3:"FollowList",4:"EncryptedDirectMessage",5:"EventDeletion",6:"Repost",7:"Reaction",8:"BadgeAward",13:"Seal",14:"PrivateDirectMessage",15:"ReadReceipt",16:"GenericRepost",40:"ChannelCreation",41:"ChannelMetadata",42:"ChannelMessage",43:"ChannelHideMessage",44:"ChannelMuteUser",1021:"Bid",1022:"BidConfirmation",1040:"OpenTimestamps",1059:"GiftWrap",1060:"GiftWrapWithKind4",1063:"FileMetadata",1311:"LiveChatMessage",1517:"BitcoinBlock",1808:"LiveStream",1971:"ProblemTracker",1984:"Reporting",1985:"Label",4550:"CommunityPostApproval",5e3:"JobRequestStart",5999:"JobRequestEnd",6e3:"JobResultStart",6999:"JobResultEnd",7e3:"JobFeedback",9041:"ZapGoal",9734:"ZapRequest",9735:"Zap",9882:"Highlights",1e4:"BlockList",10001:"PinList",10002:"RelayListMetadata",10003:"BookmarkList",10004:"CommunitiesList",10005:"PublicChatsList",10006:"BlockedRelaysList",10007:"SearchRelaysList",10015:"InterestsList",10030:"UserEmojiList",10050:"DMRelaysList",10096:"FileStorageServerList",13004:"JWTBinding",13194:"NWCWalletServiceInfo",19999:"ReplaceableEnd",2e4:"EphemeralStart",21e3:"LightningPubRPC",22242:"ClientAuthentication",23194:"WalletRequest",23195:"WalletResponse",23196:"WalletNotificationNip4",23197:"WalletNotification",24133:"NostrConnect",27235:"HTTPAuth",29999:"EphemeralEnd",3e4:"FollowSets",30001:"GenericLists",30002:"RelaySets",30003:"BookmarkSets",30004:"CurationSets",30008:"ProfileBadges",30009:"BadgeDefinition",30015:"InterestSets",30017:"StallDefinition",30018:"ProductDefinition",30019:"MarketplaceUIUX",30020:"ProductSoldAsAuction",30023:"LongFormContent",30024:"DraftLongFormContent",30030:"EmojiSets"};function X(e){k.has(e)?k.delete(e):k.add(e),n(17,k)}async function Q(){console.log("Toggle changed, showOnlyMyEvents:",N);const e=N&&l&&u?[u]:null;await we(!0,e)}async function ee(e){if(!l)return void alert("Please log in first");const t=_.find(t=>t.id===e);if(!t)return void alert("Event not found");if("admin"===p||"owner"===p||"write"===p&&t.pubkey&&t.pubkey===u){if(confirm("Are you sure you want to delete this event?"))try{if(!f)throw new Error("Signer not available for signing");const s={kind:5,created_at:Math.floor(Date.now()/1e3),tags:[["e",e]],content:""};console.log("Created delete event template:",s),console.log("User pubkey:",u),console.log("Target event:",t),console.log("Target event pubkey:",t.pubkey);const r=await f.signEvent(s);console.log("Signed delete event:",r),console.log("Signed delete event pubkey:",r.pubkey),console.log("Delete event tags:",r.tags);const i=`wss://${window.location.host}`;try{const e=await publishEventWithAuth(i,r,f,u);e.success?console.log("Delete event published successfully to ORLY relay"):console.error("Failed to publish delete event:",e.reason)}catch(e){console.error("Error publishing delete event:",e)}const o=t.pubkey&&t.pubkey===u;if(o){const t=await nostrClient.publish(r);if(console.log("Delete event published:",t),!(t.success&&t.okCount>0))throw new Error("No relays accepted the delete event");{await new Promise(e=>setTimeout(e,2e3));try{const n=await fetchEventById(e,{timeout:5e3});n?(console.warn("Event still exists after deletion attempt:",n),alert(`Warning: Delete event was accepted by ${t.okCount} relay(s), but the event still exists on the relay. This may indicate the relay does not properly handle delete events.`)):console.log("Event successfully deleted and verified")}catch(e){console.log("Could not fetch event after deletion (likely deleted):",e.message)}try{const t=await fetchDeleteEventsByTarget(e,{timeout:5e3});if(t.length>0){console.log(`Delete event verification: Found ${t.length} delete event(s) targeting ${e}`);const n=t.find(e=>e.pubkey&&e.pubkey===u);n?console.log("Our delete event found in database:",n.id):console.warn("Our delete event not found in database, but other delete events exist")}else console.warn("No delete events found in database for target event:",e)}catch(e){console.log("Could not verify delete event in database:",e.message)}n(7,_=_.filter(t=>t.id!==e)),C=C.filter(t=>t.id!==e),T=T.filter(t=>t.id!==e);for(const[t,n]of S)n.events&&(n.events=n.events.filter(t=>t.id!==e),S.set(t,n));re(),console.log("Reloading events to show delete event...");const s=N&&l&&u?[u]:null;await we(!0,s),alert(`Event deleted successfully (accepted by ${t.okCount} relay(s))`)}}else{const t=`wss://${window.location.host}/`,s=new NostrClient;await s.connectToRelay(t);const i=await s.publish(r);if(console.log("Delete event published to local relay only:",i),!(i.success&&i.okCount>0))throw new Error("Local relay did not accept the delete event");{await new Promise(e=>setTimeout(e,2e3));try{const t=await fetchEventById(e,{timeout:5e3});t?(console.warn("Event still exists after deletion attempt:",t),alert(`Warning: Delete event was accepted by ${i.okCount} relay(s), but the event still exists on the relay. This may indicate the relay does not properly handle delete events.`)):console.log("Event successfully deleted and verified")}catch(e){console.log("Could not fetch event after deletion (likely deleted):",e.message)}try{const t=await fetchDeleteEventsByTarget(e,{timeout:5e3});if(t.length>0){console.log(`Delete event verification: Found ${t.length} delete event(s) targeting ${e}`);const n=t.find(e=>e.pubkey&&e.pubkey===u);n?console.log("Our delete event found in database:",n.id):console.warn("Our delete event not found in database, but other delete events exist")}else console.warn("No delete events found in database for target event:",e)}catch(e){console.log("Could not verify delete event in database:",e.message)}n(7,_=_.filter(t=>t.id!==e)),C=C.filter(t=>t.id!==e),T=T.filter(t=>t.id!==e);for(const[t,n]of S)n.events&&(n.events=n.events.filter(t=>t.id!==e),S.set(t,n));re(),console.log("Reloading events to show delete event...");const t=N&&l&&u?[u]:null;await we(!0,t),alert("Event deleted successfully (local relay only - admin/owner deleting other user's event)")}}}catch(e){console.error("Failed to delete event:",e),alert("Failed to delete event: "+e.message)}}else alert("You do not have permission to delete this event")}async function te(){const e=z?parseInt(z):V;if(e&&l){console.log("Loading recovery events for kind:",e,"user:",u),n(31,W=!0);try{const t={kinds:[e],authors:[u],limit:100,tags:[["show_all_versions","true"]]};J&&(t.until=J),console.log("Recovery filters:",t);const s=await fetchAllEvents(t);console.log("Recovery events received:",s.length),console.log("Recovery events kinds:",s.map(e=>e.kind)),n(30,q=J?[...q,...s]:s),s.length>0?(J=Math.min(...s.map(e=>e.created_at)),n(32,G=100===s.length)):n(32,G=!1)}catch(e){console.error("Failed to load recovery events:",e)}finally{n(31,W=!1)}}}async function ne(e){if(l&&f)try{const t={kind:e.kind,content:e.content,tags:e.tags,created_at:Math.floor(Date.now()/1e3),pubkey:u};(await publishEventWithAuth(DEFAULT_RELAYS[0],t,f,u)).success?(alert("Event reposted successfully!"),n(30,q=[]),J=null,await te()):alert("Failed to repost event")}catch(e){console.error("Failed to repost event:",e),alert("Failed to repost event: "+e.message)}else alert("Please log in to repost events")}function se(e){n(28,V=e),n(29,z=""),n(30,q=[]),J=null,n(32,G=!0),te()}if("undefined"!=typeof localStorage){const e=localStorage.getItem("isDarkTheme");null!==e&&(a=JSON.parse(e));const t=localStorage.getItem("nostr_auth_method"),s=localStorage.getItem("nostr_pubkey");t&&s&&(l=!0,u=s,d=t,"extension"===t&&window.nostr&&(f=window.nostr),be(),ve()),function(){if("undefined"==typeof localStorage)return;try{const t=localStorage.getItem("app_state");if(t){const s=JSON.parse(t);s.selectedTab&&de.some(e=>e.id===s.selectedTab)&&n(5,y=s.selectedTab),s.expandedEvents&&n(17,k=new Set(s.expandedEvents)),s.globalEventsCache&&(T=s.globalEventsCache),s.globalCacheTimestamp&&(A=s.globalCacheTimestamp),void 0!==s.hasMoreEvents&&n(19,x=s.hasMoreEvents),s.oldestEventTimestamp&&($=s.oldestEventTimestamp),void 0!==s.hasMoreMyEvents&&(I=s.hasMoreMyEvents),s.oldestMyEventTimestamp&&(B=s.oldestMyEventTimestamp),T.length>0&&((e=A)&&Date.now()-e<R)&&n(7,_=T)}}catch(e){console.error("Failed to load persistent state:",e)}var e}(),async function(){try{const e=await fetch("/api/sprocket/config",{method:"GET",headers:{"Content-Type":"application/json"}});if(e.ok){const t=await e.json();n(78,M=t.enabled)}}catch(e){console.error("Error loading sprocket config:",e)}}()}function re(){if("undefined"==typeof localStorage)return;const e={selectedTab:y,expandedEvents:Array.from(k),globalEventsCache:T,globalCacheTimestamp:A,hasMoreEvents:x,oldestEventTimestamp:$};localStorage.setItem("app_state",JSON.stringify(e))}function ie(e){T=e.sort((e,t)=>t.created_at-e.created_at),A=Date.now(),re()}async function oe(){if(l&&"owner"===p&&M)try{n(23,F=!0);const e=await fetch("/api/sprocket/status",{method:"GET",headers:{Authorization:`Nostr ${await xe("GET","/api/sprocket/status")}`,"Content-Type":"application/json"}});e.ok?n(21,D=await e.json()):ue("Failed to load sprocket status","error")}catch(e){ue(`Error loading sprocket status: ${e.message}`,"error")}finally{n(23,F=!1)}}async function ae(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/versions",{method:"GET",headers:{Authorization:`Nostr ${await xe("GET","/api/sprocket/versions")}`,"Content-Type":"application/json"}});e.ok?n(22,L=await e.json()):ue("Failed to load versions","error")}catch(e){ue(`Error loading versions: ${e.message}`,"error")}finally{n(23,F=!1)}}async function ce(e){l&&"owner"===p&&(n(20,P=e.content),ue(`Loaded version: ${e.name}`,"success"))}async function le(e){if(l&&"owner"===p&&confirm(`Are you sure you want to delete version ${e}?`))try{n(23,F=!0);const t=await fetch("/api/sprocket/delete-version",{method:"POST",headers:{Authorization:`Nostr ${await xe("POST","/api/sprocket/delete-version")}`,"Content-Type":"application/json"},body:JSON.stringify({filename:e})});if(t.ok)ue(`Version ${e} deleted successfully`,"success"),await ae();else{ue(`Failed to delete version: ${await t.text()}`,"error")}}catch(e){ue(`Error deleting version: ${e.message}`,"error")}finally{n(23,F=!1)}}function ue(e,t="info"){n(24,O=e),n(25,U=t),setTimeout(()=>{n(24,O="")},5e3)}const de=[{id:"export",icon:"📤",label:"Export"},{id:"import",icon:"💾",label:"Import",requiresAdmin:!0},{id:"events",icon:"📡",label:"Events"},{id:"compose",icon:"✏️",label:"Compose"},{id:"recovery",icon:"🔄",label:"Recovery"},{id:"managed-acl",icon:"🛡️",label:"Managed ACL",requiresOwner:!0},{id:"sprocket",icon:"⚙️",label:"Sprocket",requiresOwner:!0}];function he(e){n(5,y=e),"sprocket"===e&&l&&"owner"===p&&M&&(oe(),ae()),re()}function pe(){n(13,g=!1)}function fe(e){n(6,v=v.filter(t=>t.id!==e)),S.delete(e),y===e&&n(5,y="export")}async function ge(e,t,n=!0){const s=S.get(e);if(s&&!s.isLoading){s.isLoading=!0,S.set(e,s);try{const r={limit:n?100:200,until:n?Math.floor(Date.now()/1e3):s.oldestTimestamp};console.log("Loading search results for query:",t,"with options:",r);const i=await searchEvents(t,r);if(console.log("Received search results:",i.length,"events"),s.events=n?i.sort((e,t)=>t.created_at-e.created_at):[...s.events,...i].sort((e,t)=>t.created_at-e.created_at),i.length>0){const e=Math.min(...i.map(e=>e.created_at));(!s.oldestTimestamp||e<s.oldestTimestamp)&&(s.oldestTimestamp=e)}s.hasMore=i.length===(n?100:200),s.isLoading=!1,S.set(e,s)}catch(t){console.error("Failed to load search results:",t),s.isLoading=!1,S.set(e,s),alert("Failed to load search results: "+t.message)}}}function ye(e,t){const{scrollTop:n,scrollHeight:s,clientHeight:r}=e.target;if(s-n-r<100){const e=S.get(t);e&&!e.isLoading&&e.hasMore&&async function(e){const t=v.find(t=>t.id===e);t&&await ge(e,t.query,!1)}(t)}}async function me(){if(l&&u&&!h)try{console.log("Auto-fetching profile for:",u),await initializeNostrClient(),n(3,h=await fetchUserProfile(u)),console.log("Profile auto-loaded:",h)}catch(e){console.error("Failed to auto-load profile:",e)}}async function be(){if(l&&u)try{const e=await fetch(`/api/permissions/${u}`);if(e.ok){const t=await e.json();n(4,p=t.permission||""),console.log("User role loaded:",p),console.log("Is owner?","owner"===p)}else console.error("Failed to fetch user role:",e.status),n(4,p="")}catch(e){console.error("Error fetching user role:",e),n(4,p="")}else n(4,p="")}async function ve(){try{const e=await fetch("/api/acl-mode");if(e.ok){const t=await e.json();n(9,H=t.acl_mode||""),console.log("ACL mode loaded:",H)}else console.error("Failed to fetch ACL mode:",e.status),n(9,H="")}catch(e){console.error("Error fetching ACL mode:",e),n(9,H="")}}async function _e(e=[]){if(l)if(0!==e.length||"admin"===p||"owner"===p)try{const t=await Ee("/api/export","POST"),n=await fetch("/api/export",{method:"POST",headers:{Authorization:t,"Content-Type":"application/json"},body:JSON.stringify({pubkeys:e})});if(!n.ok)throw new Error(`Export failed: ${n.status} ${n.statusText}`);const s=await n.blob(),r=window.URL.createObjectURL(s),i=document.createElement("a");i.href=r;const o=n.headers.get("Content-Disposition");let a="events.jsonl";if(o){const e=o.match(/filename="([^"]+)"/);e&&(a=e[1])}i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(r)}catch(e){console.error("Export failed:",e),alert("Export failed: "+e.message)}else alert("Admin or owner permission required to export all events");else alert("Please log in first")}async function we(e=!1,t=null){if(!l||"write"!==p&&"admin"!==p&&"owner"!==p)alert("Write, admin, or owner permission required");else if(!E){n(18,E=!0),e&&($=null);try{console.log("Loading events with authors filter:",t,"including delete events");const s=await fetchAllEvents({limit:e?100:200,until:e?Math.floor(Date.now()/1e3):$,authors:t});if(console.log("Received events:",s.length,"events"),t&&s.length>0){const e=s.filter(e=>e.pubkey&&e.pubkey!==u);e.length>0&&console.warn("Server returned non-user events:",e.length,"out of",s.length)}if(e?(n(7,_=s.sort((e,t)=>t.created_at-e.created_at)),ie(s)):(n(7,_=[..._,...s].sort((e,t)=>t.created_at-e.created_at)),ie(_)),s.length>0){const e=Math.min(...s.map(e=>e.created_at));(!$||e<$)&&($=e)}n(19,x=s.length===(e?1e3:200)),e&&x&&setTimeout(()=>{if("events"===y){const e=document.querySelectorAll(".events-view-content")[0];e&&e.scrollHeight<=e.clientHeight&&ke()}},100)}catch(e){console.error("Failed to load events:",e),alert("Failed to load events: "+e.message)}finally{n(18,E=!1)}}}async function ke(){await we(!1)}async function Ee(e,t){if(!l||!u)throw new Error("Not logged in");const n={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",window.location.origin+e],["method",t.toUpperCase()]],content:"",pubkey:u};let s;if(f&&"extension"===d)try{s=await f.signEvent(n)}catch(e){throw new Error("Failed to sign with extension: "+e.message)}else{if("nsec"!==d)throw new Error("No valid signer available");n.id="mock-id-"+Date.now(),n.sig="mock-signature-"+Date.now(),s=n}const r=JSON.stringify(s);return`Nostr ${btoa(r)}`}async function xe(e,t){if(!l||!u)throw new Error("Not logged in");const n={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",window.location.origin+t],["method",e.toUpperCase()]],content:"",pubkey:u};let s;if(f&&"extension"===d)try{s=await f.signEvent(n)}catch(e){throw new Error("Failed to sign with extension: "+e.message)}else{if("nsec"!==d)throw new Error("No valid signer available");n.id="mock-id-"+Date.now(),n.sig="mock-signature-"+Date.now(),s=n}const r=JSON.stringify(s);return btoa(r)}return e.$$.update=()=>{if(390&e.$$.dirty[0]&&n(34,s=(N&&l&&u?_.filter(e=>e.pubkey&&e.pubkey===u):_).sort((e,t)=>t.created_at-e.created_at)),8&e.$$.dirty[0]&&n(33,r=h?.about?escapeHtml(h.about).replace(/\n{2,}/g,"<br>"):""),530&e.$$.dirty[0]|65536&e.$$.dirty[2]&&n(79,i=de.filter(e=>!(e.requiresAdmin&&(!l||"admin"!==p&&"owner"!==p))&&(!(e.requiresOwner&&(!l||"owner"!==p))&&(!("sprocket"===e.id&&!M)&&(("managed-acl"!==e.id||"managed"===H)&&("managed-acl"===e.id&&console.log("Managed ACL tab check:",{isLoggedIn:l,userRole:p,requiresOwner:e.requiresOwner,aclMode:H}),!0)))))),64&e.$$.dirty[0]|131072&e.$$.dirty[2]&&n(10,o=[...i,...v]),1554&e.$$.dirty[0]|131072&e.$$.dirty[2]&&console.log("Tabs debug:",{isLoggedIn:l,userRole:p,aclMode:H,filteredBaseTabs:i.map(e=>e.id),allTabs:o.map(e=>e.id)}),1&e.$$.dirty[0]&&"undefined"!=typeof document&&(a?document.body.classList.add("dark-theme"):document.body.classList.remove("dark-theme")),14&e.$$.dirty[0]&&l&&u&&!h&&me(),438&e.$$.dirty[0]&&"events"===y&&l&&("write"===p||"admin"===p||"owner"===p)&&0===_.length){we(!0,N&&u?[u]:null)}},[a,l,u,h,p,y,v,_,N,H,o,c,f,g,m,b,w,k,E,x,P,D,L,F,O,U,K,j,V,z,q,W,G,r,s,S,Z,function(e){return Y[e]||`Kind ${e}`},X,Q,ee,te,ne,se,function(){z&&(n(28,V=null),n(30,q=[]),J=null,n(32,G=!0),te())},function(e){const t=q.filter(t=>t.kind===e.kind&&t.pubkey===e.pubkey),n=Math.max(...t.map(e=>e.created_at));return e.created_at===n},async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/status",{method:"GET",headers:{Authorization:`Nostr ${await xe("GET","/api/sprocket/status")}`,"Content-Type":"application/json"}});if(e.ok){const t=await e.json();n(20,P=t.script_content||""),n(21,D=t),ue("Script loaded successfully","success")}else ue("Failed to load script","error")}catch(e){ue(`Error loading script: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await xe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:P});if(e.ok)ue("Script saved and updated successfully","success"),await oe(),await ae();else{ue(`Failed to save script: ${await e.text()}`,"error")}}catch(e){ue(`Error saving script: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/restart",{method:"POST",headers:{Authorization:`Nostr ${await xe("POST","/api/sprocket/restart")}`,"Content-Type":"application/json"}});if(e.ok)ue("Sprocket restarted successfully","success"),await oe();else{ue(`Failed to restart sprocket: ${await e.text()}`,"error")}}catch(e){ue(`Error restarting sprocket: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p&&confirm("Are you sure you want to delete the sprocket script? This will stop the current process."))try{n(23,F=!0);const e=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await xe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:""});if(e.ok)n(20,P=""),ue("Sprocket script deleted successfully","success"),await oe(),await ae();else{ue(`Failed to delete script: ${await e.text()}`,"error")}}catch(e){ue(`Error deleting script: ${e.message}`,"error")}finally{n(23,F=!1)}},ae,ce,le,function(e){n(26,K=e.target.files[0])},async function(){if(l&&"owner"===p&&K)try{n(23,F=!0);const e=await K.text(),t=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await xe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:e});if(t.ok)n(20,P=e),ue("Script uploaded and updated successfully","success"),await oe(),await ae();else{ue(`Failed to upload script: ${await t.text()}`,"error")}}catch(e){ue(`Error uploading script: ${e.message}`,"error")}finally{n(23,F=!1),n(26,K=null);const e=document.getElementById("sprocket-upload-file");e&&(e.value="")}},he,function(){n(0,a=!a),"undefined"!=typeof localStorage&&localStorage.setItem("isDarkTheme",JSON.stringify(a))},function(){l||n(11,c=!0)},async function(e){const{method:t,pubkey:s,privateKey:r,signer:i}=e.detail;n(1,l=!0),n(2,u=s),d=t,n(12,f=i),n(11,c=!1);try{if(await initializeNostrClient(),"extension"===t&&i)nostrClient.setSigner(i);else if("nsec"===t&&r){const e=new NDKPrivateKeySigner(r);nostrClient.setSigner(e)}n(3,h=await fetchUserProfile(s)),console.log("Profile loaded:",h)}catch(e){console.error("Failed to load profile:",e)}await be(),await ve()},function(){n(1,l=!1),n(2,u=""),d="",n(3,h=null),n(4,p=""),n(12,f=null),n(13,g=!1),C=[],n(7,_=[]),T=[],A=0,re(),"undefined"!=typeof localStorage&&(localStorage.removeItem("nostr_auth_method"),localStorage.removeItem("nostr_pubkey"),localStorage.removeItem("nostr_privkey"))},function(){n(11,c=!1)},function(){n(13,g=!0)},pe,function(){n(14,m=!m),m||n(15,b="")},function(e){"Enter"===e.key&&b.trim()?(!function(e){const t=`search-${Date.now()}`,s={id:t,icon:"🔍",label:e,isSearchTab:!0,query:e};n(6,v=[...v,s]),n(5,y=t),S.set(t,{events:[],isLoading:!1,hasMore:!0,oldestTimestamp:null}),ge(t,e)}(b.trim()),n(15,b=""),n(14,m=!1)):"Escape"===e.key&&(n(14,m=!1),n(15,b=""))},fe,ge,ye,me,async function(){await _e([])},async function(){await _e([u])},function(e){n(16,w=e.target.files[0])},async function(){if(!l||"admin"!==p&&"owner"!==p)alert("Admin or owner permission required");else if(w)try{const e=await Ee("/api/import","POST"),t=new FormData;t.append("file",w);const s=await fetch("/api/import",{method:"POST",headers:{Authorization:e},body:t});if(!s.ok)throw new Error(`Import failed: ${s.status} ${s.statusText}`);await s.json();alert("Import started successfully"),n(16,w=null),document.getElementById("import-file").value=""}catch(e){console.error("Import failed:",e),alert("Import failed: "+e.message)}else alert("Please select a file")},we,function(e){const{scrollTop:t,scrollHeight:n,clientHeight:s}=e.target;n-t-s<100&&ke()},function(){try{if(!j.trim())return void alert("Please enter some JSON to reformat");const e=JSON.parse(j);n(27,j=JSON.stringify(e,null,2))}catch(e){alert("Invalid JSON: "+e.message)}},async function(){try{if(!j.trim())return void alert("Please enter an event to sign");if(!l||!u)return void alert("Please log in to sign events");if(!f)return void alert("No signer available. Please log in with a valid authentication method.");const e=JSON.parse(j);e.pubkey=u,e.created_at=Math.floor(Date.now()/1e3),delete e.id,delete e.sig;const t=await f.signEvent(e);n(27,j=JSON.stringify(t,null,2)),alert("Event signed successfully!")}catch(e){console.error("Error signing event:",e),alert("Error signing event: "+e.message)}},async function(){try{if(!j.trim())return void alert("Please enter an event to publish");if(!l)return void alert("Please log in to publish events");if(!f)return void alert("No signer available. Please log in with a valid authentication method.");const e=JSON.parse(j);if(!e.id||!e.sig)return void alert('Event must be signed before publishing. Please click "Sign" first.');const t=`wss://${window.location.host}`,n=await publishEventWithAuth(t,e,f,u);n.success?alert("Event published successfully to ORLY relay!"):alert(`Event publishing failed: ${n.reason||"Unknown error"}`)}catch(e){console.error("Error publishing event:",e),alert("Error publishing event: "+e.message)}},M,i,function(t){bubble.call(this,e,t)},function(t){bubble.call(this,e,t)},e=>e.id===y,function(){b=this.value,n(15,b)},e=>fe(e.id),(e,t)=>"Enter"===t.key&&fe(e.id),e=>he(e.id),e=>ee(e.id),e=>X(e.id),(e,t)=>"Enter"===t.key&&X(e.id),(e,t)=>copyEventToClipboard(e,t),function(){N=this.checked,n(8,N)},()=>Q(),()=>{we(!1,N&&u?[u]:null)},()=>{we(!0,N&&u?[u]:null)},function(){j=this.value,n(27,j)},function(){P=this.value,n(20,P)},e=>ce(e),e=>le(e.name),function(){V=select_value(this),n(28,V),n(36,Z)},()=>se(V),function(){z=to_number(this.value),n(29,z)},e=>ne(e),e=>ge(e.id,e.query,!0),e=>ee(e.id),e=>X(e.id),(e,t)=>"Enter"===t.key&&X(e.id),(e,t)=>copyEventToClipboard(e,t),(e,t)=>ye(t,e.id),e=>"Escape"===e.key&&pe(),function(e){c=e,n(11,c)}]}class App extends SvelteComponent{constructor(e){super(),init(this,e,instance,create_fragment,safe_not_equal,{},null,[-1,-1,-1,-1,-1,-1])}}const app=new App({target:document.body,props:{name:"world"}});return app}();
//# sourceMappingURL=bundle.js.map