holosphere 2.0.0-alpha21 → 2.0.0-alpha23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +1 -2
  2. package/dist/cjs/holosphere.cjs +1 -1
  3. package/dist/esm/holosphere.js +61 -58
  4. package/dist/{index-B6-8KAQm.js → index-BEkCLOwI.js} +2 -2
  5. package/dist/{index-B6-8KAQm.js.map → index-BEkCLOwI.js.map} +1 -1
  6. package/dist/{index-D2WstuZJ.js → index-BEvX6DxG.js} +2 -2
  7. package/dist/{index-D2WstuZJ.js.map → index-BEvX6DxG.js.map} +1 -1
  8. package/dist/{index--QsHG_gD.cjs → index-BGTOiJ2Y.cjs} +2 -2
  9. package/dist/{index--QsHG_gD.cjs.map → index-BGTOiJ2Y.cjs.map} +1 -1
  10. package/dist/{index-COpLk9gL.cjs → index-BH1woZXL.cjs} +2 -2
  11. package/dist/{index-COpLk9gL.cjs.map → index-BH1woZXL.cjs.map} +1 -1
  12. package/dist/{index-BHptWysv.js → index-Cvxov2jv.js} +2970 -7753
  13. package/dist/index-Cvxov2jv.js.map +1 -0
  14. package/dist/index-vTKI_BAX.cjs +29 -0
  15. package/dist/index-vTKI_BAX.cjs.map +1 -0
  16. package/dist/{indexeddb-storage-wKG4mICM.cjs → indexeddb-storage-BmnCNnSg.cjs} +2 -2
  17. package/dist/{indexeddb-storage-wKG4mICM.cjs.map → indexeddb-storage-BmnCNnSg.cjs.map} +1 -1
  18. package/dist/{indexeddb-storage-kQ53UHEE.js → indexeddb-storage-MIFisaPy.js} +2 -2
  19. package/dist/{indexeddb-storage-kQ53UHEE.js.map → indexeddb-storage-MIFisaPy.js.map} +1 -1
  20. package/dist/{memory-storage-CGC8xM2G.cjs → memory-storage-BJjK3F4r.cjs} +2 -2
  21. package/dist/{memory-storage-CGC8xM2G.cjs.map → memory-storage-BJjK3F4r.cjs.map} +1 -1
  22. package/dist/{memory-storage-DnXCSbBl.js → memory-storage-DhHXdKQ-.js} +2 -2
  23. package/dist/{memory-storage-DnXCSbBl.js.map → memory-storage-DhHXdKQ-.js.map} +1 -1
  24. package/examples/demo.html +2 -29
  25. package/package.json +3 -8
  26. package/src/content/social-protocols.js +3 -59
  27. package/src/core/holosphere.js +16 -554
  28. package/src/crypto/nostr-utils.js +98 -1
  29. package/src/crypto/secp256k1.js +4 -393
  30. package/src/federation/discovery.js +7 -75
  31. package/src/federation/handshake.js +69 -202
  32. package/src/federation/hologram.js +222 -298
  33. package/src/federation/index.js +2 -9
  34. package/src/federation/registry.js +67 -1257
  35. package/src/federation/request-card.js +21 -35
  36. package/src/hierarchical/upcast.js +4 -9
  37. package/src/index.js +145 -296
  38. package/src/lib/federation-methods.js +370 -909
  39. package/src/storage/global-tables.js +1 -1
  40. package/src/storage/nostr-wrapper.js +9 -5
  41. package/src/subscriptions/manager.js +1 -1
  42. package/types/index.d.ts +145 -37
  43. package/bin/holosphere-activitypub.js +0 -158
  44. package/dist/2019-BzVkRcax.js +0 -6680
  45. package/dist/2019-BzVkRcax.js.map +0 -1
  46. package/dist/2019-C1hPR_Os.cjs +0 -8
  47. package/dist/2019-C1hPR_Os.cjs.map +0 -1
  48. package/dist/browser-BcmACE3G.js +0 -3058
  49. package/dist/browser-BcmACE3G.js.map +0 -1
  50. package/dist/browser-DaqYUTcG.cjs +0 -2
  51. package/dist/browser-DaqYUTcG.cjs.map +0 -1
  52. package/dist/index-BHptWysv.js.map +0 -1
  53. package/dist/index-CDlhzxT2.cjs +0 -29
  54. package/dist/index-CDlhzxT2.cjs.map +0 -1
  55. package/src/federation/capabilities.js +0 -46
  56. package/src/storage/backend-factory.js +0 -130
  57. package/src/storage/backend-interface.js +0 -161
  58. package/src/storage/backends/activitypub/server.js +0 -675
  59. package/src/storage/backends/activitypub-backend.js +0 -295
  60. package/src/storage/backends/gundb-backend.js +0 -875
  61. package/src/storage/backends/nostr-backend.js +0 -251
  62. package/src/storage/gun-async.js +0 -341
  63. package/src/storage/gun-auth.js +0 -373
  64. package/src/storage/gun-federation.js +0 -785
  65. package/src/storage/gun-references.js +0 -209
  66. package/src/storage/gun-schema.js +0 -306
  67. package/src/storage/gun-wrapper.js +0 -642
  68. package/src/storage/migration.js +0 -351
  69. package/src/storage/unified-storage.js +0 -161
@@ -1,29 +0,0 @@
1
- "use strict";var __create=Object.create,__defProp2=Object.defineProperty,__getOwnPropDesc2=Object.getOwnPropertyDescriptor,__getOwnPropNames2=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp2=Object.prototype.hasOwnProperty,__copyProps2=(e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of __getOwnPropNames2(t))__hasOwnProp2.call(e,r)||r===n||__defProp2(e,r,{get:()=>t[r],enumerable:!(s=__getOwnPropDesc2(t,r))||s.enumerable});return e},__toESM=(e,t,n)=>(n=null!=e?__create(__getProtoOf(e)):{},__copyProps2(!t&&e&&e.__esModule?n:__defProp2(n,"default",{value:e,enumerable:!0}),e));const nostrTools=require("nostr-tools"),h3=require("h3-js"),Ajv=require("ajv");function _interopNamespaceDefault(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const n in e)if("default"!==n){const s=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,s.get?s:{enumerable:!0,get:()=>e[n]})}return t.default=e,Object.freeze(t)}const h3__namespace=_interopNamespaceDefault(h3);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$1={};Object.defineProperty(types$1,"__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(){return 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()}}(),exports2,__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,exports2=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(exports2,"__esModule",{value:!0}),__exportStar(taskCollection,exports2);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$1(e,t,n,s,r,i){var a=this.events[e];if(a){if(0===a.length)return!1;if(a.argsNum<6)a.call(t,n,s,r,i);else{for(var o=new Array(a.argsNum),l=0,c=o.length;l<c;++l)o[l]=arguments[l+1];a.call.apply(void 0,o)}return!0}return!1}function emitHasOnce(e,t,n,s,r,i){var a,o=this.events[e];if(void 0!==o){if(0===o.length)return!1;if(o.argsNum<6)o.call(t,n,s,r,i);else{for(var l=0,c=(a=new Array(o.argsNum)).length;l<c;++l)a[l]=arguments[l+1];o.call.apply(void 0,a)}}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===a)for(l=0,c=(a=new Array(arguments.length-1)).length;l<c;++l)a[l]=arguments[l+1];u.apply(void 0,a)}else{var d=u;if(this.onceEvents[e]=void 0,arguments.length<6)for(l=0;l<d.length;++l)d[l](t,n,s,r,i);else{if(void 0===a)for(l=0,c=(a=new Array(arguments.length-1)).length;l<c;++l)a[l]=arguments[l+1];for(l=0;l<d.length;++l)d[l].apply(void 0,a)}}return!0}return void 0!==o}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$1&&(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$1&&(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$1?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$1){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$1?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$1,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$1,e),n(ee,e)}(lib$1);var browser$1={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 a(e,t,n,s){var r=t>=1.5*n;return Math.round(e/n)+" "+s+(r?"s":"")}return ms=function(o,l){l=l||{};var c=typeof o;if("string"===c&&o.length>0)return function(a){if((a=String(a)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!o)return;var l=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*i;case"weeks":case"week":case"w":return l*r;case"days":case"day":case"d":return l*s;case"hours":case"hour":case"hrs":case"hr":case"h":return l*n;case"minutes":case"minute":case"mins":case"min":case"m":return l*t;case"seconds":case"second":case"secs":case"sec":case"s":return l*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(o);if("number"===c&&isFinite(o))return l.long?function(r){var i=Math.abs(r);if(i>=s)return a(r,i,s,"day");if(i>=n)return a(r,i,n,"hour");if(i>=t)return a(r,i,t,"minute");if(i>=e)return a(r,i,e,"second");return r+" ms"}(o):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"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}function setup(e){function t(e){let s,r,i,a=null;function o(...e){if(!o.enabled)return;const n=o,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 a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(s,r)=>{if("%%"===s)return"%";a++;const i=t.formatters[r];if("function"==typeof i){const t=e[a];s=i.call(n,t),e.splice(a,1),a--}return s}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=n,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(r!==t.namespaces&&(r=t.namespaces,i=t.enabled(e)),i),set:e=>{a=e}}),"function"==typeof t.init&&t.init(o),o}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 s of n)"-"===s[0]?t.skips.push(s.slice(1)):t.names.push(s)},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(n){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(n){}!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(t){return"[UnexpectedJSONParseError]: "+t.message}}}(browser$1,browser$1.exports);var browserExports=browser$1.exports;const createDebug2=getDefaultExportFromCjs(browserExports),crypto$2="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
2
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
- function isBytes$2(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$1(e,...t){if(!isBytes$2(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$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 aoutput$1(e,t){abytes$1(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function clean$1(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function createView$5(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rotr$4(e,t){return e<<32-t|e>>>t}const hasHexBuiltin$1=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hexes$3=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex$4(e){if(abytes$1(e),hasHexBuiltin$1)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=hexes$3[e[n]];return t}const asciis$1={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16$1(e){return e>=asciis$1._0&&e<=asciis$1._9?e-asciis$1._0:e>=asciis$1.A&&e<=asciis$1.F?e-(asciis$1.A-10):e>=asciis$1.a&&e<=asciis$1.f?e-(asciis$1.a-10):void 0}function hexToBytes$5(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(hasHexBuiltin$1)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 r=0,i=0;r<n;r++,i+=2){const t=asciiToBase16$1(e.charCodeAt(i)),n=asciiToBase16$1(e.charCodeAt(i+1));if(void 0===t||void 0===n){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}s[r]=16*t+n}return s}function utf8ToBytes$5(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function toBytes$5(e){return"string"==typeof e&&(e=utf8ToBytes$5(e)),abytes$1(e),e}function concatBytes$3(...e){let t=0;for(let s=0;s<e.length;s++){const n=e[s];abytes$1(n),t+=n.length}const n=new Uint8Array(t);for(let s=0,r=0;s<e.length;s++){const t=e[s];n.set(t,r),r+=t.length}return n}let Hash$4=class{};function createHasher$1(e){const t=t=>e().update(toBytes$5(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function randomBytes$3(e=32){if(crypto$2&&"function"==typeof crypto$2.getRandomValues)return crypto$2.getRandomValues(new Uint8Array(e));if(crypto$2&&"function"==typeof crypto$2.randomBytes)return Uint8Array.from(crypto$2.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$4(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),a=Number(n>>r&i),o=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,o,s)}function Chi$3(e,t,n){return e&t^~e&n}function Maj$3(e,t,n){return e&t^e&n^t&n}let HashMD$1=class extends Hash$4{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$5(this.buffer)}update(e){aexists$1(this),abytes$1(e=toBytes$5(e));const{view:t,buffer:n,blockLen:s}=this,r=e.length;for(let i=0;i<r;){const a=Math.min(s-this.pos,r-i);if(a===s){const t=createView$5(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists$1(this),aoutput$1(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:s,isLE:r}=this;let{pos:i}=this;t[i++]=128,clean$1(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let u=i;u<s;u++)t[u]=0;setBigUint64$4(n,s-8,BigInt(8*this.length),r),this.process(n,0);const a=createView$5(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,c[u],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:a}=this;return e.destroyed=i,e.finished=r,e.length=s,e.pos=a,s%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}};const SHA256_IV$1=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_K$3=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$3=new Uint32Array(64);let SHA256$3=class extends HashMD$1{constructor(e=32){super(64,e,8,!1),this.A=0|SHA256_IV$1[0],this.B=0|SHA256_IV$1[1],this.C=0|SHA256_IV$1[2],this.D=0|SHA256_IV$1[3],this.E=0|SHA256_IV$1[4],this.F=0|SHA256_IV$1[5],this.G=0|SHA256_IV$1[6],this.H=0|SHA256_IV$1[7]}get(){const{A:e,B:t,C:n,D:s,E:r,F:i,G:a,H:o}=this;return[e,t,n,s,r,i,a,o]}set(e,t,n,s,r,i,a,o){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|a,this.H=0|o}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W$3[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=SHA256_W$3[u-15],t=SHA256_W$3[u-2],n=rotr$4(e,7)^rotr$4(e,18)^e>>>3,s=rotr$4(t,17)^rotr$4(t,19)^t>>>10;SHA256_W$3[u]=s+SHA256_W$3[u-7]+n+SHA256_W$3[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(rotr$4(a,6)^rotr$4(a,11)^rotr$4(a,25))+Chi$3(a,o,l)+SHA256_K$3[u]+SHA256_W$3[u]|0,t=(rotr$4(n,2)^rotr$4(n,13)^rotr$4(n,22))+Maj$3(n,s,r)|0;c=l,l=o,o=a,a=i+e|0,i=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,s,r,i,a,o,l,c)}roundClean(){clean$1(SHA256_W$3)}destroy(){this.set(0,0,0,0,0,0,0,0),clean$1(this.buffer)}};const sha256$4=createHasher$1(()=>new SHA256$3);let HMAC$1=class extends Hash$4{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const n=toBytes$5(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 i=0;i<r.length;i++)r[i]^=54;this.iHash.update(r),this.oHash=e.create();for(let i=0;i<r.length;i++)r[i]^=106;this.oHash.update(r),clean$1(r)}update(e){return aexists$1(this),this.iHash.update(e),this}digestInto(e){aexists$1(this),abytes$1(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:a}=this;return e.finished=s,e.destroyed=r,e.blockLen=i,e.outputLen=a,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$1=(e,t,n)=>new HMAC$1(e,t).update(n).digest();hmac$1.create=(e,t)=>new HMAC$1(e,t);
4
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5
- const _0n$5=BigInt(0),_1n$5=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$2(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$5:BigInt("0x"+e)}function bytesToNumberBE(e){return hexToNumber(bytesToHex$4(e))}function bytesToNumberLE(e){return abytes$1(e),hexToNumber(bytesToHex$4(Uint8Array.from(e).reverse()))}function numberToBytesBE(e,t){return hexToBytes$5(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$5(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else{if(!isBytes$2(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$5<=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$5;e>>=_1n$5,t+=1);return t}const bitMask=e=>(_1n$5<<BigInt(e))-_1n$5;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),a=s(e),o=0;const l=()=>{i.fill(1),a.fill(0),o=0},c=(...e)=>n(a,i,...e),u=(e=s(0))=>{a=c(r(0),e),i=c(),0!==e.length&&(a=c(r(1),e),i=c())},d=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const n=[];for(;e<t;){i=c();const t=i.slice();n.push(t),e+=i.length}return concatBytes$3(...n)};return(e,t)=>{let n;for(l(),u(e);!(n=t(d()));)u();return l(),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}}
6
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$4=BigInt(1),_2n$3=BigInt(2),_3n$1=BigInt(3),_4n$1=BigInt(4),_5n=BigInt(5),_7n$1=BigInt(7),_8n=BigInt(8),_9n=BigInt(9),_16n=BigInt(16);function mod(e,t){const n=e%t;return n>=_0n$4?n:t+n}function pow2(e,t,n){let s=e;for(;t-- >_0n$4;)s*=s,s%=n;return s}function invert(e,t){if(e===_0n$4)throw new Error("invert: expected non-zero number");if(t<=_0n$4)throw new Error("invert: expected positive modulus, got "+t);let n=mod(e,t),s=t,r=_0n$4,i=_1n$4;for(;n!==_0n$4;){const e=s%n,t=r-i*(s/n);s=n,n=e,r=i,i=t}if(s!==_1n$4)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$4)/_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$3),r=e.pow(s,n),i=e.mul(t,r),a=e.mul(e.mul(i,_2n$3),r),o=e.mul(i,e.sub(a,e.ONE));return assertIsSquare(e,o,t),o}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)),a=(e+_7n$1)/_16n;return(e,t)=>{let n=e.pow(t,a),o=e.mul(n,s);const l=e.mul(n,r),c=e.mul(n,i),u=e.eql(e.sqr(o),t),d=e.eql(e.sqr(l),t);n=e.cmov(n,o,u),o=e.cmov(c,l,d);const f=e.eql(e.sqr(o),t),h=e.cmov(n,o,f);return assertIsSquare(e,h,t),h}}function tonelliShanks(e){if(e<_3n$1)throw new Error("sqrt is not defined for small field");let t=e-_1n$4,n=0;for(;t%_2n$3===_0n$4;)t/=_2n$3,n++;let s=_2n$3;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 a=(t+_1n$4)/_2n$3;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,o=e.mul(e.ONE,i),l=e.pow(s,t),c=e.pow(s,a);for(;!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;let t=1,n=e.sqr(l);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===r)throw new Error("Cannot find square root");const s=_1n$4<<BigInt(r-t-1),i=e.pow(o,s);r=t,o=e.sqr(i),l=e.mul(l,o),c=e.mul(c,i)}return c}}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$4)throw new Error("invalid exponent, negatives unsupported");if(n===_0n$4)return e.ONE;if(n===_1n$4)return t;let s=e.ONE,r=t;for(;n>_0n$4;)n&_1n$4&&(s=e.mul(s,r)),r=e.sqr(r),n>>=_1n$4;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$4)/_2n$3,s=e.pow(t,n),r=e.eql(s,e.ONE),i=e.eql(s,e.ZERO),a=e.eql(s,e.neg(e.ONE));if(!r&&!i&&!a)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$4)throw new Error("invalid field: expected ORDER > 0, got "+e);let r,i,a,o=!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&&(o=e.modFromBytes),a=e.allowedLengths}else"number"==typeof t&&(r=t),s.sqrt&&(i=s.sqrt);const{nBitLength:l,nByteLength:c}=nLength(e,r);if(c>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const d=Object.freeze({ORDER:e,isLE:n,BITS:l,BYTES:c,MASK:bitMask(l),ZERO:_0n$4,ONE:_1n$4,allowedLengths:a,create:t=>mod(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return _0n$4<=t&&t<e},is0:e=>e===_0n$4,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&_1n$4)===_1n$4,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,c):numberToBytesBE(e,c),fromBytes:(t,s=!0)=>{if(a){if(!a.includes(t.length)||t.length>c)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+t.length);const e=new Uint8Array(c);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==c)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+t.length);let r=n?bytesToNumberLE(t):bytesToNumberBE(t);if(o&&(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 a=mod(n?bytesToNumberLE(e):bytesToNumberBE(e),t-_1n$4)+_1n$4;return n?numberToBytesLE(a,r):numberToBytesBE(a,r)}
7
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$3=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:a}=n;let o=Number(e&r),l=e>>a;o>s&&(o-=i,l+=_1n$3);const c=t*s;return{nextN:l,offset:c+Math.abs(o)-1,isZero:0===o,isNeg:o<0,isNegF:t%2!=0,offsetF:c}}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$3)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$3;)t&_1n$3&&(n=n.add(s)),s=s.double(),t>>=_1n$3;return n}precomputeWindow(e,t){const{windows:n,windowSize:s}=calcWOpts(t,this.bits),r=[];let i=e,a=i;for(let o=0;o<n;o++){a=i,r.push(a);for(let e=1;e<s;e++)a=a.add(i),r.push(a);i=a.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 a=0;a<i.windows;a++){const{nextN:e,offset:o,isZero:l,isNeg:c,isNegF:u,offsetF:d}=calcOffsets(n,a,i);n=e,l?r=r.add(negateCt(u,t[d])):s=s.add(negateCt(c,t[o]))}return assert0(n),{p:s,f:r}}wNAFUnsafe(e,t,n,s=this.ZERO){const r=calcWOpts(e,this.bits);for(let i=0;i<r.windows&&n!==_0n$3;i++){const{nextN:e,offset:a,isZero:o,isNeg:l}=calcOffsets(n,i,r);if(n=e,!o){const e=t[a];s=s.add(l?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,a=e.ZERO;for(;n>_0n$3||s>_0n$3;)n&_1n$3&&(i=i.add(r)),s&_1n$3&&(a=a.add(r)),r=r.double(),n>>=_1n$3,s>>=_1n$3;return{p1:i,p2:a}}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 a=e.ZERO,o=bitLen(BigInt(r));let l=1;o>12?l=o-3:o>4?l=o-2:o>0&&(l=2);const c=bitMask(l),u=new Array(Number(c)+1).fill(a);let d=a;for(let f=Math.floor((t.BITS-1)/l)*l;f>=0;f-=l){u.fill(a);for(let t=0;t<i;t++){const e=s[t],r=Number(e>>BigInt(f)&c);u[r]=u[r].add(n[t])}let e=a;for(let t=u.length-1,n=a;t>0;t--)n=n.add(u[t]),e=e.add(n);if(d=d.add(e),0!==f)for(let t=0;t<l;t++)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 o of["p","n","h"]){const e=t[o];if(!("bigint"==typeof e&&e>_0n$3))throw new Error(`CURVE.${o} must be positive bigint`)}const r=createField(t.p,n.Fp,s),i=createField(t.n,n.Fn,s),a=["Gx","Gy","a","b"];for(const o of a)if(!r.isValid(t[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{CURVE:t=Object.freeze(Object.assign({},t)),Fp:r,Fn:i}}
8
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const divNearest=(e,t)=>(e+(e>=0?t:-t)/_2n$2)/t;function _splitEndoScalar(e,t,n){const[[s,r],[i,a]]=t,o=divNearest(a*e,n),l=divNearest(-r*e,n);let c=e-o*s-l*i,u=-o*r-l*a;const d=c<_0n$2,f=u<_0n$2;d&&(c=-c),f&&(u=-u);const h=bitMask(Math.ceil(bitLen(n)/2))+_1n$2;if(c<_0n$2||c>=h||u<_0n$2||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:c,k2neg:f,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 a=t.subarray(s,s+e);if(a.length!==e)throw new n("tlv.decode: length bytes not complete");if(0===a[0])throw new n("tlv.decode(long): zero leftmost byte");for(const t of a)i=i<<8|t;if(s+=e,i<128)throw new n("tlv.decode(long): not minimal encoding")}else i=r;const a=t.subarray(s,s+i);if(a.length!==i)throw new n("tlv.decode: wrong value length");return{v:a,l:t.subarray(s+i)}}},_int:{encode(e){const{Err:t}=DER;if(e<_0n$2)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:a}=s.decode(48,r);if(a.length)throw new t("invalid signature: left bytes after parsing");const{v:o,l:l}=s.decode(2,i),{v:c,l:u}=s.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:n.decode(o),s:n.decode(c)}},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$2=BigInt(0),_1n$2=BigInt(1),_2n$2=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 i=ensureBytes("private key",t);try{s=e.fromBytes(i)}catch(r){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:a,n:o}=i;_validateObject(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:l}=t;if(l&&(!s.is0(i.a)||"bigint"!=typeof l.beta||!Array.isArray(l.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const c=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(),a=s.toBytes(r);if(_abool2(n,"isCompressed"),n){u();return concatBytes$3(pprefix(!s.isOdd(i)),a)}return concatBytes$3(Uint8Array.of(4),a,s.toBytes(i))},f=t.fromBytes||function(e){_abytes2(e,void 0,"Point");const{publicKey:t,publicKeyUncompressed:n}=c,r=e.length,i=e[0],a=e.subarray(1);if(r!==t||2!==i&&3!==i){if(r===n&&4===i){const e=s.BYTES,t=s.fromBytes(a.subarray(0,e)),n=s.fromBytes(a.subarray(e,2*e));if(!p(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(a);if(!s.isValid(e))throw new Error("bad point: is not on curve, wrong x");const t=h(e);let n;try{n=s.sqrt(t)}catch(o){const e=o instanceof Error?": "+o.message:"";throw new Error("bad point: is not on curve, sqrt error"+e)}u();return!(1&~i)!==s.isOdd(n)&&(n=s.neg(n)),{x:e,y:n}}};function h(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 p(e,t){const n=s.sqr(t),r=h(e);return s.eql(n,r)}if(!p(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const y=s.mul(s.pow(i.a,_3n),_4n),g=s.mul(s.sqr(i.b),BigInt(27));if(s.is0(s.add(y,g)))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 A))throw new Error("ProjectivePoint expected")}function w(e){if(!l||!l.basises)throw new Error("no endo");return _splitEndoScalar(e,l.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 a=e.is0();null==t&&(t=a?s.ONE:s.inv(i));const o=s.mul(n,t),l=s.mul(r,t),c=s.mul(i,t);if(a)return{x:s.ZERO,y:s.ZERO};if(!s.eql(c,s.ONE))throw new Error("invZ was invalid");return{x:o,y:l}}),v=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(!p(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 E(e,t,n,r,i){return n=new A(s.mul(n.X,e),n.Y,n.Z),t=negateCt(r,t),n=negateCt(i,n),t.add(n)}class A{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 A)throw new Error("projective point not allowed");return s.is0(t)&&s.is0(n)?A.ZERO:new A(t,n,s.ONE)}static fromBytes(e){const t=A.fromAffine(f(_abytes2(e,void 0,"point")));return t.assertValidity(),t}static fromHex(e){return A.fromBytes(ensureBytes("pointHex",e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return k.createCache(this,e),t||this.multiply(_3n),this}assertValidity(){v(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:a,Z:o}=e,l=s.eql(s.mul(t,o),s.mul(i,r)),c=s.eql(s.mul(n,o),s.mul(a,r));return l&&c}negate(){return new A(this.X,s.neg(this.Y),this.Z)}double(){const{a:e,b:t}=i,n=s.mul(t,_3n),{X:r,Y:a,Z:o}=this;let l=s.ZERO,c=s.ZERO,u=s.ZERO,d=s.mul(r,r),f=s.mul(a,a),h=s.mul(o,o),p=s.mul(r,a);return p=s.add(p,p),u=s.mul(r,o),u=s.add(u,u),l=s.mul(e,u),c=s.mul(n,h),c=s.add(l,c),l=s.sub(f,c),c=s.add(f,c),c=s.mul(l,c),l=s.mul(p,l),u=s.mul(n,u),h=s.mul(e,h),p=s.sub(d,h),p=s.mul(e,p),p=s.add(p,u),u=s.add(d,d),d=s.add(u,d),d=s.add(d,h),d=s.mul(d,p),c=s.add(c,d),h=s.mul(a,o),h=s.add(h,h),d=s.mul(h,p),l=s.sub(l,d),u=s.mul(h,f),u=s.add(u,u),u=s.add(u,u),new A(l,c,u)}add(e){b(e);const{X:t,Y:n,Z:r}=this,{X:a,Y:o,Z:l}=e;let c=s.ZERO,u=s.ZERO,d=s.ZERO;const f=i.a,h=s.mul(i.b,_3n);let p=s.mul(t,a),y=s.mul(n,o),g=s.mul(r,l),m=s.add(t,n),w=s.add(a,o);m=s.mul(m,w),w=s.add(p,y),m=s.sub(m,w),w=s.add(t,r);let _=s.add(a,l);return w=s.mul(w,_),_=s.add(p,g),w=s.sub(w,_),_=s.add(n,r),c=s.add(o,l),_=s.mul(_,c),c=s.add(y,g),_=s.sub(_,c),d=s.mul(f,w),c=s.mul(h,g),d=s.add(c,d),c=s.sub(y,d),d=s.add(y,d),u=s.mul(c,d),y=s.add(p,p),y=s.add(y,p),g=s.mul(f,g),w=s.mul(h,w),y=s.add(y,g),g=s.sub(p,g),g=s.mul(f,g),w=s.add(w,g),p=s.mul(y,w),u=s.add(u,p),p=s.mul(_,w),c=s.mul(m,c),c=s.sub(c,p),p=s.mul(m,y),d=s.mul(_,d),d=s.add(d,p),new A(c,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(A.ZERO)}multiply(e){const{endo:n}=t;if(!r.isValidNot0(e))throw new Error("invalid scalar: out of range");let s,i;const a=e=>k.cached(this,e,e=>normalizeZ(A,e));if(n){const{k1neg:t,k1:r,k2neg:o,k2:l}=w(e),{p:c,f:u}=a(r),{p:d,f:f}=a(l);i=u.add(f),s=E(n.beta,c,d,t,o)}else{const{p:t,f:n}=a(e);s=t,i=n}return normalizeZ(A,[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$2||s.is0())return A.ZERO;if(e===_1n$2)return s;if(k.hasCache(this))return this.multiply(e);if(n){const{k1neg:t,k1:r,k2neg:i,k2:a}=w(e),{p1:o,p2:l}=mulEndoUnsafe(A,s,r,a);return E(n.beta,o,l,t,i)}return k.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 a===_1n$2||(e?e(A,this):k.unsafe(this,o).is0())}clearCofactor(){const{clearCofactor:e}=t;return a===_1n$2?this:e?e(A,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(e=!0){return _abool2(e,"isCompressed"),this.assertValidity(),d(A,this,e)}toHex(e=!0){return bytesToHex$4(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(A,e)}static msm(e,t){return pippenger(A,r,e,t)}static fromPrivateKey(e){return A.BASE.multiply(_normFnElement(r,e))}}A.BASE=new A(i.Gx,i.Gy,s.ONE),A.ZERO=new A(s.ZERO,s.ONE,s.ZERO),A.Fp=s,A.Fn=r;const S=r.BITS,k=new wNAF(A,t.endo?Math.ceil(S/2):S);return A.BASE.precompute(8),A}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$3,r=Object.assign(getWLengths(e.Fp,n),{seed:getMinHashLength(n.ORDER)});function i(e){try{return!!_normFnElement(n,e)}catch(t){return!1}}function a(e=s(r.seed)){return mapHashToField(_abytes2(e,r.seed,"seed"),n.ORDER)}function o(t,s=!0){return e.BASE.multiply(_normFnElement(n,t)).toBytes(s)}function l(t){if("bigint"==typeof t)return!1;if(t instanceof e)return!0;const{secretKey:s,publicKey:i,publicKeyUncompressed:a}=r;if(n.allowedLengths||s===i)return;const o=ensureBytes("key",t).length;return o===i||o===a}const c={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(a){return!1}},randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:e=>_normFnElement(n,e),precompute:(t=8,n=e.BASE)=>n.precompute(t,!1)};return Object.freeze({getPublicKey:o,getSharedSecret:function(t,s,r=!0){if(!0===l(t))throw new Error("first arg must be private key");if(!1===l(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=a(e);return{secretKey:t,publicKey:o(t)}},Point:e,utils:c,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$3,r=n.hmac||((e,...n)=>hmac$1(t,e,concatBytes$3(...n))),{Fp:i,Fn:a}=e,{ORDER:o,BITS:l}=a,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:f,lengths:h}=ecdh(e,n),p={prehash:!1,lowS:"boolean"==typeof n.lowS&&n.lowS,format:void 0,extraEntropy:!1},y="compact";function g(e){return e>o>>_1n$2}function m(e,t){if(!a.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=y){let n;if(function(e,t){validateSigFormat(t);const n=h.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=a.BYTES,r=e.subarray(0,s),i=e.subarray(s,2*s);return new b(a.fromBytes(r),a.fromBytes(i),n)}static fromHex(e,t){return this.fromBytes(hexToBytes$5(e),t)}addRecoveryBit(e){return new b(this.r,this.s,e)}recoverPublicKey(t){const n=i.ORDER,{r:s,s:r,recovery:l}=this;if(null==l||![0,1,2,3].includes(l))throw new Error("recovery id invalid");if(o*_2n$2<n&&l>1)throw new Error("recovery id is ambiguous for h>1 curve");const c=2===l||3===l?s+o:s;if(!i.isValid(c))throw new Error("recovery id 2 or 3 invalid");const u=i.toBytes(c),d=e.fromBytes(concatBytes$3(pprefix(!(1&l)),u)),f=a.inv(c),h=_(ensureBytes("msgHash",t)),p=a.create(-h*f),y=a.create(r*f),g=e.BASE.multiplyUnsafe(p).add(d.multiplyUnsafe(y));if(g.is0())throw new Error("point at infinify");return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=y){if(validateSigFormat(e),"der"===e)return hexToBytes$5(DER.hexFromSig(this));const t=a.toBytes(this.r),n=a.toBytes(this.s);if("recovered"===e){if(null==this.recovery)throw new Error("recovery bit must be present");return concatBytes$3(Uint8Array.of(this.recovery),t,n)}return concatBytes$3(t,n)}toHex(e){return bytesToHex$4(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,a.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return bytesToHex$4(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return bytesToHex$4(this.toBytes("compact"))}}const w=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const t=bytesToNumberBE(e),n=8*e.length-l;return n>0?t>>BigInt(n):t},_=n.bits2int_modN||function(e){return a.create(w(e))},v=bitMask(l);function E(e){return aInRange("num < 2^"+l,e,_0n$2,v),a.toBytes(e)}function A(e,n){return _abytes2(e,void 0,"message"),n?_abytes2(t(e),void 0,"prehashed message"):e}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:f,lengths:h,Point:e,sign:function(n,i,o={}){n=ensureBytes("message",n);const{seed:l,k2sig:c}=function(t,n,r){if(["recovered","canonical"].some(e=>e in r))throw new Error("sign() legacy options not supported");const{lowS:i,prehash:o,extraEntropy:l}=validateSigOpts(r,p);t=A(t,o);const c=_(t),u=_normFnElement(a,n),d=[E(u),E(c)];if(null!=l&&!1!==l){const e=!0===l?s(h.secretKey):l;d.push(ensureBytes("extraEntropy",e))}const f=concatBytes$3(...d),y=c;return{seed:f,k2sig:function(t){const n=w(t);if(!a.isValidNot0(n))return;const s=a.inv(n),r=e.BASE.multiply(n).toAffine(),o=a.create(r.x);if(o===_0n$2)return;const l=a.create(s*a.create(y+o*u));if(l===_0n$2)return;let c=(r.x===o?0:2)|Number(r.y&_1n$2),d=l;return i&&g(l)&&(d=a.neg(l),c^=1),new b(o,d,c)}}}(n,i,o);return createHmacDrbg(t.outputLen,a.BYTES,r)(l,c)},verify:function(t,n,s,r={}){const{lowS:i,prehash:o,format:l}=validateSigOpts(r,p);if(s=ensureBytes("publicKey",s),n=A(ensureBytes("message",n),o),"strict"in r)throw new Error("options.strict was renamed to lowS");const c=void 0===l?function(e){let t;const n="string"==typeof e||isBytes$2(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(r){if(!(r instanceof DER.Err))throw r}if(!t)try{t=b.fromBytes(ensureBytes("sig",e),"compact")}catch(i){return!1}}return t||!1}(t):b.fromBytes(ensureBytes("sig",t),l);if(!1===c)return!1;try{const t=e.fromBytes(s);if(i&&c.hasHighS())return!1;const{r:r,s:o}=c,l=_(n),u=a.inv(o),d=a.create(l*u),f=a.create(r*u),h=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(f));if(h.is0())return!1;return a.create(h.x)===r}catch(u){return!1}},recoverPublicKey:function(e,t,n={}){const{prehash:s}=validateSigOpts(n,p);return t=A(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))}
9
- /*! 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}}
10
- /*! 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$1=BigInt(0),_1n$1=BigInt(1),_2n$1=BigInt(2);function sqrtMod(e){const t=secp256k1_CURVE.p,n=BigInt(3),s=BigInt(6),r=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),l=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=pow2(u,n,t)*u%t,f=pow2(d,n,t)*u%t,h=pow2(f,_2n$1,t)*c%t,p=pow2(h,r,t)*h%t,y=pow2(p,i,t)*p%t,g=pow2(y,o,t)*y%t,m=pow2(g,l,t)*g%t,b=pow2(m,o,t)*y%t,w=pow2(b,n,t)*u%t,_=pow2(w,a,t)*p%t,v=pow2(_,s,t)*c%t,E=pow2(v,_2n$1,t);if(!Fpk1.eql(Fpk1.sqr(E),e))throw new Error("Cannot find square root");return E}const Fpk1=Field(secp256k1_CURVE.p,{sqrt:sqrtMod}),secp256k1$1=createCurve({...secp256k1_CURVE,Fp:Fpk1,lowS:!0,endo:secp256k1_ENDO},sha256$4),TAGGED_HASH_PREFIXES={};function taggedHash(e,...t){let n=TAGGED_HASH_PREFIXES[e];if(void 0===n){const t=sha256$4(utf8ToBytes$5(e));n=concatBytes$3(t,t),TAGGED_HASH_PREFIXES[e]=n}return sha256$4(concatBytes$3(n,...t))}const pointToBytes=e=>e.toBytes(!0).slice(1),Pointk1=(()=>secp256k1$1.Point)(),hasEven=e=>e%_2n$1===_0n$1;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$3(32)){const{Fn:s}=Pointk1,r=ensureBytes("message",e),{bytes:i,scalar:a}=schnorrGetExtPubKey(t),o=ensureBytes("auxRand",n,32),l=s.toBytes(a^num(taggedHash("BIP0340/aux",o))),c=taggedHash("BIP0340/nonce",l,i,r),{bytes:u,scalar:d}=schnorrGetExtPubKey(c),f=challenge(u,i,r),h=new Uint8Array(64);if(h.set(u,0),h.set(s.toBytes(s.create(d+f*a)),32),!schnorrVerify(h,r,i))throw new Error("sign: Invalid signature produced");return h}function schnorrVerify(e,t,n){const{Fn:s,BASE:r}=Pointk1,i=ensureBytes("signature",e,64),a=ensureBytes("message",t),o=ensureBytes("publicKey",n,32);try{const e=lift_x(num(o)),t=num(i.subarray(0,32));if(!inRange(t,_1n$1,secp256k1_CURVE.p))return!1;const n=num(i.subarray(32,64));if(!inRange(n,_1n$1,secp256k1_CURVE.n))return!1;const l=challenge(s.toBytes(t),pointToBytes(e),a),c=r.multiplyUnsafe(n).add(e.multiplyUnsafe(s.neg(l))),{x:u,y:d}=c.toAffine();return!(c.is0()||!hasEven(d)||u!==t)}catch(l){return!1}}const schnorr=(()=>{const e=(e=randomBytes$3(48))=>mapHashToField(e,secp256k1_CURVE.n);return secp256k1$1.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}}})();
11
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function isBytes$1(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function abytes(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+", got length="+e.length)}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$4(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function rotr$3(e,t){return e<<32-t|e>>>t}const hasHexBuiltin=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),hexes$2=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex$3(e){if(abytes(e),hasHexBuiltin)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=hexes$2[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$4(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 r=0,i=0;r<n;r++,i+=2){const t=asciiToBase16(e.charCodeAt(i)),n=asciiToBase16(e.charCodeAt(i+1));if(void 0===t||void 0===n){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}s[r]=16*t+n}return s}function utf8ToBytes$4(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function toBytes$4(e){return"string"==typeof e&&(e=utf8ToBytes$4(e)),abytes(e),e}let Hash$3=class{};function createHasher(e){const t=t=>e().update(toBytes$4(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}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),a=Number(n>>r&i),o=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,o,s)}function Chi$2(e,t,n){return e&t^~e&n}function Maj$2(e,t,n){return e&t^e&n^t&n}class HashMD extends Hash$3{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$4(this.buffer)}update(e){aexists(this),abytes(e=toBytes$4(e));const{view:t,buffer:n,blockLen:s}=this,r=e.length;for(let i=0;i<r;){const a=Math.min(s-this.pos,r-i);if(a===s){const t=createView$4(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){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 u=i;u<s;u++)t[u]=0;setBigUint64$3(n,s-8,BigInt(8*this.length),r),this.process(n,0);const a=createView$4(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,c[u],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:a}=this;return e.destroyed=i,e.finished=r,e.length=s,e.pos=a,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$2=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$2=new Uint32Array(64);let SHA256$2=class 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:a,H:o}=this;return[e,t,n,s,r,i,a,o]}set(e,t,n,s,r,i,a,o){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|a,this.H=0|o}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W$2[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=SHA256_W$2[u-15],t=SHA256_W$2[u-2],n=rotr$3(e,7)^rotr$3(e,18)^e>>>3,s=rotr$3(t,17)^rotr$3(t,19)^t>>>10;SHA256_W$2[u]=s+SHA256_W$2[u-7]+n+SHA256_W$2[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(rotr$3(a,6)^rotr$3(a,11)^rotr$3(a,25))+Chi$2(a,o,l)+SHA256_K$2[u]+SHA256_W$2[u]|0,t=(rotr$3(n,2)^rotr$3(n,13)^rotr$3(n,22))+Maj$2(n,s,r)|0;c=l,l=o,o=a,a=i+e|0,i=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,s,r,i,a,o,l,c)}roundClean(){clean(SHA256_W$2)}destroy(){this.set(0,0,0,0,0,0,0,0),clean(this.buffer)}};const sha256$3=createHasher(()=>new SHA256$2),sha256$2=sha256$3;var dist={},LRUCache$2={},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:a,onEntryMarkedAsMostRecentlyUsed:o,clone:l,cloneFn:c}=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!=l&&l,this.cloneFn=null!=c?c: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=a,this.onEntryMarkedAsMostRecentlyUsed=o}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$2,"__esModule",{value:!0}),LRUCache$2.LRUCache=void 0;const LRUCacheNode_1=LRUCacheNode$1;let LRUCache$1=class{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:a}=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=a,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 number$3(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool$2(e){if("boolean"!=typeof e)throw new Error(`Expected boolean, not ${e}`)}function bytes$3(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$2(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");number$3(e.outputLen),number$3(e.blockLen)}function exists$3(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$3(e,t){bytes$3(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}LRUCache$2.LRUCache=LRUCache$1,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$2,e)}(dist);const assert$2={number:number$3,bool:bool$2,bytes:bytes$3,hash:hash$2,exists:exists$3,output:output$3},crypto$1="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,u8a$2=e=>e instanceof Uint8Array,u32$2=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView$3=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr$2=(e,t)=>e<<32-t|e>>>t,isLE$3=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE$3)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$2(e){if(!u8a$2(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$3(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 s=0;s<n.length;s++){const t=2*s,r=e.slice(t,t+2),i=Number.parseInt(r,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[s]=i}return n}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 toBytes$3(e){if("string"==typeof e&&(e=utf8ToBytes$3(e)),!u8a$2(e))throw new Error("expected Uint8Array, got "+typeof e);return e}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$2(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t}let Hash$2=class{clone(){return this._cloneInto()}};const isPlainObject=e=>"[object Object]"===Object.prototype.toString.call(e)&&e.constructor===Object;function checkOpts$2(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$2(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$1&&"function"==typeof crypto$1.getRandomValues)return crypto$1.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}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),a=Number(n>>r&i),o=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,o,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){assert$2.exists(this);const{view:t,buffer:n,blockLen:s}=this,r=(e=toBytes$3(e)).length;for(let i=0;i<r;){const a=Math.min(s-this.pos,r-i);if(a===s){const t=createView$3(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){assert$2.exists(this),assert$2.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 u=i;u<s;u++)t[u]=0;setBigUint64$2(n,s-8,BigInt(8*this.length),r),this.process(n,0);const a=createView$3(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,c[u],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:a}=this;return e.length=s,e.pos=a,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$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$1=new Uint32Array(64);let SHA256$1=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:a,H:o}=this;return[e,t,n,s,r,i,a,o]}set(e,t,n,s,r,i,a,o){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|a,this.H=0|o}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W$1[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=SHA256_W$1[u-15],t=SHA256_W$1[u-2],n=rotr$2(e,7)^rotr$2(e,18)^e>>>3,s=rotr$2(t,17)^rotr$2(t,19)^t>>>10;SHA256_W$1[u]=s+SHA256_W$1[u-7]+n+SHA256_W$1[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(rotr$2(a,6)^rotr$2(a,11)^rotr$2(a,25))+Chi$1(a,o,l)+SHA256_K$1[u]+SHA256_W$1[u]|0,t=(rotr$2(n,2)^rotr$2(n,13)^rotr$2(n,22))+Maj$1(n,s,r)|0;c=l,l=o,o=a,a=i+e|0,i=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,s,r,i,a,o,l,c)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},SHA224$1=class 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$1=wrapConstructor$2(()=>new SHA256$1);wrapConstructor$2(()=>new SHA224$1);class HMAC extends Hash$2{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert$2.hash(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 i=0;i<r.length;i++)r[i]^=54;this.iHash.update(r),this.oHash=e.create();for(let i=0;i<r.length;i++)r[i]^=106;this.oHash.update(r),r.fill(0)}update(e){return assert$2.exists(this),this.iHash.update(e),this}digestInto(e){assert$2.exists(this),assert$2.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:a}=this;return e.finished=s,e.destroyed=r,e.blockLen=i,e.outputLen=a,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=(e,t,n)=>new HMAC(e,t).update(n).digest();function pbkdf2Init(e,t,n,s){assert$2.hash(e);const r=checkOpts$2({dkLen:32,asyncTick:10},s),{c:i,dkLen:a,asyncTick:o}=r;if(assert$2.number(i),assert$2.number(a),assert$2.number(o),i<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const l=toBytes$3(t),c=toBytes$3(n),u=new Uint8Array(a),d=hmac.create(e,l),f=d._cloneInto().update(c);return{c:i,dkLen:a,asyncTick:o,DK:u,PRF:d,PRFSalt:f}}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:a,PRF:o,PRFSalt:l}=pbkdf2Init(e,t,n,s);let c;const u=new Uint8Array(4),d=createView$3(u),f=new Uint8Array(o.outputLen);for(let h=1,p=0;p<i;h++,p+=o.outputLen){const e=a.subarray(p,p+o.outputLen);d.setInt32(0,h,!1),(c=l._cloneInto(c)).update(u).digestInto(f),e.set(f.subarray(0,e.length));for(let t=1;t<r;t++){o._cloneInto(c).update(f).digestInto(f);for(let t=0;t<e.length;t++)e[t]^=f[t]}}return pbkdf2Output(o,l,a,c,f)}hmac.create=(e,t)=>new HMAC(e,t);const rotl$1=(e,t)=>e<<t|e>>>32-t;function XorAndSalsa(e,t,n,s,r,i){let a=e[t++]^n[s++],o=e[t++]^n[s++],l=e[t++]^n[s++],c=e[t++]^n[s++],u=e[t++]^n[s++],d=e[t++]^n[s++],f=e[t++]^n[s++],h=e[t++]^n[s++],p=e[t++]^n[s++],y=e[t++]^n[s++],g=e[t++]^n[s++],m=e[t++]^n[s++],b=e[t++]^n[s++],w=e[t++]^n[s++],_=e[t++]^n[s++],v=e[t++]^n[s++],E=a,A=o,S=l,k=c,T=u,C=d,x=f,R=h,I=p,$=y,P=g,N=m,F=b,O=w,D=_,M=v;for(let B=0;B<8;B+=2)T^=rotl$1(E+F|0,7),I^=rotl$1(T+E|0,9),F^=rotl$1(I+T|0,13),E^=rotl$1(F+I|0,18),$^=rotl$1(C+A|0,7),O^=rotl$1($+C|0,9),A^=rotl$1(O+$|0,13),C^=rotl$1(A+O|0,18),D^=rotl$1(P+x|0,7),S^=rotl$1(D+P|0,9),x^=rotl$1(S+D|0,13),P^=rotl$1(x+S|0,18),k^=rotl$1(M+N|0,7),R^=rotl$1(k+M|0,9),N^=rotl$1(R+k|0,13),M^=rotl$1(N+R|0,18),A^=rotl$1(E+k|0,7),S^=rotl$1(A+E|0,9),k^=rotl$1(S+A|0,13),E^=rotl$1(k+S|0,18),x^=rotl$1(C+T|0,7),R^=rotl$1(x+C|0,9),T^=rotl$1(R+x|0,13),C^=rotl$1(T+R|0,18),N^=rotl$1(P+$|0,7),I^=rotl$1(N+P|0,9),$^=rotl$1(I+N|0,13),P^=rotl$1($+I|0,18),F^=rotl$1(M+D|0,7),O^=rotl$1(F+M|0,9),D^=rotl$1(O+F|0,13),M^=rotl$1(D+O|0,18);r[i++]=a+E|0,r[i++]=o+A|0,r[i++]=l+S|0,r[i++]=c+k|0,r[i++]=u+T|0,r[i++]=d+C|0,r[i++]=f+x|0,r[i++]=h+R|0,r[i++]=p+I|0,r[i++]=y+$|0,r[i++]=g+P|0,r[i++]=m+N|0,r[i++]=b+F|0,r[i++]=w+O|0,r[i++]=_+D|0,r[i++]=v+M|0}function BlockMix(e,t,n,s,r){let i=s+0,a=s+16*r;for(let o=0;o<16;o++)n[a+o]=e[t+16*(2*r-1)+o];for(let o=0;o<r;o++,i+=16,t+=16)XorAndSalsa(n,a,e,t,n,i),o>0&&(a+=16),XorAndSalsa(n,i,e,t+=16,n,a)}function scryptInit(e,t,n){const s=checkOpts$2({dkLen:32,asyncTick:10,maxmem:1073742848},n),{N:r,r:i,p:a,dkLen:o,asyncTick:l,maxmem:c,onProgress:u}=s;if(assert$2.number(r),assert$2.number(i),assert$2.number(a),assert$2.number(o),assert$2.number(l),assert$2.number(c),void 0!==u&&"function"!=typeof u)throw new Error("progressCb should be function");const d=128*i,f=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(a<0||a>137438953440/d)throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)");if(o<0||o>137438953440)throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32");const h=d*(r+a);if(h>c)throw new Error(`Scrypt: parameters too large, ${h} (128 * r * (N + p)) > ${c} (maxmem)`);const p=pbkdf2(sha256$1,e,t,{c:1,dkLen:d*a}),y=u32$2(p),g=u32$2(new Uint8Array(d*r)),m=u32$2(new Uint8Array(d));let b=()=>{};if(u){const e=2*r*a,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:a,dkLen:o,blockSize32:f,V:g,B32:y,B:p,tmp:m,blockMixCb:b,asyncTick:l}}function scryptOutput(e,t,n,s,r){const i=pbkdf2(sha256$1,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:a,blockSize32:o,V:l,B32:c,B:u,tmp:d,blockMixCb:f}=scryptInit(e,t,n);for(let h=0;h<i;h++){const e=o*h;for(let t=0;t<o;t++)l[t]=c[e+t];for(let t=0,n=0;t<s-1;t++)BlockMix(l,n,l,n+=o,r),f();BlockMix(l,(s-1)*o,c,e,r),f();for(let t=0;t<s;t++){const t=c[e+o-16]%s;for(let n=0;n<o;n++)d[n]=c[e+n]^l[t*o+n];BlockMix(d,0,c,e,r),f()}}return scryptOutput(e,a,u,l,d)}function number$2(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function bool$1(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function isBytes(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function bytes$2(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}, not of length=${e.length}`)}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}`)}
12
- /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),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),isLE$2=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];if(!isLE$2)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$2(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes$2(e){if("string"==typeof e)e=utf8ToBytes$2(e);else{if(!isBytes(e))throw new Error("Uint8Array expected, got "+typeof e);e=e.slice()}return e}function checkOpts$1(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),a=Number(n>>r&i),o=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,o,s)}const 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$2(e=toBytes$2(e),32);const t=u8to16(e,0),n=u8to16(e,2),s=u8to16(e,4),r=u8to16(e,6),i=u8to16(e,8),a=u8to16(e,10),o=u8to16(e,12),l=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|a<<2),this.r[7]=8065&(a>>>11|o<<5),this.r[8]=8191&(o>>>8|l<<8),this.r[9]=l>>>5&127;for(let c=0;c<8;c++)this.pad[c]=u8to16(e,16+2*c)}process(e,t,n=!1){const s=n?0:2048,{h:r,r:i}=this,a=i[0],o=i[1],l=i[2],c=i[3],u=i[4],d=i[5],f=i[6],h=i[7],p=i[8],y=i[9],g=u8to16(e,t+0),m=u8to16(e,t+2),b=u8to16(e,t+4),w=u8to16(e,t+6),_=u8to16(e,t+8),v=u8to16(e,t+10),E=u8to16(e,t+12),A=u8to16(e,t+14);let S=r[0]+(8191&g),k=r[1]+(8191&(g>>>13|m<<3)),T=r[2]+(8191&(m>>>10|b<<6)),C=r[3]+(8191&(b>>>7|w<<9)),x=r[4]+(8191&(w>>>4|_<<12)),R=r[5]+(_>>>1&8191),I=r[6]+(8191&(_>>>14|v<<2)),$=r[7]+(8191&(v>>>11|E<<5)),P=r[8]+(8191&(E>>>8|A<<8)),N=r[9]+(A>>>5|s),F=0,O=F+S*a+k*(5*y)+T*(5*p)+C*(5*h)+x*(5*f);F=O>>>13,O&=8191,O+=R*(5*d)+I*(5*u)+$*(5*c)+P*(5*l)+N*(5*o),F+=O>>>13,O&=8191;let D=F+S*o+k*a+T*(5*y)+C*(5*p)+x*(5*h);F=D>>>13,D&=8191,D+=R*(5*f)+I*(5*d)+$*(5*u)+P*(5*c)+N*(5*l),F+=D>>>13,D&=8191;let M=F+S*l+k*o+T*a+C*(5*y)+x*(5*p);F=M>>>13,M&=8191,M+=R*(5*h)+I*(5*f)+$*(5*d)+P*(5*u)+N*(5*c),F+=M>>>13,M&=8191;let B=F+S*c+k*l+T*o+C*a+x*(5*y);F=B>>>13,B&=8191,B+=R*(5*p)+I*(5*h)+$*(5*f)+P*(5*d)+N*(5*u),F+=B>>>13,B&=8191;let L=F+S*u+k*c+T*l+C*o+x*a;F=L>>>13,L&=8191,L+=R*(5*y)+I*(5*p)+$*(5*h)+P*(5*f)+N*(5*d),F+=L>>>13,L&=8191;let U=F+S*d+k*u+T*c+C*l+x*o;F=U>>>13,U&=8191,U+=R*a+I*(5*y)+$*(5*p)+P*(5*h)+N*(5*f),F+=U>>>13,U&=8191;let H=F+S*f+k*d+T*u+C*c+x*l;F=H>>>13,H&=8191,H+=R*o+I*a+$*(5*y)+P*(5*p)+N*(5*h),F+=H>>>13,H&=8191;let K=F+S*h+k*f+T*d+C*u+x*c;F=K>>>13,K&=8191,K+=R*l+I*o+$*a+P*(5*y)+N*(5*p),F+=K>>>13,K&=8191;let G=F+S*p+k*h+T*f+C*d+x*u;F=G>>>13,G&=8191,G+=R*c+I*l+$*o+P*a+N*(5*y),F+=G>>>13,G&=8191;let j=F+S*y+k*p+T*h+C*f+x*d;F=j>>>13,j&=8191,j+=R*u+I*c+$*l+P*o+N*a,F+=j>>>13,j&=8191,F=(F<<2)+F|0,F=F+O|0,O=8191&F,F>>>=13,D+=F,r[0]=O,r[1]=D,r[2]=M,r[3]=B,r[4]=L,r[5]=U,r[6]=H,r[7]=K,r[8]=G,r[9]=j}finalize(){const{h:e,pad:t}=this,n=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=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 a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let r=(1^s)-1;for(let a=0;a<10;a++)n[a]&=r;r=~r;for(let a=0;a<10;a++)e[a]=e[a]&r|n[a];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 a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=65535&i}update(e){exists$2(this);const{buffer:t,blockLen:n}=this,s=(e=toBytes$2(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$2(this),output$2(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 i=0;i<8;i++)e[r++]=n[i]>>>0,e[r++]=n[i]>>>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$1(e){const t=(t,n)=>e(n).update(toBytes$2(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$1(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$1(sigma16),sigma32_32=u32$1(sigma32);function rotl(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,a,o){const l=r.length,c=new Uint8Array(BLOCK_LEN),u=u32$1(c),d=isAligned32(r)&&isAligned32(i),f=d?u32$1(r):U32_EMPTY,h=d?u32$1(i):U32_EMPTY;for(let p=0;p<l;a++){if(e(t,n,s,u,a,o),a>=MAX_COUNTER)throw new Error("arx: counter overflow");const y=Math.min(BLOCK_LEN,l-p);if(d&&y===BLOCK_LEN){const e=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let t,n=0;n<BLOCK_LEN32;n++)t=e+n,h[t]=f[t]^u[n];p+=BLOCK_LEN;continue}for(let e,t=0;t<y;t++)e=p+t,i[e]=r[e]^c[t];p+=y}}function createCipher(e,t){const{allowShortKeys:n,extendNonceFn:s,counterLength:r,counterRight:i,rounds:a}=checkOpts$1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return number$2(r),number$2(a),bool$1(i),bool$1(n),(t,o,l,c,u=0)=>{bytes$2(t),bytes$2(o),bytes$2(l);const d=l.length;if(c||(c=new Uint8Array(d)),bytes$2(c),number$2(u),u<0||u>=MAX_COUNTER)throw new Error("arx: counter overflow");if(c.length<d)throw new Error(`arx: output (${c.length}) is shorter than data (${d})`);const f=[];let h,p,y=t.length;if(32===y)h=t.slice(),f.push(h),p=sigma32_32;else{if(16!==y||!n)throw new Error(`arx: invalid 32-byte key, got length=${y}`);h=new Uint8Array(32),h.set(t),h.set(t,16),p=sigma16_32,f.push(h)}isAligned32(o)||(o=o.slice(),f.push(o));const g=u32$1(h);if(s){if(24!==o.length)throw new Error("arx: extended nonce must be 24 bytes");s(p,g,u32$1(o.subarray(0,16)),g),o=o.subarray(16)}const m=16-r;if(m!==o.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(12!==m){const e=new Uint8Array(12);e.set(o,i?0:12-o.length),o=e,f.push(o)}const b=u32$1(o);for(runCipher(e,p,g,b,l,c,u,a);f.length>0;)f.pop().fill(0);return c}}function chachaCore(e,t,n,s,r,i=20){let a=e[0],o=e[1],l=e[2],c=e[3],u=t[0],d=t[1],f=t[2],h=t[3],p=t[4],y=t[5],g=t[6],m=t[7],b=r,w=n[0],_=n[1],v=n[2],E=a,A=o,S=l,k=c,T=u,C=d,x=f,R=h,I=p,$=y,P=g,N=m,F=b,O=w,D=_,M=v;for(let L=0;L<i;L+=2)E=E+T|0,F=rotl(F^E,16),I=I+F|0,T=rotl(T^I,12),E=E+T|0,F=rotl(F^E,8),I=I+F|0,T=rotl(T^I,7),A=A+C|0,O=rotl(O^A,16),$=$+O|0,C=rotl(C^$,12),A=A+C|0,O=rotl(O^A,8),$=$+O|0,C=rotl(C^$,7),S=S+x|0,D=rotl(D^S,16),P=P+D|0,x=rotl(x^P,12),S=S+x|0,D=rotl(D^S,8),P=P+D|0,x=rotl(x^P,7),k=k+R|0,M=rotl(M^k,16),N=N+M|0,R=rotl(R^N,12),k=k+R|0,M=rotl(M^k,8),N=N+M|0,R=rotl(R^N,7),E=E+C|0,M=rotl(M^E,16),P=P+M|0,C=rotl(C^P,12),E=E+C|0,M=rotl(M^E,8),P=P+M|0,C=rotl(C^P,7),A=A+x|0,F=rotl(F^A,16),N=N+F|0,x=rotl(x^N,12),A=A+x|0,F=rotl(F^A,8),N=N+F|0,x=rotl(x^N,7),S=S+R|0,O=rotl(O^S,16),I=I+O|0,R=rotl(R^I,12),S=S+R|0,O=rotl(O^S,8),I=I+O|0,R=rotl(R^I,7),k=k+T|0,D=rotl(D^k,16),$=$+D|0,T=rotl(T^$,12),k=k+T|0,D=rotl(D^k,8),$=$+D|0,T=rotl(T^$,7);let B=0;s[B++]=a+E|0,s[B++]=o+A|0,s[B++]=l+S|0,s[B++]=c+k|0,s[B++]=u+T|0,s[B++]=d+C|0,s[B++]=f+x|0,s[B++]=h+R|0,s[B++]=p+I|0,s[B++]=y+$|0,s[B++]=g+P|0,s[B++]=m+N|0,s[B++]=b+F|0,s[B++]=w+O|0,s[B++]=_+D|0,s[B++]=v+M|0}function hchacha(e,t,n,s){let r=e[0],i=e[1],a=e[2],o=e[3],l=t[0],c=t[1],u=t[2],d=t[3],f=t[4],h=t[5],p=t[6],y=t[7],g=n[0],m=n[1],b=n[2],w=n[3];for(let v=0;v<20;v+=2)r=r+l|0,g=rotl(g^r,16),f=f+g|0,l=rotl(l^f,12),r=r+l|0,g=rotl(g^r,8),f=f+g|0,l=rotl(l^f,7),i=i+c|0,m=rotl(m^i,16),h=h+m|0,c=rotl(c^h,12),i=i+c|0,m=rotl(m^i,8),h=h+m|0,c=rotl(c^h,7),a=a+u|0,b=rotl(b^a,16),p=p+b|0,u=rotl(u^p,12),a=a+u|0,b=rotl(b^a,8),p=p+b|0,u=rotl(u^p,7),o=o+d|0,w=rotl(w^o,16),y=y+w|0,d=rotl(d^y,12),o=o+d|0,w=rotl(w^o,8),y=y+w|0,d=rotl(d^y,7),r=r+c|0,w=rotl(w^r,16),p=p+w|0,c=rotl(c^p,12),r=r+c|0,w=rotl(w^r,8),p=p+w|0,c=rotl(c^p,7),i=i+u|0,g=rotl(g^i,16),y=y+g|0,u=rotl(u^y,12),i=i+u|0,g=rotl(g^i,8),y=y+g|0,u=rotl(u^y,7),a=a+d|0,m=rotl(m^a,16),f=f+m|0,d=rotl(d^f,12),a=a+d|0,m=rotl(m^a,8),f=f+m|0,d=rotl(d^f,7),o=o+l|0,b=rotl(b^o,16),h=h+b|0,l=rotl(l^h,12),o=o+l|0,b=rotl(b^o,8),h=h+b|0,l=rotl(l^h,7);let _=0;s[_++]=r,s[_++]=i,s[_++]=a,s[_++]=o,s[_++]=g,s[_++]=m,s[_++]=b,s[_++]=w}const xchacha20=createCipher(chachaCore,{counterRight:!1,counterLength:8,extendNonceFn:hchacha,allowShortKeys:!1}),ZEROS16$1=new Uint8Array(16),updatePadded=(e,t)=>{e.update(t);const n=t.length%16;n&&e.update(ZEROS16$1.subarray(n))},ZEROS32$1=new Uint8Array(32);function computeTag$1(e,t,n,s,r){const i=e(t,n,ZEROS32$1),a=poly1305.create(i);r&&updatePadded(a,r),updatePadded(a,s);const o=new Uint8Array(16),l=createView$2(o);setBigUint64$1(l,0,BigInt(r?r.length:0),!0),setBigUint64$1(l,8,BigInt(s.length),!0),a.update(o);const c=a.digest();return i.fill(0),c}const _poly1305_aead=e=>(t,n,s)=>{const r=16;return bytes$2(t,32),bytes$2(n),{encrypt:(i,a)=>{const o=i.length,l=o+r;a?bytes$2(a,l):a=new Uint8Array(l),e(t,n,i,a,1);const c=computeTag$1(e,t,n,a.subarray(0,-16),s);return a.set(c,o),a},decrypt:(i,a)=>{const o=i.length,l=o-r;if(o<r)throw new Error("encrypted data must be at least 16 bytes");a?bytes$2(a,l):a=new Uint8Array(l);const c=i.subarray(0,-16);if(!equalBytes(i.subarray(-16),computeTag$1(e,t,n,c,s)))throw new Error("invalid tag");return e(t,n,c,a,1),a}}},xchacha20poly1305=wrapCipher({blockSize:64,nonceLength:24,tagLength:16},_poly1305_aead(xchacha20));var 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));return{encode:Array.from(e).reverse().reduce((e,n)=>e?t(e,n.encode):n.encode,void 0),decode:e.reduce((e,n)=>e?t(e,n.decode):n.decode,void 0)}}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 a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function o(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=[],a=Array.from(e);for(a.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<a.length;i++){const o=a[i],l=n*e+o;if(!Number.isSafeInteger(l)||n*e/n!==e||l-o!==n*e)throw new Error("convertRadix: carry overflow");if(e=l%s,a[i]=Math.floor(l/s),!Number.isSafeInteger(a[i])||a[i]*s+e!==l)throw new Error("convertRadix: carry overflow");t&&(a[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()}
13
- /*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */
14
- 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 l=(e,t)=>t?l(t,e%t):e,c=(e,t)=>e+(t-l(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(c(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${c(n,s)}`);let i=0,a=0;const o=2**s-1,l=[];for(const c of e){if(t(c),c>=2**n)throw new Error(`convertRadix2: invalid data word=${c} from=${n}`);if(i=i<<n|c,a+n>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${n}`);for(a+=n;a>=s;a-=s)l.push((i>>a-s&o)>>>0);i&=2**a-1}if(i=i<<s-a&o,!r&&a>=n)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&a>0&&l.push(i>>>0),l}function d(e){return t(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return o(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(o(t,e,256))}}}function f(e,n=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(c(8,e)>32||c(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 h(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(n){}}}function p(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 n=0;n<e;n++)if(r[n]!==i[n])throw new Error("Invalid checksum");return s}}}e.utils={alphabet:s,chain:n,checksum:p,radix:d,radix2:f,join:r,padding:i},e.base16=n(f(4),s("0123456789ABCDEF"),r("")),e.base32=n(f(5),s("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),i(5),r("")),e.base32hex=n(f(5),s("0123456789ABCDEFGHIJKLMNOPQRSTUV"),i(5),r("")),e.base32crockford=n(f(5),s("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),r(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),e.base64=n(f(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),i(6),r("")),e.base64url=n(f(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),i(6),r(""));const y=e=>n(d(58),s(e),r(""));e.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),e.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const g=[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(g[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=g.indexOf(r.length),a=e.base58.decode(r);for(let e=0;e<a.length-i;e++)if(0!==a[e])throw new Error("base58xmr: wrong padding");n=n.concat(Array.from(a.slice(a.length-i)))}return Uint8Array.from(n)}};e.base58check=t=>n(p(4,e=>t(t(e))),e.base58);const m=n(s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),r("")),b=[996825010,642813549,513874426,1027748829,705979059];function w(e){const t=e>>25;let n=(33554431&e)<<5;for(let s=0;s<b.length;s++)1==(t>>s&1)&&(n^=b[s]);return n}function _(e,t,n=1){const s=e.length;let r=1;for(let i=0;i<s;i++){const t=e.charCodeAt(i);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);r=w(r)^t>>5}r=w(r);for(let i=0;i<s;i++)r=w(r)^31&e.charCodeAt(i);for(let i of t)r=w(r)^i;for(let i=0;i<6;i++)r=w(r);return r^=n,m.encode(u([r%2**30],30,5,!1))}function v(e){const t="bech32"===e?1:734539939,n=f(5),s=n.decode,r=n.encode,i=h(s);function a(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),a=e.slice(r+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const o=m.decode(a).slice(0,-6),l=_(i,o,t);if(!a.endsWith(l))throw new Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:i,words:o}}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:a,decodeToBytes:function(e){const{prefix:t,words:n}=a(e,!1);return{prefix:t,words:n,bytes:s(n)}},decodeUnsafe:h(a),fromWords:s,fromWordsUnsafe:i,toWords:r}}e.bech32=v("bech32"),e.bech32m=v("bech32m"),e.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},e.hex=n(f(4),s("0123456789abcdef"),r(""),a(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 E={utf8:e.utf8,hex:e.hex,base16:e.base16,base32:e.base32,base64:e.base64,base64url:e.base64url,base58:e.base58,base58xmr:e.base58xmr},A=`Invalid encoding type. Available types: ${Object.keys(E).join(", ")}`;e.bytesToString=(e,t)=>{if("string"!=typeof e||!E.hasOwnProperty(e))throw new TypeError(A);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return E[e].encode(t)},e.str=e.bytesToString;e.stringToBytes=(e,t)=>{if(!E.hasOwnProperty(e))throw new TypeError(A);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return E[e].decode(t)},e.bytes=e.stringToBytes}(lib);var Bech32MaxSize$1=5e3;function encodeBech32$1(e,t){let n=lib.bech32.toWords(t);return lib.bech32.encode(e,n,Bech32MaxSize$1)}function encodeBytes$1(e,t){return encodeBech32$1(e,t)}function encrypt$2(e,t,n=16,s=2){let r=randomBytes$2(16),i=2**n,a=scrypt(t.normalize("NFKC"),r,{N:i,r:8,p:1,dkLen:32}),o=randomBytes$2(24),l=Uint8Array.from([s]),c=xchacha20poly1305(a,o,l).encrypt(e);return encodeBytes$1("ncryptsec",concatBytes$2(Uint8Array.from([2]),Uint8Array.from([n]),r,o,l,c))}function decrypt$1(e,t){let{prefix:n,words:s}=lib.bech32.decode(e,Bech32MaxSize$1);if("ncryptsec"!==n)throw new Error(`invalid prefix ${n}, expected 'ncryptsec'`);let r=new Uint8Array(lib.bech32.fromWords(s)),i=r[0];if(2!==i)throw new Error(`invalid version ${i}, expected 0x02`);let a=2**r[1],o=r.slice(2,18),l=r.slice(18,42),c=r[42],u=Uint8Array.from([c]),d=r.slice(43),f=scrypt(t.normalize("NFKC"),o,{N:a,r:8,p:1,dkLen:32});return xchacha20poly1305(f,l,u).decrypt(d)}const nip49_star=Object.freeze(Object.defineProperty({__proto__:null,decrypt:decrypt$1,encrypt:encrypt$2},Symbol.toStringTag,{value:"Module"}));var 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(t){return{type:"invalid",data:null}}}function decode(e){let{prefix:t,words:n}=lib.bech32.decode(e,Bech32MaxSize),s=new Uint8Array(lib.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$2(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$2(e[0][0]),relays:e[1]?e[1].map(e=>utf8Decoder.decode(e)):[],author:e[2]?.[0]?bytesToHex$2(e[2][0]):void 0,kind:e[3]?.[0]?parseInt(bytesToHex$2(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$2(e[2][0]),kind:parseInt(bytesToHex$2(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$2(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$3(e))}function noteEncode(e){return encodeBytes("note",hexToBytes$3(e))}function encodeBech32(e,t){let n=lib.bech32.toWords(t);return lib.bech32.encode(e,n,Bech32MaxSize)}function encodeBytes(e,t){return encodeBech32(e,t)}function nprofileEncode(e){return encodeBech32("nprofile",encodeTLV({0:[hexToBytes$3(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$3(e.id)],1:(e.relays||[]).map(e=>utf8Encoder.encode(e)),2:e.author?[hexToBytes$3(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$3(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$2(...t)}const nip19_star=Object.freeze(Object.defineProperty({__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},Symbol.toStringTag,{value:"Module"})),{bech32:bech32,hex:hex,utf8:utf8}=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);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,a=i.connectedRelays();a.forEach(e=>{r?.add(e.url)});const o=new Map,{pubkeysToRelays:l,authorsMissingRelays:c}=getAllRelaysForAllPubkeys(e,t,n),u=getTopRelaysForAuthors(e,t),d=(e,t)=>{const n=o.get(t)||[];n.push(e),o.set(t,n)};for(const[f,h]of l.entries()){let e=s;const t=new Set;for(const n of a)h.has(n.url)&&(d(f,n.url),t.add(n.url),e--);for(const n of h)t.has(n)||o.has(n)&&(d(f,n),t.add(n),e--);if(!(e<=0))for(const n of u){if(e<=0)break;t.has(n)||h.has(n)&&(d(f,n),t.add(n),e--)}}for(const f of c)i.permanentAndConnectedRelays().forEach(e=>{const t=o.get(e.url)||[];t.push(f),o.set(e.url,t)});return o}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 a=s.split(";");i=t?"":i;let o=!1;"base64"===a[a.length-1]&&(a.pop(),o=!0);const l=a.shift()?.toLowerCase()??"",c=[...a.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 o&&c.push("base64"),(c.length>0||l&&l!==DATA_URL_DEFAULT_MIME_TYPE)&&c.unshift(l),`data:${c.join(";")},${o?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],a=r.index;n+=s.pathname.slice(t,a).replace(/\/{2,}/g,"/"),n+=i,t=a+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 i of[...s.searchParams.keys()])testParameter(i,t.removeQueryParameters)&&s.searchParams.delete(i);if(Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(s.search=""),Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const i of[...s.searchParams.keys()])testParameter(i,t.keepQueryParameters)||s.searchParams.delete(i);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;pendingAuthPublishes=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(n){}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(n){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,n),this._status=1,t?this.handleReconnection():this.ndkRelay.emit("delayed-connect",1728e5),n}}}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(),this.clearPendingPublishes(new Error(`Relay ${this.ndkRelay.url} disconnected`)),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();if(!r||!i)return void this.debug("Received OK for unknown event publish",s);if(e)i.resolve(n),this.pendingAuthPublishes.delete(s);else{if(n&&(n.toLowerCase().includes("auth-required")||n.toLowerCase().includes("not authorized")||n.toLowerCase().includes("blocked: not authorized"))){this.pendingAuthPublishes.get(s)?(this.debug("Publish failed due to auth-required, will retry after auth",s),r.push(i),this.openEventPublishes.set(s,r)):i.reject(new Error(n))}else i.reject(new Error(n)),this.pendingAuthPublishes.delete(s)}return void(0===r.length?this.openEventPublishes.delete(s):e||n?.toLowerCase().includes("auth-required")||n?.toLowerCase().includes("not authorized")||n?.toLowerCase().includes("blocked: not authorized")||this.openEventPublishes.set(s,r))}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(t){return void this.debug(`Error parsing message from ${this.ndkRelay.url}: ${t.message}`,t?.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 s;this._status=7;try{s=await t(this.ndkRelay,e)}catch(n){this.debug("Authentication policy threw an error",n),s=!1}if(this.debug("Authentication policy returned",!!s),s instanceof NDKEvent||!0===s){s instanceof NDKEvent&&await this.auth(s);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"),this.retryPendingAuthPublishes()}).catch(e=>{this._status=6,this.ndkRelay.emit("auth:failed",e),this.debug("Authentication failed",e),this.rejectPendingAuthPublishes(e)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};!0===s&&(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}clearPendingPublishes(e){this.rejectPendingAuthPublishes(e);for(const[t,n]of this.openEventPublishes.entries()){for(;n.length>0;){const t=n.shift();t&&t.reject(e)}this.openEventPublishes.delete(t)}}retryPendingAuthPublishes(){if(0!==this.pendingAuthPublishes.size){this.debug(`Retrying ${this.pendingAuthPublishes.size} pending publishes after auth`);for(const[e,t]of this.pendingAuthPublishes.entries())this.debug(`Retrying publish for event ${e}`),this.send(`["EVENT",${JSON.stringify(t)}]`);this.pendingAuthPublishes.clear()}}rejectPendingAuthPublishes(e){if(0!==this.pendingAuthPublishes.size){this.debug(`Rejecting ${this.pendingAuthPublishes.size} pending publishes due to auth failure`);for(const[t]of this.pendingAuthPublishes.entries()){const n=this.openEventPublishes.get(t);if(n&&n.length>0){const s=n.pop();s&&s.reject(new Error(`Authentication failed: ${e.message}`)),0===n.length&&this.openEventPublishes.delete(t)}}this.pendingAuthPublishes.clear()}}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.pendingAuthPublishes.set(e.id,e),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(s){n(s)}}),r=new Promise((e,s)=>{n=setTimeout(()=>{n=void 0,s(new Error(`Timeout: ${t}ms`))},t)}),i=()=>{s().then(e=>a(e)).catch(e=>o(e))};let a,o;const l=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},c=()=>{n&&clearTimeout(n),this.ndkRelay.removeListener("connect",i)};return this.ndkRelay.status>=5?Promise.race([s(),r]).catch(l).finally(c):(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)=>{a=e,o=t,this.ndkRelay.on("connect",i)}),r]).catch(l).finally(c))}async publishEvent(e){return this.ndkRelay.connectivity.publish(e.rawEvent())}};function filterFingerprint(e,t){const n=[];for(const r of e){const e=Object.entries(r||{}).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<25)&&(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(t){this.debug("Error closing subscription",t,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(){if(this.subIdParts.size>0){let e=Array.from(this.subIdParts).map(e=>e.substring(0,10)).join("-");e.length>20&&(e=e.substring(0,20)),this._subId=e}else 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:t}of this.items.values())t.eoseReceived(this.relay),t.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:formatFilters(t.filters),internalId:t.internalId,status:this.status,fingerprint:this.fingerprint,itemsSize:this.items.size}),this.removeItem(t))}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=createDebug2(`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 a=r.relays.get(normalizeRelayUrl(e));if(a)a.status<5&&s&&a.connect(),i.add(a);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 a=e=>{s.add(e)};e.on("relay:published",a);try{const a=Array.from(this.relays).map(n=>new Promise(a=>{const o=t?setTimeout(()=>{s.has(n)||(r.set(n,new Error(`Publish timeout after ${t}ms`)),a(!1))},t):null;n.publish(e,t).then(e=>{o&&clearTimeout(o),e?(s.add(n),a(!0)):a(!1)}).catch(e=>{o&&clearTimeout(o),i||r.set(n,e),a(!1)})}));if(await Promise.all(a),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",a)}}get size(){return this.relays.size}},d=createDebug2("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 a=t.getMatchingTags("p").map(e=>e[1]);if(a.length<5){Array.from(chooseRelayCombinationForPubkeys(e,a,"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",a.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 isValidHex64(e){if("string"!=typeof e||64!==e.length)return!1;for(let t=0;t<64;t++){const n=e.charCodeAt(t);if(!(n>=48&&n<=57||n>=97&&n<=102||n>=65&&n<=70))return!1}return!0}function isValidPubkey(e){return isValidHex64(e)}function isValidNip05(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t++)if(46===e.charCodeAt(t))return!0;return!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 r of t)n.has(r.slice(1))||(s.add(r.slice(1)),n.add(r.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:a}=nostrTools.nip19.decode(t);let o;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&&(o=["p",a]);break;case"nprofile":!1!==n?.pTags&&(o=["p",a.pubkey]);break;case"note":r.push(new Promise(async e=>{const n=await maybeGetEventRelayUrl(t);i(["q",a,n]),e()}));break;case"nevent":r.push(new Promise(async e=>{const{id:s,author:r}=a;let{relays:o}=a;o&&0!==o.length||(o=[await maybeGetEventRelayUrl(t)]),i(["q",s,o[0]]),r&&!1!==n?.pTags&&!1!==n?.pTagOnQTags&&i(["p",r]),e()}));break;case"naddr":r.push(new Promise(async e=>{const s=[a.kind,a.pubkey,a.identifier].join(":");let r=a.relays??[];0===r.length&&(r=[await maybeGetEventRelayUrl(t)]),i(["q",s,r[0]]),!1!==n?.pTags&&!1!==n?.pTagOnQTags&&!1!==n?.pTagOnATags&&i(["p",a.pubkey]),e()}));break;default:return e}return o&&i(o),`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$1(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 a=n||(this.content.match(/\\?iv=/)?"nip04":"nip44");if(("nip04"===a||4===this.kind)&&await isEncryptionEnabled(r,"nip04")&&this.content.search("\\?iv=")&&(s=await r.decrypt(i,this.content,"nip04")),!s&&"nip44"===a&&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.id,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],a=""!==i?this.ndk.pool.getRelay(i):void 0;return await this.ndk.fetchEvent(r,{},a)}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$1(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()?nostrTools.nip19.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:t}):t.length>0?nostrTools.nip19.neventEncode({id:this.tagId(),relays:t,author:this.pubkey}):nostrTools.nip19.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 getEventDetails(e){return"inspect"in e&&"string"==typeof e.inspect?e.inspect:JSON.stringify(e)}function validateForSerialization(e){if("number"!=typeof e.kind)throw new Error(`Can't serialize event with invalid properties: kind (must be number, got ${typeof e.kind}). Event: ${getEventDetails(e)}`);if("string"!=typeof e.content)throw new Error(`Can't serialize event with invalid properties: content (must be string, got ${typeof e.content}). Event: ${getEventDetails(e)}`);if("number"!=typeof e.created_at)throw new Error(`Can't serialize event with invalid properties: created_at (must be number, got ${typeof e.created_at}). Event: ${getEventDetails(e)}`);if("string"!=typeof e.pubkey)throw new Error(`Can't serialize event with invalid properties: pubkey (must be string, got ${typeof e.pubkey}). Event: ${getEventDetails(e)}`);if(!Array.isArray(e.tags))throw new Error(`Can't serialize event with invalid properties: tags (must be array, got ${typeof e.tags}). Event: ${getEventDetails(e)}`);for(let t=0;t<e.tags.length;t++){const n=e.tags[t];if(!Array.isArray(n))throw new Error(`Can't serialize event with invalid properties: tags[${t}] (must be array, got ${typeof n}). Event: ${getEventDetails(e)}`);for(let s=0;s<n.length;s++)if("string"!=typeof n[s])throw new Error(`Can't serialize event with invalid properties: tags[${t}][${s}] (must be string, got ${typeof n[s]}). Event: ${getEventDetails(e)}`)}}function serialize$1(e=!1,t=!1){validateForSerialization(this);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=>{if(!Array.isArray(e.data)||2!==e.data.length)return void console.error("[NDK] ❌ Signature verification worker received incompatible message format.","\n\n📋 Expected format: [eventId, boolean]","\n📦 Received:",e.data,"\n\n🔍 This likely means:","\n 1. You have a STALE worker.js file that needs updating","\n 2. Version mismatch between @nostr-dev-kit/ndk and deployed worker","\n 3. Wrong worker is being used for signature verification","\n\n✅ Solution: Update your worker files:","\n cp node_modules/@nostr-dev-kit/ndk/dist/workers/sig-verification.js public/","\n cp node_modules/@nostr-dev-kit/cache-sqlite-wasm/dist/worker.js public/","\n\n💡 Or use Vite/bundler imports instead of static files:",'\n import SigWorker from "@nostr-dev-kit/ndk/workers/sig-verification?worker"');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$1(){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$2((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(n){return this.signatureVerified=!1,!1}}function getEventHash(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(e){return bytesToHex$3(sha256$2((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 a=[];if(void 0!==t.fetchProfile){if(r??="p","p"===r&&!1===i?.pTags)return;const e=[r,t.pubkey];n&&e.push("",n),a.push(e)}else if(t instanceof e){const e=t;if(s??=e?.pubkey===this.pubkey,a=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);a=[t]}this.tags=mergeTags(this.tags,a)}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(r){}return this.rawEvent()}serialize=serialize$1.bind(this);getEventHash=getEventHash.bind(this);validate=validate$1.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$1.bind(this);encrypt=encrypt$1.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(this.ndk.aiGuardrails?.event?.publishing(this),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(a){console.error("Error adding unpublished event to cache",a)}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 a=t=>this.emit("notice",e,t),o=()=>this.handleRelayConnect(i),l=()=>this.handleRelayReady(e),c=()=>{this.recordDisconnection(e),this.emit("relay:disconnect",e)},u=()=>this.handleFlapping(e),d=t=>this.emit("relay:auth",e,t),f=()=>this.emit("relay:authed",e);e.off("notice",a),e.off("connect",o),e.off("ready",l),e.off("disconnect",c),e.off("flapping",u),e.off("auth",d),e.off("authed",f),e.on("notice",a),e.on("connect",o),e.on("ready",l),e.on("disconnect",c),e.on("flapping",u),e.on("auth",d),e.on("authed",f),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 i of t)5!==i.status&&4!==i.status&&(this.emit("relay:connecting",i),i.connect().catch(e=>{this.debug(`Failed to connect to relay ${i.url}: ${e??"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[n,s]of this.disconnectionTimes.entries())t-s>1e4&&this.disconnectionTimes.delete(n);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(t){return void console.error(t)}}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 s of n){const e=s.split(" "),n=e[0],r=e.slice(1).join(" ");"fallback"===n?(t.fallback||(t.fallback=[]),t.fallback.push(r)):t[n]=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=nostrTools.nip19.naddrEncode({kind:Number.parseInt(n),pubkey:s,identifier:r});break}case"e":e=nostrTools.nip19.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(n){}}catch(n){}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 s of this.items)if("e"===s[0]&&s[1])e.add(s[1]);else if("a"===s[0]&&s[1]){const[e,n,r]=s[1].split(":");if(!e||!n)continue;const i=`${e}:${n}`,a=t.get(i)||[];a.push(r||""),t.set(i,a)}if(e.size>0&&n.push({ids:Array.from(e)}),t.size>0)for(const[s,r]of t.entries()){const[e,t]=s.split(":");n.push({kinds:[Number.parseInt(e)],authors:[t],"#d":r})}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")??createDebug2("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(t){this.debug("error parsing p2pk pubkey",t,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[n,s]of Object.entries(this.properties))t.push(`${n} ${s}`);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 n of t.tags)switch(n[0]){case"imeta":this._imeta=mapImetaTag(n);break;case"dim":this.dimensions=strToDimension(n[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 s=0;s<this.tags.length;s++)if("sticker"===this.tags[s][0]){if(n===e){this.tags.splice(s,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")??createDebug2("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")??createDebug2("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 r of n)for(const e of r.kinds)t.set(e,r);const s=t.get(e.kind);return s?s.from(e):e}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 checkHashtagsWithPrefix(e,t){e.getMatchingTags("t").forEach((e,n)=>{if(e[1]&&e[1].startsWith("#")){const s=JSON.stringify(e);t("tag-hashtag-with-prefix",`t-tag[${n}] contains hashtag with # prefix.\n\n📦 Your tag:\n ${s}\n\n❌ Invalid value: "${e[1]}"\n\nHashtag tags should NOT include the # symbol.`,"Remove the # prefix from hashtag tags:\n ✅ event.tags.push(['t', 'nostr'])\n ❌ event.tags.push(['t', '#nostr'])",!1)}})}function checkReplaceableWithOldTimestamp(e,t){if(void 0===e.kind||null===e.kind||!e.created_at)return;if(!e.isReplaceable())return;const n=Math.floor(Date.now()/1e3),s=n-e.created_at;if(s>10){const r=Math.floor(s/60),i=r>0?`${r} minute${1!==r?"s":""}`:`${s} seconds`;t("event-replaceable-old-timestamp",`Publishing a replaceable event with an old created_at timestamp.\n\n📦 Event details:\n • kind: ${e.kind} (replaceable)\n • created_at: ${e.created_at}\n • age: ${i} old\n • current time: ${n}\n\n⚠️ This is wrong and will be rejected by relays.`,"For replaceable events, use publishReplaceable():\n\n ✅ CORRECT:\n await event.publishReplaceable();\n // Automatically updates created_at to now\n\n ❌ WRONG:\n await event.publish();\n // Uses old created_at")}}function signing(e,t,n,s){checkMissingKind(e,t),checkContentIsObject(e,t),checkCreatedAtMilliseconds(e,t),checkInvalidPTags(e,t),checkInvalidETags(e,t),checkHashtagsWithPrefix(e,t),checkManualReplyMarkers(e,n,s)}function publishing(e,t){checkReplaceableWithOldTimestamp(e,t)}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 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,s,r){if(r(),"ONLY_CACHE"===t?.cacheUsage)return;const i=Array.isArray(e)?e:[e],a=i.map(formatFilter).join("\n\n ---\n\n ");if(isNip33Pattern(e))i[0],n("fetch-events-usage","For fetching a NIP-33 addressable event, use fetchEvent() with the naddr directly.\n\n📦 Your filter:\n "+a+"\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(isReplaceableEventFilter(e))return;{if(!s())return;let e="";const t=i.some(e=>void 0!==e.limit),r=new Set(i.flatMap(e=>e.kinds||[])).size,o=new Set(i.flatMap(e=>e.authors||[])).size;if(t){const t=Math.max(...i.map(e=>e.limit||0));e+=`\n • Limit: ${t} event${1!==t?"s":""}`}r>0&&(e+=`\n • Kinds: ${r} type${1!==r?"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"+(i.length>1?"s":"")+":\n "+a+(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_EMPTY:"filter-empty",FILTER_SINCE_AFTER_UNTIL:"filter-since-after-until",FILTER_INVALID_A_TAG:"filter-invalid-a-tag",FILTER_HASHTAG_WITH_PREFIX:"filter-hashtag-with-prefix"};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;_fetchEventsCount=0;_subscribeCount=0;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[s,r]of Object.entries(t))"function"==typeof r&&(n[s]=(...e)=>{this.enabled&&r(...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}incrementFetchEventsCount(){this._fetchEventsCount++}incrementSubscribeCount(){this._subscribeCount++}shouldWarnAboutFetchEventsRatio(){const e=this._fetchEventsCount+this._subscribeCount;if(e<=6)return!1;return this._fetchEventsCount/e>.5}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),this.shouldWarnAboutFetchEventsRatio.bind(this),this.incrementFetchEventsCount.bind(this))}};event={signing:e=>{this.enabled&&signing(e,this.error.bind(this),this.warn.bind(this),this._replyEvents)},publishing:e=>{this.enabled&&publishing(e,this.warn.bind(this))},received:(e,t)=>{this.enabled},creatingReply:e=>{this.enabled&&this._replyEvents.add(e)}};subscription={created:(e,t)=>{this.enabled&&this.incrementSubscribeCount()}};relay={connected:e=>{this.enabled}}};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,a=i?e:{...e};if(e.ids){const t=[];e.ids.forEach((e,a)=>{void 0===e?i?s.push(`Filter[${n}].ids[${a}] is undefined`):r?.(`Fixed: Removed undefined value at ids[${a}]`):"string"!=typeof e?i?s.push(`Filter[${n}].ids[${a}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at ids[${a}] (was ${typeof e})`):isValidHex64(e)?t.push(e):i?s.push(`Filter[${n}].ids[${a}] is not a valid 64-char hex string: "${e}"`):r?.(`Fixed: Removed invalid hex string at ids[${a}]`)}),i||(a.ids=t.length>0?t:void 0)}if(e.authors){const t=[];e.authors.forEach((e,a)=>{void 0===e?i?s.push(`Filter[${n}].authors[${a}] is undefined`):r?.(`Fixed: Removed undefined value at authors[${a}]`):"string"!=typeof e?i?s.push(`Filter[${n}].authors[${a}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at authors[${a}] (was ${typeof e})`):isValidHex64(e)?t.push(e):i?s.push(`Filter[${n}].authors[${a}] is not a valid 64-char hex pubkey: "${e}"`):r?.(`Fixed: Removed invalid hex pubkey at authors[${a}]`)}),i||(a.authors=t.length>0?t:void 0)}if(e.kinds){const t=[];e.kinds.forEach((e,a)=>{void 0===e?i?s.push(`Filter[${n}].kinds[${a}] is undefined`):r?.(`Fixed: Removed undefined value at kinds[${a}]`):"number"!=typeof e?i?s.push(`Filter[${n}].kinds[${a}] is not a number (got ${typeof e})`):r?.(`Fixed: Removed non-number value at kinds[${a}] (was ${typeof e})`):Number.isInteger(e)?e<0||e>65535?i?s.push(`Filter[${n}].kinds[${a}] is out of valid range (0-65535): ${e}`):r?.(`Fixed: Removed out-of-range kind at kinds[${a}]: ${e}`):t.push(e):i?s.push(`Filter[${n}].kinds[${a}] is not an integer: ${e}`):r?.(`Fixed: Removed non-integer value at kinds[${a}]: ${e}`)}),i||(a.kinds=t.length>0?t:void 0)}for(const o in e)if(o.startsWith("#")&&2===o.length){const t=e[o];if(Array.isArray(t)){const e=[];t.forEach((t,a)=>{void 0===t?i?s.push(`Filter[${n}].${o}[${a}] is undefined`):r?.(`Fixed: Removed undefined value at ${o}[${a}]`):"string"!=typeof t?i?s.push(`Filter[${n}].${o}[${a}] is not a string (got ${typeof t})`):r?.(`Fixed: Removed non-string value at ${o}[${a}] (was ${typeof t})`):"#e"!==o&&"#p"!==o||isValidHex64(t)?e.push(t):i?s.push(`Filter[${n}].${o}[${a}] is not a valid 64-char hex string: "${t}"`):r?.(`Fixed: Removed invalid hex string at ${o}[${a}]`)}),i||(a[o]=e.length>0?e:void 0)}}return i||Object.keys(a).forEach(e=>{void 0===a[e]&&delete a[e]}),a}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/;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):isValidHex64(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):isValidHex64(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 a in e)if(a.startsWith("#")&&2===a.length){const n=e[a];Array.isArray(n)&&n.forEach((e,n)=>{"string"==typeof e&&("#e"!==a&&"#p"!==a||(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].${a}[${n}] contains bech32: "${e}". Tag values must be decoded.`,"Use filterFromId() or nip19.decode() to get the hex value first.",!1):isValidHex64(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].${a}[${n}] is not a valid 64-char hex string: "${e}"`,("#e"===a?"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)})}if(e["#t"]){const n=e["#t"];n?.forEach((e,n)=>{"string"==typeof e&&e.startsWith("#")&&s.error(GuardrailCheckId.FILTER_HASHTAG_WITH_PREFIX,`Filter[${t}].#t[${n}] contains hashtag with # prefix: "${e}". Hashtag values should NOT include the # symbol.`,'Remove the # prefix from hashtag filters:\n ✅ { "#t": ["nostr"] }\n ❌ { "#t": ["#nostr"] }',!1)})}}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=nostrTools.nip19.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(n){console.error("Error decoding",e,n)}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=nostrTools.nip19.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(n){}return[]}var NDKSubscriptionCacheUsage=(e=>(e.ONLY_CACHE="ONLY_CACHE",e.CACHE_FIRST="CACHE_FIRST",e.PARALLEL="PARALLEL",e.ONLY_RELAY="ONLY_RELAY",e))(NDKSubscriptionCacheUsage||{}),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;exclusiveRelay=!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.exclusiveRelay=this.opts.exclusiveRelay||!1,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[t,n]of this.relayFilters){this.pool.getRelay(t,!0,!0,n).subscribe(this,n)}}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 a;if(e instanceof NDKEvent&&(a=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||(a??=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e),this.ndk.cacheAdapter.setEventDup(a,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(a??=new NDKEvent(this.ndk,e),a.ndk=this.ndk,a.relay=t,!n&&!s){if(!this.skipValidation&&!a.isValid)return void this.debug("Event failed validation %s from relay %s",r,t?.url);if(t){if(t.shouldValidateEvent()&&!this.skipVerification)if(a.relay=t,this.ndk.asyncSigVerification)a.verifySignature(!0);else{if(!a.verifySignature(!0))return this.debug("Event failed signature validation",e),void this.ndk.reportInvalidSignature(a,t);t.addValidatedEvent()}else t.addNonValidatedEvent()}this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(a,this.filters,t)}if(!this.opts.includeMuted&&this.ndk.muteFilter&&this.ndk.muteFilter(a))return void this.debug("Event muted, skipping");s&&!0===this.skipOptimisticPublishEvent||(this.emitEvent(this.opts?.wrap??!1,a,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,a="_",o]=r;try{const r=await n(`https://${o}/.well-known/nostr.json?name=${a}`,s),{names:i,relays:l,nip46:c}=parseNIP05Result(await r.json()),u=i[a.toLowerCase()];let d=null;return u&&(d={pubkey:u,relays:l?.[u],nip46:c?.[u]}),e?.cacheAdapter?.saveNip05&&e.cacheAdapter.saveNip05(t,d),d}catch(l){return e?.cacheAdapter?.saveNip05&&e?.cacheAdapter.saveNip05(t,null),console.error("Failed to fetch NIP05 for",t,l),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(s){throw new Error(`Failed to parse profile event: ${s}`)}t.profileEvent=JSON.stringify(e.rawEvent());for(const r of Object.keys(n))switch(r){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[r]=n[r]}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=nostrTools.nip19.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(t){console.error("Failed to decode nprofile",t)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nostrTools.nip19.npubEncode(this.pubkey)}return this._npub}get nprofile(){const e=this.profileEvent?.onRelays?.map(e=>e.url);return nostrTools.nip19.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=nostrTools.nip19.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(r){if(r instanceof Error&&"Timeout"===r.message)try{return await t}catch(i){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");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n));const s="string"==typeof e?e:e.pubkey;if(Array.from(t).some(e=>"string"==typeof e?e===s:e.pubkey===s))return!1;t.add(e);const r=new NDKEvent(this.ndk,{kind:n});for(const i of t)"string"==typeof i?r.tags.push(["p",i]):r.tag(i);return await r.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="string"==typeof e?e:e.pubkey,r=new Set;let i=!1;for(const o of t){("string"==typeof o?o:o.pubkey)!==s?r.add(o):i=!0}if(!i)return!1;const a=new NDKEvent(this.ndk,{kind:n});for(const o of r)"string"==typeof o?a.tags.push(["p",o]):a.tag(o);return await a.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return 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}=nostrTools.nip19.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$4(e)}else this._privateKey=e;this._pubkey=nostrTools.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$3(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 nostrTools.nip19.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nostrTools.nip19.npubEncode(this._pubkey)}encryptToNcryptsec(e,t=16,n=2){if(!this._privateKey)throw new Error("Private key not available");return encrypt$2(this._privateKey,e,t,n)}static generate(){const t=nostrTools.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 nostrTools.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=nostrTools.nip44.v2.utils.getConversationKey(this._privateKey,s);return await nostrTools.nip44.v2.encrypt(t,e)}return await nostrTools.nip04.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=nostrTools.nip44.v2.utils.getConversationKey(this._privateKey,s);return await nostrTools.nip44.v2.decrypt(t,e)}return await nostrTools.nip04.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,a=new Set;for(const f of i.relays.values())a.add(f);if(r)for(const f of r.values())for(const e of f){const t=i.getRelay(e,!0,!0);t&&a.add(t)}const o=new Map,l=new Map,c=new NDKRelaySet(a,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&&o.set(e.pubkey,NDKRelayList.from(e));for(const e of n)if(3===e.kind){if(o.has(e.pubkey))continue;const n=relayListFromKind3(t,e);n&&l.set(e.pubkey,n)}e=e.filter(e=>!o.has(e)&&!l.has(e))}if(0===e.length)return o;const u=new Map,d=new Map;return new Promise(n=>{let r=!1;(async()=>{const l={closeOnEose:!0,pool:i,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:c};c&&(l.relaySet=c),t.subscribe({kinds:[3,10002],authors:e},l,{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())o.set(e.pubkey,NDKRelayList.from(e));for(const n of e){if(o.has(n))continue;const e=d.get(n);if(!e)continue;const s=relayListFromKind3(t,e);s&&o.set(n,s)}t.debug(`[getRelayListForUsers] Returning ${o.size} relay lists for ${e.length} pubkeys`),n(o)}}});const f=Array.from(a).some(e=>e.status<=2),h=Array.from(a).some(e=>4===e.status);let p=s;(f||h)&&(p=s+3e3),t.debug(`[getRelayListForUsers] Setting fallback timeout to ${p}ms (disconnected: ${f}, connecting: ${h})`,{pubkeys:e}),setTimeout(()=>{r||(r=!0,t.debug(`[getRelayListForUsers] Timeout reached, returning ${o.size} relay lists`),n(o))},p)})()})}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 a=new Map;for(const e of r)e instanceof NDKUser&&e.relayUrls.length>0&&a.set(e.pubkey,e.relayUrls);n.push(new Promise(e=>{getRelayListForUsers(i,this.ndk,t,1e3,a).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 s of n)e.addRelay(s);if(0===n.length)for(const s of t.relays.values())e.addRelay(s);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 i of s)nostrTools.matchFilters(i.filters,e)&&r.push(i);for(const i of r){if(i.exclusiveRelay&&i.relaySet){let s=!1;if(n)s=!i.skipOptimisticPublishEvent;else if(t)s=i.relaySet.relays.has(t);else{s=(this.seenEvents.get(e.id)||[]).some(e=>i.relaySet.relays.has(e))}if(!s){i.debug.extend("exclusive-relay")("Rejected event %s from %s (relay not in exclusive set)",e.id,t?.url||(n?"optimistic":"cache"));continue}}i.eventReceived(e,t,!1,n)}}},debug6=createDebug2("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=nostrTools.nip19.decode(e);return"npub"===t.type?npub(this,t.data):"nprofile"===t.type?nprofile(this,t.data):t}catch(t){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(t){return!1}}async function fetchEventFromTag(e,t,n,s={type:"timeout"}){const r=this.debug.extend("fetch-event-from-tag"),[i,a,o]=e;r("fetching event from tag",e,n={},s);const l=getRelaysForSync(this,t.pubkey);if(l&&l.size>0){r("fetching event from author relays %o",Array.from(l));const e=NDKRelaySet.fromRelayUrls(Array.from(l),this),t=await this.fetchEvent(a,n,e);if(t)return t}else r("no author relays found for %s",t.pubkey,t);const c=calculateRelaySetsFromFilters(this,[{ids:[a]}],this.pool);r("fetching event without relay hint",c);const u=await this.fetchEvent(a,n);if(u)return u;if(o&&""!==o){const e=await this.fetchEvent(a,n,this.pool.getRelay(o,!0,!0,[{ids:[a]}]));if(e)return e}let d;const f=isValidHint(o)?this.pool.getRelay(o,!1,!0,[{ids:[a]}]):void 0,h=new Promise(e=>{this.fetchEvent(a,n,f).then(e)});if(!isValidHint(o)||"none"===s.type)return h;const p=new Promise(async e=>{const t=s.relaySet,i=s.timeout??1500,o=new Promise(e=>setTimeout(e,i));if("timeout"===s.type&&await o,d)e(d);else{r("fallback fetch triggered");e(await this.fetchEvent(a,n,t))}});switch(s.type){case"timeout":return Promise.race([h,p]);case"eose":return d=await h,d||p}}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;_wallet;walletConfig;constructor(e={}){super(),this.debug=e.debug||createDebug2("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 n of this.subManager.subscriptions.values()){n.filters.some(t=>t.authors?.includes(e))&&"function"==typeof n.refreshRelayConnections&&(this.debug(`Refreshing relay connections for subscription ${n.internalId}`),n.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)),this.cacheAdapter?.initializeAsync&&t.push(this.cacheAdapter.initializeAsync(this)),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}=nostrTools.nip19.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}=nostrTools.nip19.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(isValidNip05(e))return NDKUser.fromNip05(e,this,t);if(e.startsWith("npub1")){const{type:t,data:n}=nostrTools.nip19.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}=nostrTools.nip19.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,a=s;n instanceof NDKRelaySet?(console.warn("relaySet is deprecated, use opts.relaySet instead. This will be removed in version v2.14.0"),i=n,a=s):"boolean"!=typeof n&&"object"!=typeof n||(a=n);const o={relaySet:i,...t};a&&"object"==typeof a&&(a.onEvent&&(o.onEvent=a.onEvent),a.onEose&&(o.onEose=a.onEose),a.onClose&&(o.onClose=a.onClose),a.onEvents&&(r=a.onEvents));const l=new NDKSubscription(this,e,o);this.subManager.add(l),this.aiGuardrails?.subscription?.created(Array.isArray(e)?e:[e],o);const c=l.pool;if(l.relaySet)for(const u of l.relaySet.relays)c.useTemporaryRelay(u,void 0,l.filters);if(this.outboxPool&&l.hasAuthorsFilter()){const e=l.filters.filter(e=>e.authors&&e.authors?.length>0).flatMap(e=>e.authors);this.outboxTracker?.trackUsers(e)}return a&&setTimeout(async()=>{this.cacheAdapter?.initializeAsync&&!this.cacheAdapter.ready&&await this.cacheAdapter.initializeAsync(this);const e=l.start(!r);e&&e.length>0&&r&&r(e)},0),l}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 a={...t||{},closeOnEose:!0};r&&(a.relaySet=r);const o=setTimeout(()=>{l.stop(),this.aiGuardrails._nextCallDisabled=null,e(i)},1e4),l=this.subscribe(s,a,{onEvent:t=>{t.ndk=this,t.isReplaceable()?(!i||i.created_at<t.created_at)&&(i=t):(clearTimeout(o),this.aiGuardrails._nextCallDisabled=null,e(t))},onEose:()=>{clearTimeout(o),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){if(!e)return this._wallet=void 0,void(this.walletConfig=void 0);this._wallet=e,this.walletConfig??={},this.walletConfig.lnPay=e?.lnPay?.bind(e),this.walletConfig.cashuPay=e?.cashuPay?.bind(e)}get wallet(){return this._wallet}},nip19_exports={};__reExport(nip19_exports,nip19_star);var nip49_exports={};function disconnect(e,t){return t??=createDebug2("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(a){s?.(`Failed to publish auth event to relay ${t.url}`,a),i(e)}}function signIn({ndk:e,signer:t,debug:n}={}){return n??=createDebug2("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,a)=>{t?await signAndAuth(i,s,t,n,r,a):e?.once("signer:ready",async e=>{await signAndAuth(i,s,e,n,r,a)})})}}__reExport(nip49_exports,nip49_star);var NDKRelayAuthPolicies={disconnect:disconnect,signIn:signIn};async function ndkSignerFromPayload(e,t){let n;try{n=JSON.parse(e)}catch(r){return void console.error("Failed to parse signer payload string",e,r)}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(r){const e=r instanceof Error?r.message:String(r);throw new Error(`Failed to deserialize signer type ${n.type}: ${e}`)}}var NDKNip07Signer=class e{_userPromise;encryptionQueue=[];encryptionProcessing=!1;debug;waitTimeout;_pubkey;ndk;_user;constructor(e=1e3,t){this.debug=createDebug2("ndk:nip07"),this.waitTimeout=e,this.ndk=t}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}async blockUntilReady(){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 s of Object.keys(t))t[s].read&&t[s].write&&n.push(s);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:a,resolve:o,reject:l}=n;this.debug("Processing encryption queue item",{method:r,counterpartyHexpubkey:i,value:a});try{const e=await(window.nostr?.[s]?.[r](i,a));if(!e)throw new Error("Failed to encrypt/decrypt");o(e)}catch(c){const e=c instanceof Error?c.message:String(c);if(e.includes("call already executing")&&t<5)return this.debug("Retrying encryption queue item",{method:r,counterpartyHexpubkey:i,value:a,retries:t}),void setTimeout(()=>{this.processEncryptionQueue(n,t+1)},50*t);l(c instanceof Error?c:new Error(e))}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(c){const s="nip04"===this.encryptionType?"nip44":"nip04";n=await this.signer.decrypt(t,e.content,s),this.encryptionType=s}const s=JSON.parse(n),{id:r,method:i,params:a,result:o,error:l}=s;return i?{id:r,pubkey:e.pubkey,method:i,params:a,event:e}:{id:r,result:o,error:l,event:e}}async sendResponse(e,t,n,s=24133,r){const i={id:e,result:n};r&&(i.error=r);const a=await this.signer.user(),o=this.ndk.getUser({pubkey:t}),l=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(i),tags:[["p",t]],pubkey:a.pubkey});l.content=await this.signer.encrypt(o,l.content,this.encryptionType),await l.sign(this.signer),await l.publish(this.relaySet)}async sendRequest(e,t,n=[],s=24133,r){const i=Math.random().toString(36).substring(7),a=await this.signer.user(),o=this.ndk.getUser({pubkey:e}),l={id:i,method:t,params:n},c=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(l),tags:[["p",e]],pubkey:a.pubkey});return u.content=await this.signer.encrypt(o,u.content,this.encryptionType),await u.sign(this.signer),await u.publish(this.relaySet),c}};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 a=`nostrconnect://${e}?image=${s?.image?encodeURIComponent(s.image):""}&url=${i}&name=${r}&perms=${s?.perms?encodeURIComponent(s.perms):""}&secret=${encodeURIComponent(t)}`;return n&&(a+=`&relay=${encodeURIComponent(n)}`),a}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 a;return a=new e(n,!1,i,r.relayUrls),a.userPubkey=r.userPubkey,a.bunkerPubkey=r.bunkerPubkey,a.relayUrls=r.relayUrls,a.secret=r.secret,r.userPubkey&&(a._user=new NDKUser({pubkey:r.userPubkey}),a._user&&(a._user.ndk=n)),a}};registerSigner("nip46",NDKNip46Signer),createDebug2("ndk:zapper:ln"),createDebug2("ndk:zapper");class OutboxQueue{constructor(e,t={}){this.storage=e,this.queuePrefix="_outbox/",this.maxRetries=t.maxRetries||5,this.baseDelay=t.baseDelay||1e3,this.maxDelay=t.maxDelay||6e4,this.failedTTL=t.failedTTL||864e5}async enqueue(e,t){const n={id:e.id,event:e,relays:t,status:"pending",retries:0,createdAt:Date.now(),nextRetryAt:Date.now(),failedRelays:[]},s=`${this.queuePrefix}${e.id}`;return await this.storage.put(s,n),n}async markSent(e,t){const n=`${this.queuePrefix}${e}`,s=await this.storage.get(n);s&&(t.length>0?await this.storage.delete(n):await this._scheduleRetry(n,s))}async _scheduleRetry(e,t){if(t.retries++,t.retries>=this.maxRetries)t.status="failed",t.failedAt=Date.now();else{t.status="pending";const e=Math.min(this.baseDelay*Math.pow(2,t.retries)+1e3*Math.random(),this.maxDelay);t.nextRetryAt=Date.now()+e}await this.storage.put(e,t)}async getPendingEvents(){const e=await this.storage.getAll(this.queuePrefix),t=Date.now();return e.filter(e=>e&&"pending"===e.status&&e.nextRetryAt<=t).sort((e,t)=>e.createdAt-t.createdAt)}async getFailedEvents(){return(await this.storage.getAll(this.queuePrefix)).filter(e=>e&&"failed"===e.status)}async getStats(){const e=await this.storage.getAll(this.queuePrefix),t={total:e.length,pending:0,failed:0,oldestPending:null,oldestFailed:null};for(const n of e)n&&("pending"===n.status?(t.pending++,(!t.oldestPending||n.createdAt<t.oldestPending)&&(t.oldestPending=n.createdAt)):"failed"===n.status&&(t.failed++,(!t.oldestFailed||n.failedAt<t.oldestFailed)&&(t.oldestFailed=n.failedAt)));return t}async purgeOldFailed(e=this.failedTTL){const t=await this.storage.getAll(this.queuePrefix),n=Date.now();let s=0;for(const r of t)r&&"failed"===r.status&&n-r.failedAt>e&&(await this.storage.delete(`${this.queuePrefix}${r.id}`),s++);return s}async clear(){const e=await this.storage.getAll(this.queuePrefix);let t=0;for(const n of e)n&&n.id&&(await this.storage.delete(`${this.queuePrefix}${n.id}`),t++);return t}async retryFailed(e){const t=`${this.queuePrefix}${e}`,n=await this.storage.get(t);return n&&"failed"===n.status?(n.status="pending",n.retries=0,n.nextRetryAt=Date.now(),delete n.failedAt,await this.storage.put(t,n),n):null}}class SyncService{constructor(e,t={}){this.client=e,this.interval=t.interval||1e4,this.running=!1,this.timer=null,this._processing=!1,t.autoStart&&this.start()}start(){this.running||(this.running=!0,this._scheduleNextRun())}stop(){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=null)}isRunning(){return this.running}async syncNow(){return this._processOutbox()}_scheduleNextRun(){this.running&&(this.timer=setTimeout(()=>{this._runLoop()},this.interval))}async _runLoop(){if(this.running){try{await this._processOutbox()}catch(e){console.warn("[sync] Outbox processing failed:",e.message)}this._scheduleNextRun()}}async _processOutbox(){if(this._processing)return{skipped:!0,reason:"already processing"};this._processing=!0;const e={processed:0,succeeded:0,failed:0,purged:0};try{if(!this.client.outboxQueue)return{...e,skipped:!0,reason:"no outbox queue"};const n=await this.client.outboxQueue.getPendingEvents();e.processed=n.length;for(const s of n)try{(await this.client._attemptDelivery(s.event,s.relays)).successful.length>0?e.succeeded++:e.failed++}catch(t){console.warn(`[sync] Retry failed for ${s.id}:`,t.message),e.failed++}e.purged=await this.client.outboxQueue.purgeOldFailed()}finally{this._processing=!1}return e}async getStats(){const e={running:this.running,interval:this.interval,queue:null};return this.client.outboxQueue&&(e.queue=await this.client.outboxQueue.getStats()),e}}class PersistentStorage{async init(e){throw new Error("init() must be implemented by subclass")}async put(e,t){throw new Error("put() must be implemented by subclass")}async get(e){throw new Error("get() must be implemented by subclass")}async getAll(e){throw new Error("getAll() must be implemented by subclass")}async delete(e){throw new Error("delete() must be implemented by subclass")}async clear(){throw new Error("clear() must be implemented by subclass")}async close(){throw new Error("close() must be implemented by subclass")}}async function createPersistentStorage(e,t={}){const n="undefined"!=typeof window&&void 0!==window.indexedDB;if("undefined"!=typeof process&&process.versions,n){const{IndexedDBStorage:t}=await Promise.resolve().then(()=>require("./indexeddb-storage-wKG4mICM.cjs")),n=new t;return await n.init(e),n}{const{MemoryStorage:t}=await Promise.resolve().then(()=>require("./memory-storage-CGC8xM2G.cjs")),n=new t;return await n.init(e),n}}let NDKCacheAdapterDexie=null,ndkCacheAdapterLoaded=!1;async function loadNDKCacheAdapter(){if(ndkCacheAdapterLoaded)return NDKCacheAdapterDexie;if(ndkCacheAdapterLoaded=!0,"undefined"!=typeof window&&"undefined"!=typeof indexedDB)try{const e=await Promise.resolve().then(()=>require("./index--QsHG_gD.cjs"));NDKCacheAdapterDexie=e.default||e.NDKCacheAdapterDexie}catch(e){console.debug("[nostr] NDK cache adapter not available, using LRU cache")}return NDKCacheAdapterDexie}let globalNDK=null,globalNDKRelays=new Set;function getGlobalNDK(e={}){if(globalNDK){if(e.relays)for(const t of e.relays)globalNDKRelays.has(t)||(globalNDK.addExplicitRelay(t),globalNDKRelays.add(t))}else{const t={explicitRelayUrls:e.relays||[],signer:e.signer,autoConnectUserRelays:!1,autoFetchUserMutelist:!1};e.cacheAdapter&&(t.cacheAdapter=e.cacheAdapter,e.cacheAdapter),globalNDK=new NDK(t)}return globalNDK}const pendingQueries$1=new Map,PENDING_QUERY_TIMEOUT=5e3,activeSubscriptions=new Map,backgroundRefreshThrottle=new Map,BACKGROUND_REFRESH_INTERVAL=3e4,pendingWrites=new Map,WRITE_DEBOUNCE_MS=500,authorSubscriptions=new Map,AUTHOR_SUB_INIT_TIMEOUT=5e3;class LRUCache{constructor(e=500){this.maxSize=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;const t=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,t),t}set(e,t){for(this.cache.has(e)&&this.cache.delete(e),this.cache.set(e,t);this.cache.size>this.maxSize;){const e=this.cache.keys().next().value;this.cache.delete(e)}}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}forEach(e){this.cache.forEach(e)}}let webSocketPolyfillPromise=null;function ensureWebSocket(){return void 0!==globalThis.WebSocket?Promise.resolve():(webSocketPolyfillPromise||(webSocketPolyfillPromise=(async()=>{try{const{default:e}=await import("ws");globalThis.WebSocket=e}catch(e){}})()),webSocketPolyfillPromise)}function hexToBytes$2(e){const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}class NostrClient{constructor(e={}){if(e.relays&&!Array.isArray(e.relays))throw new Error("Relays must be an array");this.relays=e.relays||[],this.privateKey=e.privateKey||this._generatePrivateKey(),this.signer=new NDKPrivateKeySigner(this.privateKey),this.publicKey=nostrTools.getPublicKey(this.privateKey),this.config=e,this._subscriptions=new Map,this._eventCache=new LRUCache(e.cacheSize||500),this._cacheIndex=new Map,this.persistentStorage=null,this._persistQueue=new Map,this._persistTimer=null,this._persistBatchMs=e.persistBatchMs||100,this._initReady=this._initialize()}async _initialize(){await ensureWebSocket();const e=await loadNDKCacheAdapter();let t=null;if(e&&this.config.appName){const r=`holosphere_ndk_${this.config.appName}`;await this._clearIncompatibleNDKCache(r);try{t=new e({dbName:r}),this._useNDKCache=!0}catch(n){console.warn("[nostr] Failed to initialize NDK cache adapter:",n.message),await this._deleteDexieDatabase(r);try{t=new e({dbName:r}),this._useNDKCache=!0}catch(s){console.warn("[nostr] Failed to initialize NDK cache adapter after reset:",s.message)}}}if(this.relays.length>0){this.ndk=getGlobalNDK({relays:this.relays,signer:this.signer,cacheAdapter:t}),this.relays.forEach(e=>globalNDKRelays.add(e)),console.log("[NostrClient] Connecting to relays:",this.relays);try{await this.ndk.connect(),console.log("[NostrClient] NDK connect() completed. Pool stats:",this.ndk.pool?.stats?.())}catch(r){console.error("[NostrClient] NDK connect() FAILED:",r.message)}}else this.ndk=null;await this._initPersistentStorage(),this.relays.length>0&&this._initLongLivedSubscription()}_initLongLivedSubscription(){const e=this.publicKey;if(authorSubscriptions.has(e))return;const t={subscription:null,initialized:!1,initPromise:null,initResolve:null};t.initPromise=new Promise(e=>{t.initResolve=e}),authorSubscriptions.set(e,t);const n={kinds:[3e4],authors:[this.publicKey]},s=this.ndk.subscribe(n,{closeOnEose:!1,cacheUsage:NDKSubscriptionCacheUsage.ONLY_RELAY});s.on("event",e=>{if(e.pubkey!==this.publicKey)return;const t=e.rawEvent();this._cacheEvent(t)}),s.on("eose",()=>{t.initialized||(t.initialized=!0,t.initResolve())}),t.subscription=s,setTimeout(()=>{t.initialized||(t.initialized=!0,t.initResolve())},AUTHOR_SUB_INIT_TIMEOUT)}async _waitForSubscriptionInit(){const e=authorSubscriptions.get(this.publicKey);e&&e.initPromise&&await e.initPromise}async _initPersistentStorage(){if(!1!==this.config.persistence&&(this.config.radisk||this.config.appName))try{const e=this.config.appName||"holosphere_default";this.persistentStorage=await createPersistentStorage(e,{dataDir:this.config.dataDir}),this._loadFromPersistentStorage().catch(e=>{console.warn("Background persistent storage load failed:",e)}),this.outboxQueue=new OutboxQueue(this.persistentStorage,{maxRetries:this.config.maxRetries||5,baseDelay:this.config.retryBaseDelay||1e3,maxDelay:this.config.retryMaxDelay||6e4,failedTTL:this.config.failedTTL||864e5}),!1!==this.config.backgroundSync&&(this.syncService=new SyncService(this,{interval:this.config.syncInterval||1e4,autoStart:!0}))}catch(e){console.warn("Failed to initialize persistent storage:",e)}}async _clearIncompatibleNDKCache(e){if("undefined"==typeof indexedDB)return;if((await(indexedDB.databases?.())||[]).find(t=>t.name===e))try{await new Promise((t,n)=>{const s=indexedDB.open(e);s.onsuccess=()=>{const n=s.result,r=Array.from(n.objectStoreNames);n.close();!["events","eventTags"].every(e=>r.includes(e))&&r.length>0?(console.warn(`[nostr] NDK cache database ${e} has incompatible schema, clearing...`),this._deleteDexieDatabase(e).then(t).catch(t)):t()},s.onerror=()=>t(),s.onblocked=()=>t()})}catch{}}async _deleteDexieDatabase(e){if("undefined"!=typeof indexedDB)return new Promise(t=>{const n=indexedDB.deleteDatabase(e);n.onsuccess=()=>{console.log(`[nostr] Deleted incompatible database: ${e}`),t()},n.onerror=()=>{console.warn(`[nostr] Failed to delete database: ${e}`),t()},n.onblocked=()=>{console.warn(`[nostr] Database deletion blocked: ${e}`),t()}})}async _loadFromPersistentStorage(){if(this.persistentStorage)try{const e=await this.persistentStorage.getAll("");for(const t of e)t&&t.id&&!t.status&&this._cacheEventSync(t)}catch(e){console.warn("Failed to load from persistent storage:",e)}}async persistentGet(e){try{await Promise.race([this._initReady,new Promise((e,t)=>setTimeout(()=>t(new Error("Init timeout")),1e4))])}catch(t){return console.warn("[NostrClient] persistentGet: Init timeout, returning null"),null}if(!this.persistentStorage)return null;try{return await this.persistentStorage.get(e)||null}catch(n){return console.warn("[nostr] Persistent storage read failed:",n),null}}getCachedByPath(e,t=3e4){const n=`d:${t}:${e}`,s=this._eventCache.get(n);return s&&s.events&&s.events[0]?s.events[0]:null}async persistentGetAll(e){if(await this._initReady,!this.persistentStorage)return[];try{return(await this.persistentStorage.getAll(e)).filter(e=>e&&e.id&&!e.status)}catch(t){return console.warn("[nostr] Persistent storage read failed:",t),[]}}_generatePrivateKey(){const e=new Uint8Array(32);if("undefined"!=typeof window&&window.crypto)window.crypto.getRandomValues(e);else try{const t=globalThis.crypto||global.crypto;if(t&&t.getRandomValues)t.getRandomValues(e);else for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}catch(t){for(let n=0;n<32;n++)e[n]=Math.floor(256*Math.random())}return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}async publish(e,t={}){try{await Promise.race([this._initReady,new Promise((e,t)=>setTimeout(()=>t(new Error("Init timeout")),15e3))])}catch(s){console.warn("[NostrClient] publish: Init timeout, continuing with available state")}const n=t.waitForRelays||!1;if(e.kind>=3e4&&e.kind<4e4&&!1!==t.debounce&&!n){const n=e.tags?.find(e=>"d"===e[0]);if(n&&n[1])return this._debouncedPublish(e,n[1],t)}return this._doPublish(e,t)}_debouncedPublish(e,t,n){return new Promise((s,r)=>{const i=pendingWrites.get(t);i&&(clearTimeout(i.timer),i.resolve({event:null,results:[],debounced:!0,supersededBy:e}));const a=setTimeout(async()=>{pendingWrites.delete(t);try{const t=await this._doPublish(e,n);s(t)}catch(i){r(i)}},WRITE_DEBOUNCE_MS);pendingWrites.set(t,{event:e,timer:a,resolve:s,reject:r});const o=this._createSignedEvent(e,n.signingKey);this._cacheEvent(o)})}_createSignedEvent(e,t=null){const n=t||this.privateKey,s=t?nostrTools.getPublicKey(hexToBytes$2(t)):this.publicKey;if(this.ndk){const t=new NDKEvent(this.ndk);return t.kind=e.kind,t.content=e.content,t.tags=e.tags||[],t.created_at=e.created_at||Math.floor(Date.now()/1e3),{kind:t.kind,content:t.content,tags:t.tags,created_at:t.created_at,pubkey:s,id:"",sig:""}}try{return nostrTools.finalizeEvent(e,hexToBytes$2(n))}catch(r){return{...e,pubkey:s,id:Math.random().toString(16).slice(2).padStart(64,"0"),sig:"mock-signature",created_at:e.created_at||Math.floor(Date.now()/1e3)}}}async _doPublish(e,t={}){const n=t.waitForRelays||!1,s=t.signingKey||null;let r;if(e.id&&e.sig)r=e;else if(this.ndk){const t=new NDKEvent(this.ndk);if(t.kind=e.kind,t.content=e.content,t.tags=e.tags||[],t.created_at=e.created_at||Math.floor(Date.now()/1e3),s){const e=new NDKPrivateKeySigner(s);await t.sign(e)}else await t.sign(this.signer);r=t.rawEvent()}else r=this._createSignedEvent(e,s);if(await this._cacheEvent(r),this.outboxQueue&&await this.outboxQueue.enqueue(r,this.relays),this.ndk&&this.relays.length>0){if(n){return{event:r,results:(await this._attemptDelivery(r,this.relays)).results,queued:!!this.outboxQueue}}return this._attemptDelivery(r,this.relays).catch(()=>{}),{event:r,results:[],queued:!!this.outboxQueue}}return{event:r,results:[],queued:!!this.outboxQueue}}async _attemptDelivery(e,t){if(!this.ndk)return{successful:[],failed:t,results:[]};const n=new NDKEvent(this.ndk,e),s=[],r=[],i=[];try{const e=n.publish(),a=new Promise((e,t)=>setTimeout(()=>t(new Error("Publish timeout")),3e4)),o=await Promise.race([e,a]);for(const n of t){const e=this.ndk.pool.getRelay(n);o.has(e)?(s.push(n),i.push({relay:n,status:"fulfilled",value:!0})):(r.push(n),i.push({relay:n,status:"rejected",reason:"Not published to relay"}))}}catch(a){for(const e of t)r.push(e),i.push({relay:e,status:"rejected",reason:a.message})}if(this.outboxQueue&&await this.outboxQueue.markSent(e.id,s),r.length>0&&0===s.length){const t=i.filter(e=>"rejected"===e.status).map(e=>e.reason||"unknown").join(", ");t.includes("timed out")||console.warn(`[nostr] All relays failed for ${e.id?.slice(0,8)}: ${t}`)}return{successful:s,failed:r,results:i}}async query(e,t={}){const n=void 0!==t.timeout?t.timeout:3e4;try{await Promise.race([this._initReady,new Promise((e,t)=>setTimeout(()=>t(new Error("Init timeout")),Math.min(n,1e4)))])}catch(u){console.warn("[NostrClient] query: Init timeout, continuing with available state")}const s=n,r=!1!==t.localFirst,i=!0===t.forceRelay;if(0===this.relays.length||!this.ndk){return this._getMatchingCachedEvents(e)}const a=authorSubscriptions.get(this.publicKey),o=e.authors&&1===e.authors.length&&e.authors[0]===this.publicKey;if(!i&&o&&a&&a.initialized){return this._getMatchingCachedEvents(e)}if(!i&&o&&a&&!a.initialized&&(await Promise.race([a.initPromise,new Promise(e=>setTimeout(e,Math.min(s,AUTHOR_SUB_INIT_TIMEOUT)))]),a.initialized)){return this._getMatchingCachedEvents(e)}if(e["#d"]&&1===e["#d"].length&&e.kinds&&1===e.kinds.length){const t=`d:${e.kinds[0]}:${e["#d"][0]}`,n=this._eventCache.get(t);if(n&&Date.now()-n.timestamp<5e3)return n.events}const l=JSON.stringify(e),c=this._eventCache.get(l);return c&&Date.now()-c.timestamp<5e3?c.events:r&&c?(this._refreshCacheInBackground(e,l,s),c.events):this._queryRelaysAndCache(e,l,s)}async _queryRelaysAndCache(e,t,n){const s=pendingQueries$1.get(t);if(s&&Date.now()-s.timestamp<PENDING_QUERY_TIMEOUT)return s.promise;const r=(async()=>{try{let r=[];if(this.ndk){const t=this.ndk.fetchEvents(e,{closeOnEose:!0}),i=new Promise((e,t)=>setTimeout(()=>t(new Error("Relay query timeout")),n||3e4));try{const e=await Promise.race([t,i]);r=Array.from(e).map(e=>e.rawEvent())}catch(s){if("Relay query timeout"!==s.message)throw s;console.warn("[NostrClient] Relay query timed out, returning empty results"),r=[]}}return e.authors&&e.authors.length>0&&(r=r.filter(t=>e.authors.includes(t.pubkey))),this._eventCache.set(t,{events:r,timestamp:Date.now()}),this._indexCacheEntry(t,e),r}finally{pendingQueries$1.delete(t)}})();return pendingQueries$1.set(t,{promise:r,timestamp:Date.now()}),r}_limitCacheSize(){}_indexCacheEntry(e,t){if(t.kinds)for(const n of t.kinds)this._cacheIndex.has(n)||this._cacheIndex.set(n,new Set),this._cacheIndex.get(n).add(e)}_unindexCacheEntry(e){if(e.startsWith("{"))try{const t=JSON.parse(e);if(t.kinds)for(const n of t.kinds){const t=this._cacheIndex.get(n);t&&(t.delete(e),0===t.size&&this._cacheIndex.delete(n))}}catch{}}_refreshCacheInBackground(e,t,n){this._queryRelaysAndCache(e,t,n).catch(e=>{console.debug("[nostr] Background cache refresh failed:",e.message)})}refreshPathInBackground(e,t=3e4,n={}){this._doBackgroundPathRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background path refresh failed:",e.message)})}async _doBackgroundPathRefresh(e,t,n){if(0===this.relays.length||!this.ndk)return;const s=backgroundRefreshThrottle.get(e);if(s&&Date.now()-s<BACKGROUND_REFRESH_INTERVAL)return;if(backgroundRefreshThrottle.set(e,Date.now()),backgroundRefreshThrottle.size>1e3){const e=Date.now()-BACKGROUND_REFRESH_INTERVAL;for(const[t,n]of backgroundRefreshThrottle)n<e&&backgroundRefreshThrottle.delete(t)}const r={kinds:[t],authors:n.authors||[this.publicKey],"#d":[e],limit:1},i=JSON.stringify(r),a=n.timeout||3e4,o=(await this._queryRelaysAndCache(r,i,a)).filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey));o.length>0&&await this._cacheEvent(o[0])}refreshPrefixInBackground(e,t=3e4,n={}){this._doBackgroundPrefixRefresh(e,t,n).catch(e=>{console.debug("[nostr] Background prefix refresh failed:",e.message)})}async _doBackgroundPrefixRefresh(e,t,n){if(0===this.relays.length||!this.ndk)return;const s=`prefix:${e}`,r=backgroundRefreshThrottle.get(s);if(r&&Date.now()-r<BACKGROUND_REFRESH_INTERVAL)return;backgroundRefreshThrottle.set(s,Date.now());const i={kinds:[t],authors:n.authors||[this.publicKey],limit:n.limit||1e3},a=JSON.stringify(i),o=n.timeout||3e4;let l=await this._queryRelaysAndCache(i,a,o);l=l.filter(e=>(n.authors||[this.publicKey]).includes(e.pubkey)),l=l.filter(t=>{const n=t.tags.find(e=>"d"===e[0]);return n&&n[1]&&n[1].startsWith(e)});for(const c of l)await this._cacheEvent(c)}async queryHybrid(e,t={}){await this._initReady;const n=void 0!==t.timeout?t.timeout:3e4,s=this._getMatchingCachedEvents(e);if(0===this.relays.length||!this.ndk)return s;let r=[];try{const t=this.ndk.fetchEvents(e,{closeOnEose:!0}),s=new Promise((e,t)=>setTimeout(()=>t(new Error("Relay query timeout")),n)),i=await Promise.race([t,s]);r=Array.from(i).map(e=>e.rawEvent()),e.authors&&e.authors.length>0&&(r=r.filter(t=>e.authors.includes(t.pubkey)))}catch(l){console.warn("Relay query failed, using local cache only:",l.message)}const i=new Map;for(const c of s){const e=this._getEventKey(c);i.set(e,c)}for(const c of r){const e=this._getEventKey(c),t=i.get(e);c.kind>=3e4&&c.kind<4e4&&t?c.created_at>=t.created_at&&i.set(e,c):i.set(e,c)}const a=Array.from(i.values()),o=JSON.stringify(e);return this._eventCache.set(o,{events:a,timestamp:Date.now()}),a}_getEventKey(e){if(e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1])return`${e.kind}:${t[1]}`}return e.id}async subscribe(e,t,n={}){await this._initReady;const s=`sub-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,r=JSON.stringify(e);if(0===this.relays.length||!this.ndk){const r=this._getMatchingCachedEvents(e),i={filter:e,onEvent:t,active:!0};return this._subscriptions.set(s,i),setTimeout(()=>{i.active&&(r.forEach(e=>t(e)),n.onEOSE&&n.onEOSE())},10),{id:s,unsubscribe:()=>{i.active=!1,this._subscriptions.delete(s),i.onEvent=()=>{}}}}const i=activeSubscriptions.get(r);if(i)return i.callbacks.add(t),i.refCount++,{id:s,unsubscribe:()=>{i.callbacks.delete(t),i.refCount--,0===i.refCount&&(i.subscription&&i.subscription.stop&&i.subscription.stop(),activeSubscriptions.delete(r)),this._subscriptions.delete(s)}};const a=new Set([t]),o={callbacks:a,refCount:1,subscription:null};activeSubscriptions.set(r,o);const l=this.ndk.subscribe(e,{closeOnEose:!1,cacheUsage:NDKSubscriptionCacheUsage.ONLY_RELAY});return l.on("event",t=>{const n=t.rawEvent();if(e.authors&&e.authors.length>0&&!e.authors.includes(n.pubkey))return;this._cacheEvent(n);const s=activeSubscriptions.get(r);if(s)for(const e of s.callbacks)try{e(n)}catch(i){console.warn("[nostr] Subscription callback error:",i.message)}}),l.on("eose",()=>{n.onEOSE&&n.onEOSE()}),o.subscription=l,this._subscriptions.set(s,l),{id:s,unsubscribe:()=>{a.delete(t),o.refCount--,0===o.refCount&&(l.stop&&l.stop(),activeSubscriptions.delete(r)),this._subscriptions.delete(s)}}}_cacheEventSync(e){const t=e.id;if(this._eventCache.set(t,{events:[e],timestamp:Date.now()}),e.kind>=3e4&&e.kind<4e4){const t=e.tags.find(e=>"d"===e[0]);if(t&&t[1]){const n=`d:${e.kind}:${t[1]}`,s=this._eventCache.get(n);(!s||!s.events[0]||e.created_at>s.events[0].created_at||e.created_at===s.events[0].created_at&&e.id!==s.events[0].id)&&(this._eventCache.set(n,{events:[e],timestamp:Date.now()}),s&&s.events[0]&&this._eventCache.delete(s.events[0].id),this._invalidateQueryCachesForEvent(e))}}}_invalidateQueryCachesForEvent(e){const t=this._cacheIndex.get(e.kind);if(!t||0===t.size)return;const n=[];for(const s of t){if(this._eventCache.get(s))try{const t=JSON.parse(s);this._eventMatchesFilter(e,t)&&n.push(s)}catch{t.delete(s)}else t.delete(s)}for(const s of n)this._eventCache.delete(s),this._unindexCacheEntry(s)}async _cacheEvent(e){if(this._cacheEventSync(e),this.persistentStorage){let t=e.id;if(e.kind>=3e4&&e.kind<4e4){const n=e.tags.find(e=>"d"===e[0]);n&&n[1]&&(t=n[1])}this._persistQueue.set(t,e),this._persistTimer||(this._persistTimer=setTimeout(()=>this._flushPersistQueue(),this._persistBatchMs))}if(0===this.relays.length||!this.ndk)for(const t of this._subscriptions.values())t.active&&this._eventMatchesFilter(e,t.filter)&&setTimeout(()=>{t.active&&t.onEvent(e)},10)}async _flushPersistQueue(){if(this._persistTimer=null,!this.persistentStorage||0===this._persistQueue.size)return;const e=Array.from(this._persistQueue.entries());this._persistQueue.clear();const t=e.map(async([e,t])=>{try{await this.persistentStorage.put(e,t)}catch(n){console.warn(`Failed to persist event ${e}:`,n.message)}});await Promise.all(t)}_getMatchingCachedEvents(e){const t=[],n=new Map;for(const s of this._eventCache.values())for(const r of s.events||[])if(this._eventMatchesFilter(r,e)){if(r.kind>=3e4&&r.kind<4e4){const e=r.tags.find(e=>"d"===e[0]);if(e&&e[1]){const s=`${r.kind}:${e[1]}`,i=n.get(s);if(!i||r.created_at>i.created_at||r.created_at===i.created_at&&JSON.parse(r.content)?._deleted&&!JSON.parse(i.content)?._deleted){if(i){const e=t.indexOf(i);e>-1&&t.splice(e,1)}n.set(s,r),t.push(r)}continue}}t.push(r)}return t}_eventMatchesFilter(e,t){if(t.kinds&&!t.kinds.includes(e.kind))return!1;if(t.ids&&!t.ids.includes(e.id))return!1;if(t.authors&&!t.authors.includes(e.pubkey))return!1;if(t["#d"]){const n=e.tags.find(e=>"d"===e[0]);if(!n||!t["#d"].includes(n[1]))return!1}return!(t.since&&e.created_at<t.since)&&!(t.until&&e.created_at>t.until)}async getEvent(e){const t=await this.query({ids:[e]});return t.length>0?t[0]:null}clearCache(e=null){if(e)for(const t of this._eventCache.keys())t.includes(e)&&this._eventCache.delete(t);else this._eventCache.clear()}async close(e={}){!1!==e.flush&&this._persistTimer&&(clearTimeout(this._persistTimer),await this._flushPersistQueue()),this.syncService&&this.syncService.stop();const t=authorSubscriptions.get(this.publicKey);t&&t.subscription&&(t.subscription.stop&&t.subscription.stop(),authorSubscriptions.delete(this.publicKey));for(const n of this._subscriptions.values())n.stop?n.stop():void 0!==n.active&&(n.active=!1);this._subscriptions.clear(),this._eventCache.clear(),this._cacheIndex.clear()}getRelayStatus(){return this.ndk?this.relays.map(e=>{const t=this.ndk.pool.getRelay(e);return{url:e,connected:1===t?.status}}):this.relays.map(e=>({url:e,connected:!1}))}}function createClient(e){return new NostrClient(e)}const BACKEND_MODULES={nostr:"./backends/nostr-backend.js",gundb:"./backends/gundb-backend.js",activitypub:"./backends/activitypub-backend.js"},loadedBackends=new Map;class BackendFactory{static getAvailableBackends(){return Object.keys(BACKEND_MODULES)}static isAvailable(e){return e in BACKEND_MODULES}static async loadBackend(e){if(loadedBackends.has(e))return loadedBackends.get(e);const t=BACKEND_MODULES[e];if(!t)throw new Error(`Unknown backend type: '${e}'. Available backends: ${Object.keys(BACKEND_MODULES).join(", ")}`);try{const n=await import(t),s=n.default||n[`${capitalize(e)}Backend`];if(!s)throw new Error(`Backend module '${e}' does not export a valid backend class`);return loadedBackends.set(e,s),s}catch(n){if("ERR_MODULE_NOT_FOUND"===n.code)throw new Error(`Backend '${e}' requires additional dependencies. Please install them: ${getDependencyHint(e)}`);throw n}}static async create(e,t){const n=new(await this.loadBackend(e))(t);return await n.init(),n}static register(e,t){"string"==typeof t?BACKEND_MODULES[e]=t:(loadedBackends.set(e,t),BACKEND_MODULES[e]=null)}}function capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}function getDependencyHint(e){return{nostr:"npm install nostr-tools",gundb:"npm install gun",activitypub:"npm install express"}[e]||"Check the documentation for required dependencies"}function gunPromise(e,t=1e3){return new Promise((n,s)=>{let r=!1;const i=setTimeout(()=>{r||(r=!0,n(null))},t);e.once(e=>{r||(r=!0,clearTimeout(i),n(e||null))})})}function gunPut(e,t,n=1e3){return new Promise((s,r)=>{let i=!1;const a=setTimeout(()=>{i||(i=!0,s({ok:!0,timeout:!0}))},n);e.put(t,e=>{i||(i=!0,clearTimeout(a),e.err?r(new Error(e.err)):s(e))})})}async function gunMap(e,t=5e3){return new Promise(n=>{const s={};let r=!1,i=0,a=0;e.once(t=>{if(r)return;if(!t)return r=!0,void n({});const o=Object.keys(t).filter(e=>"_"!==e);if(0===o.length)return r=!0,void n({});for(const e of o){const n=t[e];n&&("object"==typeof n&&n["#"]||(s[e]=n))}i=o.length,e.map().once((e,t)=>{r||!e||t.startsWith("_")||(s[t]=e,a++,r||i>0&&a>=i&&(r=!0,n(s)))})}),setTimeout(()=>{r||(r=!0,n(s))},t)})}function buildPath$2(e,t,n,s=null){const r=encodePathComponent$1(t),i=encodePathComponent$1(n);if(s){return`${e}/${r}/${i}/${encodePathComponent$1(s)}`}return`${e}/${r}/${i}`}function buildGlobalPath(e,t,n=null){const s=encodePathComponent$1(t);if(n){return`${e}/${s}/${encodePathComponent$1(n)}`}return`${e}/${s}`}function encodePathComponent$1(e){return encodeURIComponent(e).replace(/%2F/g,"/")}function getGunPath(e,t){const n=t.split("/").filter(e=>e.length>0);let s=e;for(const r of n)s=s.get(r);return s}function serializeForGun(e){return JSON.stringify(e)}function deserializeFromGun(e){if(!e)return null;try{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}if(e._json&&"string"==typeof e._json)try{return JSON.parse(e._json)}catch(t){return console.warn("Failed to parse _json field:",t),null}if(e._&&e._["#"])return e;if(e._&&e._[">"]){const n=Object.entries(e).find(([e,t])=>"_"!==e&&"string"==typeof t);if(n)try{return JSON.parse(n[1])}catch(t){return n[1]}}if("object"==typeof e&&null!==e){const t={...e};return delete t._,0===Object.keys(t).length?null:t}return e}catch(n){return console.warn("Error deserializing Gun data:",n),e}}async function write$2(e,t,n){try{const s=serializeForGun(n),r=t.split("/").filter(e=>e.length>0);console.log("[gun-wrapper] write:",{path:t,parts:r,dataId:n?.id});const i=getGunPath(e,t);console.log("[gun-wrapper] write ref soul:",i?._.get);const a=await gunPut(i,s,5e3);return console.log("[gun-wrapper] write ack:",{ok:a.ok,timeout:a.timeout}),a.timeout&&console.warn("[gun-wrapper] write timed out (data may not be persisted):",t),console.log("[gun-wrapper] write complete:",t),{ok:!0,timeout:a.timeout||!1}}catch(s){throw console.error("[gun-wrapper] write error:",s),s}}async function read$2(e,t){const n=t.split("/").filter(e=>e.length>0);console.log("[gun-wrapper] read:",{path:t,parts:n});const s=getGunPath(e,t);console.log("[gun-wrapper] read ref soul:",s?._.get);const r=await gunPromise(s,2e3);if(console.log("[gun-wrapper] read rawData:",r?"string"==typeof r?r.substring(0,100):"object":"null"),!r)return null;const i=deserializeFromGun(r);return!i||i._deleted?null:i}async function readAll$2(e,t,n=5e3){const s=t.split("/").filter(e=>e.length>0);return console.log("[gun-wrapper] readAll:",{path:t,parts:s}),new Promise(s=>{const r=new Map;let i=!1,a=0,o=0;const l=getGunPath(e,t);console.log("[gun-wrapper] readAll ref soul:",l?._.get);const c=e=>deserializeFromGun(e);l.once(e=>{if(i)return;if(console.log("[gun-wrapper] readAll parentData:",e),console.log("[gun-wrapper] readAll parentData keys:",e?Object.keys(e).filter(e=>"_"!==e):"null"),console.log("[gun-wrapper] readAll parentData type:",typeof e),!e)return i=!0,console.log("[gun-wrapper] readAll: no parent data, returning empty"),void s([]);const t=Object.keys(e).filter(e=>"_"!==e);if(console.log("[gun-wrapper] readAll keys:",t),0===t.length)return i=!0,console.log("[gun-wrapper] readAll: no keys, returning empty"),void s([]);for(const n of t){const t=e[n];if(!t)continue;if("object"==typeof t&&t["#"])continue;const s=c(t);s&&s.id&&!s._deleted&&r.set(s.id,s)}if(a=t.length,0===a)return i=!0,void s(Array.from(r.values()));l.map().once((e,t)=>{if(i||!e||"_"===t)return;const n=c(e);n&&n.id&&!n._deleted&&(r.has(n.id)||r.set(n.id,n)),o++,i||a>0&&o>=a&&(i=!0,console.log("[gun-wrapper] readAll resolved with",r.size,"items"),s(Array.from(r.values())))})}),setTimeout(()=>{i||(i=!0,s(Array.from(r.values())))},n)})}async function update$2(e,t,n){const s=await gunPromise(getGunPath(e,t));if(!s)return!1;const r=deserializeFromGun(s);if(!r||!r.id||r._deleted)return!1;const i={...r,...n};try{const n=serializeForGun(i);return await gunPut(getGunPath(e,t),n,2e3),await new Promise(e=>setTimeout(e,200)),!0}catch(a){throw a}}async function deleteData$2(e,t){try{const n=await gunPromise(getGunPath(e,t));if(!n)return!0;const s=deserializeFromGun(n),r={id:s?.id,_deleted:!0,_deletedAt:Date.now()};return await gunPut(getGunPath(e,t),serializeForGun(r),2e3),await new Promise(e=>setTimeout(e,200)),!0}catch(n){throw n}}async function deleteAll$2(e,t){const n=await readAll$2(e,t);let s=0;for(const r of n)if(r&&r.id){const n=`${t}/${r.id}`;await deleteData$2(e,n),s++}return{success:!0,count:s}}function subscribe$2(e,t,n,s={}){const r=t.split("/");if(void 0!==s.prefix?s.prefix:r.length<=3){const s=getGunPath(e,t);return s.map().on((e,t)=>{if(e&&!t.startsWith("_")){const s=deserializeFromGun(e);s&&!s._deleted&&n(s,t)}}),{unsubscribe:()=>{try{s.off()}catch(e){}}}}{const s=getGunPath(e,t).on((e,t)=>{if(e){const s=deserializeFromGun(e);s&&!s._deleted&&n(s,t)}});return{unsubscribe:()=>{try{s.off()}catch(e){}}}}}async function writeGlobal$1(e,t,n,s){if(!s||!s.id)throw new Error("writeGlobal: data must have an id field");return write$2(e,buildGlobalPath(t,n,s.id),s)}async function readGlobal$1(e,t,n,s){return read$2(e,buildGlobalPath(t,n,s))}async function readAllGlobal(e,t,n,s=2e3){return readAll$2(e,buildGlobalPath(t,n))}async function deleteGlobal$1(e,t,n,s){return deleteData$2(e,buildGlobalPath(t,n,s))}async function deleteAllGlobal$1(e,t,n){return deleteAll$2(e,buildGlobalPath(t,n))}function parse(e){return deserializeFromGun(e)}function serialize(e){return serializeForGun(e)}const gunWrapper=Object.freeze(Object.defineProperty({__proto__:null,buildGlobalPath:buildGlobalPath,buildPath:buildPath$2,deleteAll:deleteAll$2,deleteAllGlobal:deleteAllGlobal$1,deleteData:deleteData$2,deleteGlobal:deleteGlobal$1,parse:parse,read:read$2,readAll:readAll$2,readAllGlobal:readAllGlobal,readGlobal:readGlobal$1,serialize:serialize,subscribe:subscribe$2,update:update$2,write:write$2,writeGlobal:writeGlobal$1},Symbol.toStringTag,{value:"Module"}));async function federate(e,t,n,s=!0){if(!t||!n)throw new Error("federate: Missing required space IDs");if(t===n)throw new Error("Cannot federate a space with itself");try{let r=await e.readGlobal("federation",t);r||(r={id:t,name:t,federation:[],notify:[],timestamp:Date.now()}),r.federation||(r.federation=[]),r.notify||(r.notify=[]),r.federation.includes(n)||r.federation.push(n),r.timestamp=Date.now(),await e.writeGlobal("federation",r);let i=await e.readGlobal("federation",n);i||(i={id:n,name:n,federation:[],notify:[],timestamp:Date.now()}),i.notify||(i.notify=[]),i.notify.includes(t)||i.notify.push(t),i.timestamp=Date.now(),await e.writeGlobal("federation",i);const a={id:`${t}_${n}`,space1:t,space2:n,created:Date.now(),status:"active",bidirectional:s};return await e.writeGlobal("federationMeta",a),!0}catch(r){throw console.error(`Federation creation failed: ${r.message}`),r}}async function getFederation(e,t){if(!t)throw new Error("getFederation: Missing space ID");return e.readGlobal("federation",t)}async function unfederate(e,t,n){if(!t||!n)throw new Error("unfederate: Missing required space IDs");try{let s=await e.readGlobal("federation",t);s&&s.federation&&(s.federation=s.federation.filter(e=>e!==n),s.timestamp=Date.now(),await e.writeGlobal("federation",s));let r=await e.readGlobal("federation",n);r&&r.notify&&(r.notify=r.notify.filter(e=>e!==t),r.timestamp=Date.now(),await e.writeGlobal("federation",r));const i=`${t}_${n}`,a=`${n}_${t}`;let o=await e.readGlobal("federationMeta",i);return o||(o=await e.readGlobal("federationMeta",a)),o&&(o.status="inactive",o.endedAt=Date.now(),await e.writeGlobal("federationMeta",o)),!0}catch(s){throw console.error(`Federation removal failed: ${s.message}`),s}}async function resetFederation(e,t,n={}){if(!t)throw new Error("resetFederation: Missing required space ID");const{notifyPartners:s=!0,spaceName:r=null}=n,i={success:!1,federatedCount:0,notifyCount:0,partnersNotified:0,errors:[]};try{const n=await getFederation(e,t);if(!n)return{...i,success:!0,message:"No federation configuration found for this space"};i.federatedCount=n.federation?.length||0,i.notifyCount=n.notify?.length||0;const o={id:t,name:r||t,federation:[],notify:[],timestamp:Date.now()};if(await e.writeGlobal("federation",o),s&&n.federation&&n.federation.length>0)for(const s of n.federation)try{const n=await getFederation(e,s);n&&(n.federation&&(n.federation=n.federation.filter(e=>e!==t.toString())),n.notify&&(n.notify=n.notify.filter(e=>e!==t.toString())),n.timestamp=Date.now(),await e.writeGlobal("federation",n),i.partnersNotified++)}catch(a){i.errors.push({partner:s,error:a.message})}if(n.federation&&n.federation.length>0)for(const s of n.federation)try{const n=`${t}_${s}`,r=`${s}_${t}`;let i=await e.readGlobal("federationMeta",n);i||(i=await e.readGlobal("federationMeta",r)),i&&(i.status="inactive",i.endedAt=Date.now(),await e.writeGlobal("federationMeta",i))}catch(a){}return i.success=!0,i}catch(a){return console.error(`Federation reset failed: ${a.message}`),{...i,success:!1,error:a.message}}}async function propagate(e,t,n,s,r={}){if(!(e&&t&&n&&s))throw new Error("propagate: Missing required parameters");const{useReferences:i=!0,targetSpaces:a=null}=r,o={success:0,errors:0,errorDetails:[],propagated:!1,referencesUsed:i};try{const r=await getFederation(e,t);if(!r||!r.federation||0===r.federation.length)return{...o,message:`No federation found for ${t}`};if(!r.notify||0===r.notify.length)return{...o,message:`No notification targets found for ${t}`};let c=r.notify;if(a&&Array.isArray(a)&&a.length>0&&(c=c.filter(e=>a.includes(e))),0===c.length)return{...o,message:"No valid target spaces found after filtering"};const u=e.isReference(s);for(const a of c)try{if(i&&!u){const r=e.createReference(t,n,s);r._federation={origin:t,lens:n,timestamp:Date.now()};const i=e.buildPath(e.appName,a,n,r.id);await e.write(i,r),o.success++}else if(u){const r={...s,_federation:s._federation||{origin:t,lens:n,timestamp:Date.now()}},i=e.buildPath(e.appName,a,n,s.id);await e.write(i,r),o.success++}else{const r={...s,_federation:{origin:t,lens:n,timestamp:Date.now()}},i=e.buildPath(e.appName,a,n,s.id);await e.write(i,r),o.success++}}catch(l){o.errors++,o.errorDetails.push({space:a,error:l.message})}return o.propagated=o.success>0,o}catch(l){return console.error("Error in propagate:",l),{...o,error:l.message}}}async function getFederated(e,t,n,s={}){const{aggregate:r=!1,idField:i="id",sumFields:a=[],concatArrays:o=[],removeDuplicates:l=!0,mergeStrategy:c=null,includeLocal:u=!0,includeFederated:d=!0,resolveReferences:f=!0,maxFederatedSpaces:h=-1,timeout:p=1e4}=s;if(!e||!t||!n)throw new Error("Missing required parameters: backend, holon, and lens are required");const y=await getFederation(e,t),g=[],m=new Set;if(d&&y&&y.federation&&y.federation.length>0){const t=-1===h?y.federation:y.federation.slice(0,h);for(const s of t)try{const t=e.buildPath(e.appName,s,n),r=await e.readAll(t);for(const e of r)e&&e[i]&&(g.push(e),m.add(e[i]))}catch(b){console.warn(`Error processing federated space ${s}: ${b.message}`)}}if(u){const s=e.buildPath(e.appName,t,n),r=await e.readAll(s);for(const e of r)e&&e[i]&&!m.has(e[i])&&(g.push(e),m.add(e[i]))}if(f)for(let w=0;w<g.length;w++){const t=g[w];if(t.soul&&t.id)try{const n=await e.resolveReference(t);n&&(g[w]=n)}catch(b){g[w]={id:t.id,_federation:{isReference:!0,resolved:!1,soul:t.soul,error:b.message,timestamp:Date.now()}}}else if(t._federation&&t._federation.isReference)try{const n=await e.resolveReference(t);n&&(g[w]=n)}catch(b){console.warn(`Error resolving legacy reference: ${b.message}`)}}if(r&&g.length>0){const e=g.reduce((e,t)=>{const n=t[i];return e[n]||(e[n]=[]),e[n].push(t),e},{});return Object.values(e).map(e=>{if(1===e.length)return e[0];if(c&&"function"==typeof c)return c(e);const t={...e[0]};for(const n of a)"number"==typeof t[n]&&(t[n]=e.reduce((e,t)=>e+(Number(t[n])||0),0));for(const n of o)if(Array.isArray(t[n])){const s=e.reduce((e,t)=>Array.isArray(t[n])?[...e,...t[n]]:e,[]);t[n]=l?Array.from(new Set(s)):s}return t._aggregated={count:e.length,timestamp:Date.now()},t})}return g}async function subscribeFederation(e,t,n,s={}){if(!t||!n)throw new Error("subscribeFederation: Missing required parameters");const{lenses:r=["*"],throttle:i=0,resolveReferences:a=!0}=s,o=await getFederation(e,t);if(!o)throw new Error("No federation info found for space");const l=[];let c={};if(o.federation&&o.federation.length>0)for(const d of o.federation)for(const t of r)try{const s=e.buildPath(e.appName,d,t),r=await e.subscribe(s,async(s,r)=>{try{if(!s||!s.id)return;const r=Date.now(),o=`${d}_${t}_${s.id}`;if(i>0){if(c[o]&&r-c[o]<i)return;c[o]=r}let l=s;a&&e.isReference(s)&&(l=await e.resolveReference(s)),l._federation||(l._federation={origin:d,timestamp:r}),await n(l,d,t)}catch(o){console.warn("Federation notification error:",o)}},{resolveReferences:!1});r&&"function"==typeof r.unsubscribe&&l.push(r)}catch(u){console.warn(`Error creating subscription for ${d}/${t}:`,u)}return{unsubscribe:()=>{l.forEach(e=>{try{e&&"function"==typeof e.unsubscribe&&e.unsubscribe()}catch(u){console.warn("Error unsubscribing:",u)}}),l.length=0,c={}},getSubscriptionCount:()=>l.length}}async function federateMessage(e,t,n,s,r,i="generic"){const a=`${t}_${n}_fedmsgs`;let o=await e.readGlobal("federation_messages",a);o||(o={id:a,originalChatId:t,originalMessageId:n,type:i,messages:[]});const l=o.messages.find(e=>e.chatId===s);l?(l.messageId=r,l.timestamp=Date.now()):o.messages.push({chatId:s,messageId:r,timestamp:Date.now()}),await e.writeGlobal("federation_messages",o)}async function getFederatedMessages(e,t,n){const s=`${t}_${n}_fedmsgs`;return e.readGlobal("federation_messages",s)}async function updateFederatedMessages(e,t,n,s){const r=await getFederatedMessages(e,t,n);if(r?.messages)for(const a of r.messages)try{await s(a.chatId,a.messageId)}catch(i){console.warn(`Failed to update federated message in chat ${a.chatId}:`,i)}}class StorageBackend{constructor(e){if(new.target===StorageBackend)throw new Error("StorageBackend is abstract and cannot be instantiated directly");this.config=e,this.publicKey=null}async init(){throw new Error("init() must be implemented by subclass")}buildPath(e,t,n,s=null){throw new Error("buildPath() must be implemented by subclass")}async write(e,t,n={}){throw new Error("write() must be implemented by subclass")}async read(e,t={}){throw new Error("read() must be implemented by subclass")}async readAll(e,t={}){throw new Error("readAll() must be implemented by subclass")}async update(e,t){throw new Error("update() must be implemented by subclass")}async delete(e){throw new Error("delete() must be implemented by subclass")}async deleteAll(e){throw new Error("deleteAll() must be implemented by subclass")}async subscribe(e,t,n={}){throw new Error("subscribe() must be implemented by subclass")}async exportData(e=""){throw new Error("exportData() must be implemented by subclass")}async importData(e,t={}){throw new Error("importData() must be implemented by subclass")}close(){throw new Error("close() must be implemented by subclass")}getStatus(){throw new Error("getStatus() must be implemented by subclass")}}class GunReferenceHandler{constructor(e){this.appname=e}createReference(e,t,n){if(!n||!n.id)throw new Error("createReference: data must have an id field");return{id:n.id,soul:`${this.appname}/${e}/${t}/${n.id}`}}isReference(e){return!!e&&(!!(e.soul&&e.id&&Object.keys(e).filter(e=>!e.startsWith("_")).length<=2)||(!(!e._federation||!e._federation.isReference)||!(!e._||!e._["#"])))}parseSoulPath(e){if(!e||"string"!=typeof e)return null;const t=e.split("/");return t.length<4?null:{appname:t[0],holon:t[1],lens:t[2],key:t.slice(3).join("/")}}async resolveReference(e,t,n={}){const{followReferences:s=!0}=n;if(!t)return null;let r=null,i=null;if(t.soul)r=t.soul;else if(t._federation&&t._federation.isReference){const e=t._federation;e.origin&&e.lens&&t.id&&(r=`${this.appname}/${e.origin}/${e.lens}/${t.id}`,i=e)}else t._&&t._["#"]&&(r=t._["#"]);if(!r)return null;const a=this.parseSoulPath(r);if(!a)return null;try{const t=`${a.appname}/${a.holon}/${a.lens}/${a.key}`,n=await read$2(e,t);if(!n)return null;if(s&&this.isReference(n)){const t=await this.resolveReference(e,n,{followReferences:!0});if(t)return{...t,_federation:{resolved:!0,soul:r,origin:a.holon,lens:a.lens,timestamp:Date.now()}}}return{...n,_federation:{resolved:!0,soul:r,origin:i?.origin||a.holon,lens:i?.lens||a.lens,timestamp:Date.now()}}}catch(o){return console.warn("Error resolving reference:",o),null}}getSoul(e,t,n){return`${this.appname}/${e}/${t}/${n}`}}class GunAuth{constructor(e,t){this.gun=e,this.appname=t,this.user=null,this.authenticated=!1,this.currentHolonId=null}userName(e){return`${this.appname}:${e}`}async authenticate(e,t){if(!e||!t)throw new Error("authenticate: holonId and password are required");const n=this.userName(e);return this.user=this.gun.user(),new Promise((s,r)=>{this.user.auth(n,t,t=>{t.err?(this.authenticated=!1,this.currentHolonId=null,r(new Error(t.err))):(this.authenticated=!0,this.currentHolonId=e,s(this.user))})})}async createUser(e,t){if(!e||!t)throw new Error("createUser: holonId and password are required");const n=this.userName(e);return this.user=this.gun.user(),new Promise((s,r)=>{this.user.create(n,t,i=>{i.err?r(new Error(i.err)):this.user.auth(n,t,t=>{t.err?r(new Error(t.err)):(this.authenticated=!0,this.currentHolonId=e,s(this.user))})})})}logout(){this.user&&this.user.leave(),this.authenticated=!1,this.currentHolonId=null,this.user=null}isAuthenticated(){return this.authenticated&&null!==this.user}getPrivatePath(e,t=null){if(!this.isAuthenticated())throw new Error("Not authenticated");const n=this.user.get("private").get(e);return t?n.get(t):n}async writePrivate(e,t,n){if(!this.isAuthenticated())throw new Error("Not authenticated");if(!n||!t)throw new Error("writePrivate: key and data are required");try{const s=JSON.stringify(n);return await gunPut(this.getPrivatePath(e,t),s,2e3),!0}catch(s){throw s}}async readPrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const s=await gunPromise(this.getPrivatePath(e,t),2e3);if(!s)return null;if("string"==typeof s)try{return JSON.parse(s)}catch(n){return s}if(s._json&&"string"==typeof s._json)try{return JSON.parse(s._json)}catch(n){return null}if("object"==typeof s){const e={...s};return delete e._,e}return null}catch(s){throw s}}async readAllPrivate(e,t=5e3){if(!this.isAuthenticated())throw new Error("Not authenticated");return new Promise(n=>{const s=[],r=new Set,i=this.getPrivatePath(e);let a=!1,o=0,l=0;const c=e=>{if(!e)return null;let t=null;if("string"==typeof e)try{t=JSON.parse(e)}catch(n){t=e}else if(e._json&&"string"==typeof e._json)try{t=JSON.parse(e._json)}catch(n){}else"object"==typeof e&&(t={...e},delete t._);return t};i.once(e=>{if(a)return;if(!e)return a=!0,void n([]);const t=Object.keys(e).filter(e=>"_"!==e);if(0===t.length)return a=!0,void n([]);for(const n of t){const t=e[n];if(!t)continue;if("object"==typeof t&&t["#"])continue;const i=c(t);!i||i._deleted||r.has(n)||(r.add(n),s.push(i))}o=t.length,i.map().once((e,t)=>{if(!a&&e&&!t.startsWith("_")){if(!r.has(t)){r.add(t);const n=c(e);n&&!n._deleted&&s.push(n)}l++,a||o>0&&l>=o&&(a=!0,n(s))}})}),setTimeout(()=>{a||(a=!0,n(s))},t)})}async deletePrivate(e,t){if(!this.isAuthenticated())throw new Error("Not authenticated");try{const n=await this.readPrivate(e,t),s={id:n?.id||t,_deleted:!0,_deletedAt:Date.now()};return await gunPut(this.getPrivatePath(e,t),JSON.stringify(s)),!0}catch(n){throw n}}}const META_SCHEMA={type:"object",required:["type"],properties:{$schema:{type:"string"},$id:{type:"string"},type:{type:"string"},properties:{type:"object"},required:{type:"array",items:{type:"string"}},additionalProperties:{type:"boolean"}}};class GunSchemaValidator{constructor(e={}){this.strict=e.strict||!1,this.cacheMaxAge=e.cacheMaxAge||36e5,this.schemaCache=new Map,this.validator=null,this.Ajv=null}async init(){if(this.validator)return!0;try{const e=await Promise.resolve().then(()=>require("./2019-C1hPR_Os.cjs")).then(e=>e._2019);return this.Ajv=e.default||e,this.validator=new this.Ajv({allErrors:!0,strict:!1,validateSchema:!0}),!0}catch(e){return console.warn("AJV not available, schema validation disabled:",e.message),!1}}async setSchema(e,t,n,s){if(!s||"object"!=typeof s)throw new Error("setSchema: schema must be an object");if(this.strict&&this.validator){if(!this.validateSchema(META_SCHEMA,s))throw new Error("setSchema: Invalid schema definition")}const r={id:n,lens:n,schema:s,timestamp:Date.now()};return await writeGlobal$1(e,t,"schemas",r),this.schemaCache.set(n,{schema:s,timestamp:Date.now()}),!0}async getSchema(e,t,n,s={}){const{useCache:r=!0}=s;if(r){const e=this.schemaCache.get(n);if(e&&Date.now()-e.timestamp<this.cacheMaxAge)return e.schema}const i=await readGlobal$1(e,t,"schemas",n);return i&&i.schema?(this.schemaCache.set(n,{schema:i.schema,timestamp:Date.now()}),i.schema):null}async getAllSchemas(e,t){return readAllGlobal(e,t,"schemas")}async deleteSchema(e,t,n){return this.schemaCache.delete(n),deleteGlobal$1(e,t,"schemas",n)}validate(e,t){if(!this.validator)return{valid:!0,errors:[]};try{const n=this.validator.compile(e),s=n(t);return{valid:s,errors:s?[]:this.formatErrors(n.errors)}}catch(n){return{valid:!1,errors:[{message:n.message,path:""}]}}}async validateData(e,t,n,s){const r=await this.getSchema(e,t,n);return r?this.validate(r,s):{valid:!0,errors:[]}}validateSchema(e,t){if(!this.validator)return!0;try{return this.validator.compile(e)(t)}catch(n){return!1}}formatErrors(e){return e?e.map(e=>({message:e.message||"Validation error",path:e.instancePath||e.dataPath||"",keyword:e.keyword,params:e.params})):[]}clearCache(e=null){e?this.schemaCache.delete(e):this.schemaCache.clear()}isStrict(){return this.strict}setStrict(e){this.strict=e}}class GunDBBackend extends StorageBackend{constructor(e){super(e),this.gun=null,this.keyPair=null,this.appName=e.appName||"holosphere",this.references=null,this.auth=null,this.schemaValidator=null,this.subscriptions=new Map,this.subscriptionCounter=0,this.writeCache=new Map,this.writeCacheTTL=3e5,this.pendingWrites=new Map,this.maxWriteRetries=5,this.writeRetryInterval=1e4}async init(){let e;try{console.log("[gundb-backend] Importing Gun...");const t=await Promise.resolve().then(()=>require("./browser-DaqYUTcG.cjs")).then(e=>e.browser);e=t.default||t,console.log("[gundb-backend] Gun imported:",typeof e)}catch(s){throw new Error('GunDB backend requires the "gun" package. Install it with: npm install gun')}const t=this.config.dataDir||"radata",n={peers:this.config.peers||[],radisk:!1!==this.config.radisk,localStorage:!1!==this.config.localStorage,file:t};console.log("[gundb-backend] Gun config:",JSON.stringify(n)),this.gun=e(n),console.log("[gundb-backend] Gun instance created:",!!this.gun);try{const e=`_test_${Date.now()}`;this.gun.get(e).put({test:!0},e=>{console.log("[gundb-backend] Gun test write ack:",e)}),console.log("[gundb-backend] Gun test write initiated")}catch(r){console.error("[gundb-backend] Gun test write failed:",r.message)}await new Promise(e=>setTimeout(e,500));try{const t=e.SEA;t?this.config.privateKey?(this.keyPair={priv:this.config.privateKey,pub:this.config.publicKey},this.publicKey=this.config.publicKey||this.config.privateKey.substring(0,32)):(this.keyPair=await t.pair(),this.publicKey=this.keyPair.pub):this.publicKey=this.appName}catch(s){this.publicKey=this.appName}this.references=new GunReferenceHandler(this.appName),this.auth=new GunAuth(this.gun,this.appName),this.schemaValidator=new GunSchemaValidator({strict:this.config.strict||!1,cacheMaxAge:this.config.schemaCacheMaxAge||36e5}),await this.schemaValidator.init()}_addToWriteCache(e,t){if(!t||!t.id)return;const n=e.substring(0,e.lastIndexOf("/"));if(!n)return;this.writeCache.has(n)||this.writeCache.set(n,new Map);this.writeCache.get(n).set(t.id.toString(),{data:t,timestamp:Date.now()})}_removeFromWriteCache(e,t){const n=e.substring(0,e.lastIndexOf("/")),s=this.writeCache.get(n);s&&s.delete(t.toString())}_getWriteCacheEntries(e){const t=this.writeCache.get(e);if(!t)return[];const n=Date.now(),s=[];for(const[r,i]of t)n-i.timestamp<this.writeCacheTTL?s.push(i.data):t.delete(r);return s}_mergeWithWriteCache(e,t){const n=this._getWriteCacheEntries(e);if(0===n.length)return t;const s=new Map;for(const r of t)r&&r.id&&s.set(r.id.toString(),r);for(const r of n)r&&r.id&&!r._deleted?s.set(r.id.toString(),r):r&&r.id&&r._deleted&&s.delete(r.id.toString());return Array.from(s.values())}clearWriteCache(e=null){e?this.writeCache.delete(e):this.writeCache.clear()}buildPath(e,t,n,s=null){return buildPath$2(e,t,n,s)}buildGlobalPath(e,t=null){return buildGlobalPath(this.appName,e,t)}async write(e,t,n={}){if(this.schemaValidator&&this.schemaValidator.isStrict()){const n=e.split("/");if(n.length>=3){const e=n[2];if(!this.isReference(t)){const n=await this.schemaValidator.validateData(this.gun,this.appName,e,t);if(!n.valid)throw new Error(`Schema validation failed: ${JSON.stringify(n.errors)}`)}}}this._addToWriteCache(e,t);return await this._writeWithRetry(e,t)}async _writeWithRetry(e,t,n=0){const s=await write$2(this.gun,e,t);return s.timeout&&n<this.maxWriteRetries?(this.pendingWrites.set(e,{data:t,retries:n+1,lastAttempt:Date.now()}),this._scheduleRetry(e)):s.timeout||this.pendingWrites.delete(e),s}_scheduleRetry(e){setTimeout(async()=>{const t=this.pendingWrites.get(e);if(t){if(t.retries>=this.maxWriteRetries)return console.warn(`[gundb-backend] Max retries reached for: ${e}`),void this.pendingWrites.delete(e);console.log(`[gundb-backend] Retrying write (attempt ${t.retries+1}): ${e}`),await this._writeWithRetry(e,t.data,t.retries)}},this.writeRetryInterval)}async read(e,t={}){const n=await read$2(this.gun,e);return n&&t.resolveReferences&&this.isReference(n)?this.resolveReference(n):n}async readAll(e,t={}){const n=await readAll$2(this.gun,e),s=this._mergeWithWriteCache(e,n);if(t.resolveReferences){const e=[];for(const t of s)if(this.isReference(t)){const n=await this.resolveReference(t);n&&e.push(n)}else e.push(t);return e}return s}async update(e,t){return update$2(this.gun,e,t)}async delete(e){const t=await deleteData$2(this.gun,e),n=e.split("/"),s=n[n.length-1];if(s){const t=e.substring(0,e.lastIndexOf("/"));this.writeCache.has(t)||this.writeCache.set(t,new Map),this.writeCache.get(t).set(s.toString(),{data:{id:s,_deleted:!0},timestamp:Date.now()})}return t}async deleteAll(e){const t=await this.readAll(e);let n=0;for(const s of t)if(s&&s.id){const t=`${e}/${s.id}`;await deleteData$2(this.gun,t),n++}return{success:!0,count:n}}async writeGlobal(e,t){const n=this.buildGlobalPath(e,t.id);this._addToWriteCache(n,t);return await this._writeGlobalWithRetry(e,t)}async _writeGlobalWithRetry(e,t,n=0){const s=this.buildGlobalPath(e,t.id),r=await writeGlobal$1(this.gun,this.appName,e,t);return r.timeout&&n<this.maxWriteRetries?(this.pendingWrites.set(s,{data:{tableName:e,data:t},isGlobal:!0,retries:n+1,lastAttempt:Date.now()}),this._scheduleGlobalRetry(s,e)):r.timeout||this.pendingWrites.delete(s),r}_scheduleGlobalRetry(e,t){setTimeout(async()=>{const n=this.pendingWrites.get(e);if(n&&n.isGlobal){if(n.retries>=this.maxWriteRetries)return console.warn(`[gundb-backend] Max retries reached for global: ${e}`),void this.pendingWrites.delete(e);console.log(`[gundb-backend] Retrying global write (attempt ${n.retries+1}): ${e}`),await this._writeGlobalWithRetry(t,n.data.data,n.retries)}},this.writeRetryInterval)}async readGlobal(e,t){return readGlobal$1(this.gun,this.appName,e,t)}async readAllGlobal(e,t=5e3){const n=await readAllGlobal(this.gun,this.appName,e,t),s=this.buildGlobalPath(e);return this._mergeWithWriteCache(s,n)}async deleteGlobal(e,t){const n=await deleteGlobal$1(this.gun,this.appName,e,t),s=this.buildGlobalPath(e);return this.writeCache.has(s)||this.writeCache.set(s,new Map),this.writeCache.get(s).set(t.toString(),{data:{id:t,_deleted:!0},timestamp:Date.now()}),n}async deleteAllGlobal(e){return deleteAllGlobal$1(this.gun,this.appName,e)}createReference(e,t,n){return this.references.createReference(e,t,n)}isReference(e){return this.references.isReference(e)}async resolveReference(e,t={}){return this.references.resolveReference(this.gun,e,t)}parseSoulPath(e){return this.references.parseSoulPath(e)}getSoul(e,t,n){return this.references.getSoul(e,t,n)}async authenticate(e,t){return this.auth.authenticate(e,t)}async createUser(e,t){return this.auth.createUser(e,t)}logout(){this.auth.logout()}isAuthenticated(){return this.auth.isAuthenticated()}async writePrivate(e,t,n){return this.auth.writePrivate(e,t,n)}async readPrivate(e,t){return this.auth.readPrivate(e,t)}async readAllPrivate(e,t=2e3){return this.auth.readAllPrivate(e,t)}async deletePrivate(e,t){return this.auth.deletePrivate(e,t)}async setSchema(e,t){return this.schemaValidator.setSchema(this.gun,this.appName,e,t)}async getSchema(e,t={}){return this.schemaValidator.getSchema(this.gun,this.appName,e,t)}async getAllSchemas(){return this.schemaValidator.getAllSchemas(this.gun,this.appName)}async deleteSchema(e){return this.schemaValidator.deleteSchema(this.gun,this.appName,e)}validate(e,t){return this.schemaValidator.validate(e,t)}async validateData(e,t){return this.schemaValidator.validateData(this.gun,this.appName,e,t)}clearSchemaCache(e=null){this.schemaValidator.clearCache(e)}async subscribe(e,t,n={}){const s=++this.subscriptionCounter,r=e.split("/").length<=3,i={id:s,path:e,active:!0,gunRef:null};if(r){const r=this.gun.get(e);i.gunRef=r,r.map().on(async(e,r)=>{if(!this.subscriptions.get(s)?.active)return;if(!e||r.startsWith("_")||e._deleted)return;let i=parse(e);i&&(n.resolveReferences&&this.isReference(i)&&(i=await this.resolveReference(i)),i&&t(i,r))})}else{const r=this.gun.get(e);i.gunRef=r,r.on(async(e,r)=>{if(!this.subscriptions.get(s)?.active)return;if(!e)return;let i=parse(e);i&&!i._deleted&&(n.resolveReferences&&this.isReference(i)&&(i=await this.resolveReference(i)),i&&t(i,r))})}return this.subscriptions.set(s,i),{id:s,unsubscribe:()=>{const e=this.subscriptions.get(s);if(e){if(e.active=!1,e.gunRef)try{e.gunRef.off()}catch(t){}this.subscriptions.delete(s)}}}}async exportData(e=""){const t=[],n=e||this.appName;try{const e=await gunMap(this.gun.get(n),2e3);for(const[s,r]of Object.entries(e))s.startsWith("_")||!r||"object"!=typeof r||r._deleted||await this._collectRecords(n,s,r,t)}catch(s){console.warn("Export data error:",s)}return t}async _collectRecords(e,t,n,s){const r=`${e}/${t}`;if(n.id)s.push({path:r,data:this._cleanGunData(n),timestamp:n._meta?.timestamp||Date.now()});else try{const e=await gunMap(this.gun.get(r),500);for(const[t,n]of Object.entries(e))!t.startsWith("_")&&n&&await this._collectRecords(r,t,n,s)}catch(i){}}_cleanGunData(e){const t={...e};return delete t._,t}async importData(e,t={}){const n={success:0,failed:0,errors:[]};for(const r of e)try{await write$2(this.gun,r.path,r.data),n.success++}catch(s){n.failed++,n.errors.push({path:r.path,error:s.message})}return n}close(){for(const[n,s]of this.subscriptions)if(s.active&&(s.active=!1,s.gunRef))try{s.gunRef.off()}catch(e){}if(this.subscriptions.clear(),this.schemaValidator&&this.schemaValidator.clearCache(),this.writeCache.clear(),this.auth&&this.auth.logout(),this.gun)try{const e=this.gun.back("opt.mesh");e&&(e.way&&Object.values(e.way).forEach(e=>{e?.wire?.close&&e.wire.close()}),e.opt?.peers&&(e.opt.peers={}));const t=this.gun.back("opt.web");t?.close&&t.close(),this.gun.off()}catch(t){console.warn("Error during Gun cleanup:",t)}}getStatus(){return{type:"gundb",publicKey:this.publicKey,peers:this.config.peers||[],connected:!!this.gun,authenticated:this.isAuthenticated(),subscriptionCount:this.subscriptions.size,schemaValidationEnabled:this.schemaValidator?.isStrict()||!1}}}const name="holosphere",version$1="2.0.0-alpha19",description="Holonic geospatial communication infrastructure combining H3 hexagonal indexing with distributed P2P storage",type="module",bin={"holosphere-activitypub":"bin/holosphere-activitypub.js"},main="./dist/cjs/holosphere.cjs",module$1="./dist/esm/holosphere.js",browser="./dist/cdn/holosphere.min.js",types="./types/index.d.ts",exports$1={".":{import:"./dist/esm/holosphere.js",require:"./dist/cjs/holosphere.cjs"}},scripts={dev:"vite",build:"vite build","build:cdn":"vite build --config vite.config.cdn.js","build:all":"npm run build && npm run build:cdn",docs:"jsdoc -c jsdoc.json",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage","test:real-relays":"USE_REAL_RELAYS=true vitest run","test:integration:real":"USE_REAL_RELAYS=true vitest run tests/unit/integration",lint:"eslint src tests",format:'prettier --write "src/**/*.js" "tests/**/*.js"'},keywords=["geospatial","h3","gundb","p2p","distributed","holonic","federation","noosphere","smart-contracts","ethereum","erc20","fractal"],author="Roberto Valenti",license="AGPL-3.0-or-later",repository={type:"git",url:"https://github.com/liminalvillage/holosphere2.git"},homepage="https://github.com/liminalvillage/holosphere2#readme",bugs={url:"https://github.com/liminalvillage/holosphere2/issues"},dependencies={"@noble/curves":"^1.3.0","@nostr-dev-kit/ndk":"^2.10.0",ajv:"^8.12.0",dotenv:"^17.2.3",ethers:"^6.13.4",express:"^4.21.0","h3-js":"^4.1.0","nostr-tools":"^2.17.0",openai:"^4.85.1",ws:"^8.18.3"},optionalDependencies={"@nostr-dev-kit/ndk-cache-dexie":"^2.5.0",gun:"^0.2020.1241"},devDependencies={"@vitest/coverage-v8":"^1.3.0","clean-jsdoc-theme":"^4.3.0",eslint:"^8.57.0",jsdoc:"^4.0.4",prettier:"^3.2.5",terser:"^5.44.0",vite:"^5.1.0",vitest:"^1.3.0"},engines={node:">=18.0.0"},pkg={name:name,version:version$1,description:description,type:type,bin:bin,main:main,module:module$1,browser:browser,types:types,exports:exports$1,scripts:scripts,keywords:keywords,author:author,license:license,repository:repository,homepage:homepage,bugs:bugs,dependencies:dependencies,optionalDependencies:optionalDependencies,devDependencies:devDependencies,engines:engines};function getEnv(e){if("undefined"!=typeof process&&process.env)return process.env[e]}function getDefaultRelays(){const e=getEnv("HOLOSPHERE_RELAYS");return e?e.split(",").map(e=>e.trim()).filter(e=>e):["wss://relay.holons.io"]}let HoloSphere$1=class{constructor(e={}){if("string"==typeof e&&(e={appName:e}),e&&"object"!=typeof e)throw new TypeError("Config must be an object");if(void 0!==e.appName&&"string"!=typeof e.appName)throw new TypeError("config.appName must be a string");if(void 0!==e.relays&&!Array.isArray(e.relays))throw new TypeError("config.relays must be an array");if(void 0!==e.logLevel&&!["ERROR","WARN","INFO","DEBUG"].includes(e.logLevel))throw new TypeError("config.logLevel must be one of: ERROR, WARN, INFO, DEBUG");if(void 0!==e.backend&&!BackendFactory.isAvailable(e.backend))throw new TypeError(`config.backend must be one of: ${BackendFactory.getAvailableBackends().join(", ")}`);this.config={appName:e.appName||getEnv("HOLOSPHERE_APP_NAME")||"holosphere",backend:e.backend||"nostr",relays:e.relays||getDefaultRelays(),privateKey:e.privateKey||getEnv("HOLOSPHERE_PRIVATE_KEY"),logLevel:e.logLevel||getEnv("HOLOSPHERE_LOG_LEVEL")||"INFO",hybridMode:!1!==e.hybridMode},this._rawConfig=e,this.logLevels={ERROR:0,WARN:1,INFO:2,DEBUG:3},this.currentLogLevel=this.logLevels[this.config.logLevel]||1,this._backend=null,"nostr"===this.config.backend?this._initNostrSync(e):"gundb"===this.config.backend?this._backendReady=this._initGunDBAsync(e):this._backendReady=this._initBackendAsync(e),this._metrics={writes:0,reads:0,subscriptions:0}}_initNostrSync(e){try{this.client=createClient({relays:this.config.relays,privateKey:this.config.privateKey,enableReconnect:!1!==e.enableReconnect,enablePing:!1!==e.enablePing,appName:this.config.appName,radisk:!1!==e.radisk,persistence:!1!==e.persistence,dataDir:e.dataDir}),this._logStartup({version:pkg.version,appName:this.config.appName,backend:"nostr",relays:this.config.relays,publicKey:this.client.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,reconnect:!1!==e.enableReconnect,dataDir:e.dataDir}),this._backendReady=Promise.resolve()}catch(t){throw this._log("ERROR","Nostr client initialization failed",{error:t.message}),new Error(`Nostr client initialization failed: ${t.message}`)}}async _initGunDBAsync(e){try{const t=e.gundb||{};this._backend=new GunDBBackend({appName:this.config.appName,peers:t.peers||[],radisk:!1!==t.radisk,localStorage:!1!==t.localStorage,dataDir:e.dataDir,privateKey:this.config.privateKey,strict:t.strict||!1,schemaCacheMaxAge:t.schemaCacheMaxAge||36e5}),await this._backend.init(),this.publicKey=this._backend.publicKey,this._gun=this._backend.gun,this.client={publicKey:this.publicKey,gun:this._gun,write:(e,t)=>this._backend.write(e,t),read:(e,t)=>this._backend.read(e,t),readAll:(e,t)=>this._backend.readAll(e,t),update:(e,t)=>this._backend.update(e,t),delete:e=>this._backend.delete(e),subscribe:(e,t,n)=>this._backend.subscribe(e,t,n),buildPath:buildPath$2},this._gunWrapper=gunWrapper,this._logStartup({version:pkg.version,appName:this.config.appName,backend:"gundb",peers:t.peers||[],publicKey:this.publicKey,logLevel:this.config.logLevel,persistence:!1!==t.radisk,dataDir:e.dataDir})}catch(t){throw this._log("ERROR","GunDB client initialization failed",{error:t.message}),new Error(`GunDB client initialization failed: ${t.message}`)}}async _initBackendAsync(e){const t=this.config.backend,n=e[t]||{};try{const s={appName:this.config.appName,privateKey:this.config.privateKey,persistence:!1!==e.persistence,dataDir:e.dataDir,...n};this._backend=await BackendFactory.create(t,s),this.client=this._backend.client||this._backend,this._logStartup({version:pkg.version,appName:this.config.appName,backend:t,publicKey:this._backend.publicKey,logLevel:this.config.logLevel,persistence:!1!==e.persistence,...this._backend.getStatus()})}catch(s){throw this._log("ERROR",`${t} backend initialization failed`,{error:s.message}),new Error(`${t} backend initialization failed: ${s.message}`)}}async ready(){this._backendReady&&await this._backendReady}get backend(){return this._backend}_log(e,t,n={}){if(this.logLevels[e]<=this.currentLogLevel){const s={timestamp:Date.now(),level:e,message:t,app:this.config.appName,...n};console.log(JSON.stringify(s))}}_logStartup(e){this.currentLogLevel>=this.logLevels.INFO&&(console.log("\n"+"=".repeat(60)),console.log(" HoloSphere - Holonic Geospatial Infrastructure"),console.log("=".repeat(60)),console.log(` Version: ${e.version}`),console.log(` App Name: ${e.appName}`),console.log(` Backend: ${e.backend||"nostr"}`),console.log(" Public Key: "+(e.publicKey?e.publicKey.substring(0,16)+"...":"N/A")),console.log(` Log Level: ${e.logLevel}`),console.log(` Persistence: ${e.persistence?"Enabled":"Disabled"}${e.dataDir?` (${e.dataDir})`:""}`),"nostr"!==e.backend&&e.backend?"gundb"===e.backend?(console.log("\n Gun Peers:"),e.peers&&0!==e.peers.length?e.peers.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")):"activitypub"===e.backend&&(console.log(` Server URL: ${e.serverUrl||"N/A"}`),console.log(` Actor ID: ${e.actorId||"N/A"}`)):(console.log(" Auto-reconnect: "+(e.reconnect?"Enabled":"Disabled")),console.log("\n Connected Relays:"),e.relays&&0!==e.relays.length?e.relays.forEach((e,t)=>{console.log(` ${t+1}. ${e}`)}):console.log(" (none - running in local mode)")),console.log("=".repeat(60)+"\n"))}metrics(){return{...this._metrics}}_requireGunDB(){if("gundb"!==this.config.backend)throw new Error("This method requires the GunDB backend");if(!this._backend)throw new Error("Backend not initialized. Call ready() first.")}async putGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.writeGlobal(e,t)}async getGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.readGlobal(e,t)}async getAllGlobal(e){return await this.ready(),this._requireGunDB(),this._backend.readAllGlobal(e)}async deleteGlobal(e,t){return await this.ready(),this._requireGunDB(),this._backend.deleteGlobal(e,t)}createReference(e,t,n){return this._requireGunDB(),this._backend.createReference(e,t,n)}isReference(e){return this._requireGunDB(),this._backend.isReference(e)}async resolveReference(e,t={}){return await this.ready(),this._requireGunDB(),this._backend.resolveReference(e,t)}async authenticate(e,t){return await this.ready(),this._requireGunDB(),this._backend.authenticate(e,t)}async createUser(e,t){return await this.ready(),this._requireGunDB(),this._backend.createUser(e,t)}logout(){this._requireGunDB(),this._backend.logout()}isAuthenticated(){return this._requireGunDB(),this._backend.isAuthenticated()}async writePrivate(e,t,n){return await this.ready(),this._requireGunDB(),this._backend.writePrivate(e,t,n)}async readPrivate(e,t){return await this.ready(),this._requireGunDB(),this._backend.readPrivate(e,t)}async setSchema(e,t){return await this.ready(),this._requireGunDB(),this._backend.setSchema(e,t)}async getSchema(e){return await this.ready(),this._requireGunDB(),this._backend.getSchema(e)}async validateData(e,t){return await this.ready(),this._requireGunDB(),this._backend.validateData(e,t)}async federate(e,t,n=!0){return await this.ready(),this._requireGunDB(),federate(this._backend,e,t,n)}async unfederate(e,t){return await this.ready(),this._requireGunDB(),unfederate(this._backend,e,t)}async getFederation(e){return await this.ready(),this._requireGunDB(),getFederation(this._backend,e)}async resetFederation(e,t={}){return await this.ready(),this._requireGunDB(),resetFederation(this._backend,e,t)}async propagate(e,t,n,s={}){return await this.ready(),this._requireGunDB(),propagate(this._backend,e,t,n,s)}async getFederated(e,t,n={}){return await this.ready(),this._requireGunDB(),getFederated(this._backend,e,t,n)}async subscribeFederation(e,t,n={}){return await this.ready(),this._requireGunDB(),subscribeFederation(this._backend,e,t,n)}async federateMessage(e,t,n,s,r="generic"){return await this.ready(),this._requireGunDB(),federateMessage(this._backend,e,t,n,s,r)}async getFederatedMessages(e,t){return await this.ready(),this._requireGunDB(),getFederatedMessages(this._backend,e,t)}async updateFederatedMessages(e,t,n){return await this.ready(),this._requireGunDB(),updateFederatedMessages(this._backend,e,t,n)}close(){this._backend&&this._backend.close(),this.client&&"function"==typeof this.client.close&&this.client.close()}};function toHolon(e,t,n){if("number"!=typeof e||e<-90||e>90)throw new RangeError(`Invalid latitude: ${e}. Must be between -90 and 90.`);if("number"!=typeof t||t<-180||t>180)throw new RangeError(`Invalid longitude: ${t}. Must be between -180 and 180.`);if(!Number.isInteger(n)||n<0||n>15)throw new RangeError(`Invalid resolution: ${n}. Must be integer between 0 and 15.`);try{return h3.latLngToCell(e,t,n)}catch(s){throw new Error(`H3 conversion failed: ${s.message}`)}}function getParents(e,t=0){if(!isValidH3(e))throw new Error(`Invalid H3 holon ID: ${e}`);const n=[];let s=e;for(let i=h3.getResolution(e)-1;i>=t;i--)try{s=h3.cellToParent(s,i),n.push(s)}catch(r){break}return n}function getChildren(e){if(!isValidH3(e))throw new Error(`Invalid H3 holon ID: ${e}`);try{const t=h3.getResolution(e);if(t>=15)throw new Error("Cannot get children of resolution 15 cell (maximum resolution)");return h3.cellToChildren(e,t+1)}catch(t){throw new Error(`Failed to get children: ${t.message}`)}}function isValidH3(e){return"string"==typeof e&&h3.isValidCell(e)}function getH3Resolution(e){if(!isValidH3(e))throw new Error(`Invalid H3 holon ID: ${e}`);return h3.getResolution(e)}const h3Operations=Object.freeze(Object.defineProperty({__proto__:null,getChildren:getChildren,getH3Resolution:getH3Resolution,getParents:getParents,isValidH3:isValidH3,toHolon:toHolon},Symbol.toStringTag,{value:"Module"})),BLOCK_SIZE$1=16,ZEROS16=new Uint8Array(16),ZEROS32=u32$1(ZEROS16),POLY$1=225,mul2$1=(e,t,n,s)=>({s3:n<<31|s>>>1,s2:t<<31|n>>>1,s1:e<<31|t>>>1,s0:e>>>1^POLY$1<<24&-(1&(1&s))}),swapLE=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255;function _toGHASHKey(e){e.reverse();const t=1&e[15];let n=0;for(let s=0;s<e.length;s++){const t=e[s];e[s]=t>>>1|n,n=(1&t)<<7}return e[0]^=225&-t,e}const estimateWindow=e=>e>65536?8:e>1024?4:2;class GHASH{constructor(e,t){this.blockLen=BLOCK_SIZE$1,this.outputLen=BLOCK_SIZE$1,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,bytes$2(e=toBytes$2(e),16);const n=createView$2(e);let s=n.getUint32(0,!1),r=n.getUint32(4,!1),i=n.getUint32(8,!1),a=n.getUint32(12,!1);const o=[];for(let f=0;f<128;f++)o.push({s0:swapLE(s),s1:swapLE(r),s2:swapLE(i),s3:swapLE(a)}),({s0:s,s1:r,s2:i,s3:a}=mul2$1(s,r,i,a));const l=estimateWindow(t||1024);if(![1,2,4,8].includes(l))throw new Error(`ghash: wrong window size=${l}, should be 2, 4 or 8`);this.W=l;const c=128/l,u=this.windowSize=2**l,d=[];for(let f=0;f<c;f++)for(let e=0;e<u;e++){let t=0,n=0,s=0,r=0;for(let i=0;i<l;i++){if(!(e>>>l-i-1&1))continue;const{s0:a,s1:c,s2:u,s3:d}=o[l*f+i];t^=a,n^=c,s^=u,r^=d}d.push({s0:t,s1:n,s2:s,s3:r})}this.t=d}_updateBlock(e,t,n,s){e^=this.s0,t^=this.s1,n^=this.s2,s^=this.s3;const{W:r,t:i,windowSize:a}=this;let o=0,l=0,c=0,u=0;const d=(1<<r)-1;let f=0;for(const h of[e,t,n,s])for(let e=0;e<4;e++){const t=h>>>8*e&255;for(let e=8/r-1;e>=0;e--){const n=t>>>r*e&d,{s0:s,s1:h,s2:p,s3:y}=i[f*a+n];o^=s,l^=h,c^=p,u^=y,f+=1}}this.s0=o,this.s1=l,this.s2=c,this.s3=u}update(e){e=toBytes$2(e),exists$2(this);const t=u32$1(e),n=Math.floor(e.length/BLOCK_SIZE$1),s=e.length%BLOCK_SIZE$1;for(let r=0;r<n;r++)this._updateBlock(t[4*r+0],t[4*r+1],t[4*r+2],t[4*r+3]);return s&&(ZEROS16.set(e.subarray(n*BLOCK_SIZE$1)),this._updateBlock(ZEROS32[0],ZEROS32[1],ZEROS32[2],ZEROS32[3]),ZEROS32.fill(0)),this}destroy(){const{t:e}=this;for(const t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){exists$2(this),output$2(e,this),this.finished=!0;const{s0:t,s1:n,s2:s,s3:r}=this,i=u32$1(e);return i[0]=t,i[1]=n,i[2]=s,i[3]=r,e}digest(){const e=new Uint8Array(BLOCK_SIZE$1);return this.digestInto(e),this.destroy(),e}}class Polyval extends GHASH{constructor(e,t){const n=_toGHASHKey((e=toBytes$2(e)).slice());super(n,t),n.fill(0)}update(e){e=toBytes$2(e),exists$2(this);const t=u32$1(e),n=e.length%BLOCK_SIZE$1,s=Math.floor(e.length/BLOCK_SIZE$1);for(let r=0;r<s;r++)this._updateBlock(swapLE(t[4*r+3]),swapLE(t[4*r+2]),swapLE(t[4*r+1]),swapLE(t[4*r+0]));return n&&(ZEROS16.set(e.subarray(s*BLOCK_SIZE$1)),this._updateBlock(swapLE(ZEROS32[3]),swapLE(ZEROS32[2]),swapLE(ZEROS32[1]),swapLE(ZEROS32[0])),ZEROS32.fill(0)),this}digestInto(e){exists$2(this),output$2(e,this),this.finished=!0;const{s0:t,s1:n,s2:s,s3:r}=this,i=u32$1(e);return i[0]=t,i[1]=n,i[2]=s,i[3]=r,e.reverse()}}function wrapConstructorWithKey(e){const t=(t,n)=>e(n,t.length).update(toBytes$2(t)).digest(),n=e(new Uint8Array(16),0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=(t,n)=>e(t,n),t}const ghash=wrapConstructorWithKey((e,t)=>new GHASH(e,t));wrapConstructorWithKey((e,t)=>new Polyval(e,t));const BLOCK_SIZE=16,BLOCK_SIZE32=4,EMPTY_BLOCK=new Uint8Array(BLOCK_SIZE),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 n=0,s=1;n<256;n++,s^=mul2(s))e[n]=s;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})(),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),a=new Uint32Array(65536),o=new Uint32Array(65536),l=new Uint16Array(65536);for(let c=0;c<256;c++)for(let t=0;t<256;t++){const u=256*c+t;a[u]=n[c]^s[t],o[u]=r[c]^i[t],l[u]=e[c]<<8|e[t]}return{sbox:e,sbox2:l,T0:n,T1:s,T2:r,T3:i,T01:a,T23:o}}const tableEncoding=genTtable(sbox,e=>mul(e,3)<<24|e<<16|e<<8|mul(e,2)),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$2(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$1(e),r=s.length,i=e=>applySbox(n,e,e,e,e),a=new Uint32Array(t+28);a.set(s);for(let o=r;o<a.length;o++){let e=a[o-1];o%r===0?e=i(rotr32_8(e))^xPowers[o/r-1]:r>6&&o%r===4&&(e=i(e)),a[o]=a[o-r]^e}return a}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(e,t,n,s,r){const{sbox2:i,T01:a,T23:o}=tableEncoding;let l=0;t^=e[l++],n^=e[l++],s^=e[l++],r^=e[l++];const c=e.length/4-2;for(let u=0;u<c;u++){const i=e[l++]^apply0123(a,o,t,n,s,r),c=e[l++]^apply0123(a,o,n,s,r,t),u=e[l++]^apply0123(a,o,s,r,t,n),d=e[l++]^apply0123(a,o,r,t,n,s);t=i,n=c,s=u,r=d}return{s0:e[l++]^applySbox(i,t,n,s,r),s1:e[l++]^applySbox(i,n,s,r,t),s2:e[l++]^applySbox(i,s,r,t,n),s3:e[l++]^applySbox(i,r,t,n,s)}}function getDst(e,t){if(!t)return new Uint8Array(e);if(bytes$2(t),t.length<e)throw new Error(`aes: wrong destination length, expected at least ${e}, got: ${t.length}`);return t}function ctr32(e,t,n,s,r){bytes$2(n,BLOCK_SIZE),bytes$2(s),r=getDst(s.length,r);const i=n,a=u32$1(i),o=createView$2(i),l=u32$1(s),c=u32$1(r),u=t?0:12,d=s.length;let f=o.getUint32(u,t),{s0:h,s1:p,s2:y,s3:g}=encrypt(e,a[0],a[1],a[2],a[3]);for(let b=0;b+4<=l.length;b+=4)c[b+0]=l[b+0]^h,c[b+1]=l[b+1]^p,c[b+2]=l[b+2]^y,c[b+3]=l[b+3]^g,f=f+1>>>0,o.setUint32(u,f,t),({s0:h,s1:p,s2:y,s3:g}=encrypt(e,a[0],a[1],a[2],a[3]));const m=BLOCK_SIZE*Math.floor(l.length/BLOCK_SIZE32);if(m<d){const e=new Uint32Array([h,p,y,g]),t=u8(e);for(let n=m,i=0;n<d;n++,i++)r[n]=s[n]^t[i]}return r}function computeTag(e,t,n,s,r){const i=e.create(n,s.length+(r?.length||0));r&&i.update(r),i.update(s);const a=new Uint8Array(16),o=createView$2(a);return r&&setBigUint64$1(o,0,BigInt(8*r.length),t),setBigUint64$1(o,8,BigInt(8*s.length),t),i.update(a),i.digest()}const gcm=wrapCipher({blockSize:16,nonceLength:12,tagLength:16},function(e,t,n){if(bytes$2(t),0===t.length)throw new Error("aes/gcm: empty nonce");const s=16;function r(e,t,s){const r=computeTag(ghash,!1,e,s,n);for(let n=0;n<t.length;n++)r[n]^=t[n];return r}function i(){const n=expandKeyLE(e),s=EMPTY_BLOCK.slice(),r=EMPTY_BLOCK.slice();if(ctr32(n,!1,r,r,s),12===t.length)r.set(t);else{const e=EMPTY_BLOCK.slice();setBigUint64$1(createView$2(e),8,BigInt(8*t.length),!1),ghash.create(s).update(t).update(e).digestInto(r)}return{xk:n,authKey:s,counter:r,tagMask:ctr32(n,!1,r,EMPTY_BLOCK)}}return{encrypt:e=>{bytes$2(e);const{xk:t,authKey:n,counter:a,tagMask:o}=i(),l=new Uint8Array(e.length+s);ctr32(t,!1,a,e,l);const c=r(n,o,l.subarray(0,l.length-s));return l.set(c,e.length),t.fill(0),l},decrypt:e=>{if(bytes$2(e),e.length<s)throw new Error("aes/gcm: ciphertext less than tagLen (16)");const{xk:t,authKey:n,counter:a,tagMask:o}=i(),l=e.subarray(0,-16),c=e.subarray(-16);if(!equalBytes(r(n,o,l),c))throw new Error("aes/gcm: invalid ghash tag");const u=ctr32(t,!1,a,l);return n.fill(0),o.fill(0),t.fill(0),u}}}),cr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function randomBytes$1(e=32){if(cr&&"function"==typeof cr.getRandomValues)return cr.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}
15
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$1=e=>e instanceof Uint8Array,createView$1=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=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function bytesToHex$1(e){if(!u8a$1(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=hexes[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 s=0;s<n.length;s++){const t=2*s,r=e.slice(t,t+2),i=Number.parseInt(r,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[s]=i}return n}function utf8ToBytes$1(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes$1(e){if("string"==typeof e&&(e=utf8ToBytes$1(e)),!u8a$1(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$1(e))throw new Error("Uint8Array expected");t.set(e,n),n+=e.length}),t}let Hash$1=class{clone(){return this._cloneInto()}};function wrapConstructor$1(e){const t=t=>e().update(toBytes$1(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function hexToBytes(e){const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function bytesToHex(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}function parseNpubOrHex(e){const t=e?.trim();if(!t)return{valid:!1,error:"Public key is required"};if(/^[0-9a-fA-F]{64}$/.test(t))return{valid:!0,hexPubKey:t.toLowerCase()};let n=t;if(n.startsWith("nostr:")&&(n=n.slice(6)),n.startsWith("npub1"))try{const e=nostrTools.nip19.decode(n);return"npub"===e.type?{valid:!0,hexPubKey:e.data}:{valid:!1,error:"Invalid npub format"}}catch(s){return{valid:!1,error:"Invalid npub: unable to decode"}}return{valid:!1,error:"Enter a valid npub (npub1...) or 64-character hex public key"}}function hexToNpub(e){try{return nostrTools.nip19.npubEncode(e)}catch(t){return console.error("Failed to encode hex to npub:",t),e}}function npubToHex(e){try{const t=nostrTools.nip19.decode(e);return"npub"===t.type?t.data:null}catch(t){return null}}function shortenPubKey(e){return!e||e.length<=20?e||"":`${e.slice(0,8)}...${e.slice(-8)}`}function shortenNpub(e){return!e||e.length<=20?e||"":`${e.slice(0,12)}...${e.slice(-8)}`}function getPublicKey$1(e){return nostrTools.getPublicKey(hexToBytes(e))}async function encryptNIP04(e,t,n){return await nostrTools.nip04.encrypt(e,t,n)}async function decryptNIP04(e,t,n){return await nostrTools.nip04.decrypt(e,t,n)}function encryptNIP44(e,t,n){const s=hexToBytes(e),r=nostrTools.nip44.v2.utils.getConversationKey(s,t);return nostrTools.nip44.v2.encrypt(n,r)}function decryptNIP44(e,t,n){const s=hexToBytes(e),r=nostrTools.nip44.v2.utils.getConversationKey(s,t);return nostrTools.nip44.v2.decrypt(n,r)}function createSignedEvent(e,t,n,s){const r={kind:e,content:t,tags:n,created_at:Math.floor(Date.now()/1e3)};return nostrTools.finalizeEvent(r,hexToBytes(s))}function createDMEvent(e,t,n){return createSignedEvent(4,t,[["p",e]],n)}function isValidHexPubKey(e){return"string"==typeof e&&/^[0-9a-fA-F]{64}$/.test(e)}function isValidNpub(e){if("string"!=typeof e||!e.startsWith("npub1"))return!1;try{return"npub"===nostrTools.nip19.decode(e).type}catch{return!1}}function generateNonce$1(){return Date.now().toString(36)+Math.random().toString(36).substring(2,15)}function signEvent(e,t){const n={kind:e.kind,content:e.content,tags:e.tags||[],created_at:e.created_at||Math.floor(Date.now()/1e3)};return nostrTools.finalizeEvent(n,hexToBytes(t))}function verifyEvent(e){return nostrTools.verifyEvent(e)}const nostrUtils=Object.freeze(Object.defineProperty({__proto__:null,NDK:NDK,NDKEvent:NDKEvent,NDKPrivateKeySigner:NDKPrivateKeySigner,NDKSubscriptionCacheUsage:NDKSubscriptionCacheUsage,NDKUser:NDKUser,bytesToHex:bytesToHex,createDMEvent:createDMEvent,createSignedEvent:createSignedEvent,decryptNIP04:decryptNIP04,decryptNIP44:decryptNIP44,encryptNIP04:encryptNIP04,encryptNIP44:encryptNIP44,generateNonce:generateNonce$1,getPublicKey:getPublicKey$1,hexToBytes:hexToBytes,hexToNpub:hexToNpub,isValidHexPubKey:isValidHexPubKey,isValidNpub:isValidNpub,npubToHex:npubToHex,parseNpubOrHex:parseNpubOrHex,shortenNpub:shortenNpub,shortenPubKey:shortenPubKey,signEvent:signEvent,verifyEvent:verifyEvent},Symbol.toStringTag,{value:"Module"}));function generateLensKey(){return randomBytes$1(32)}function uint8ToBase64(e){return"function"==typeof btoa?btoa(String.fromCharCode(...e)):Buffer.from(e).toString("base64")}function base64ToUint8(e){if("function"==typeof atob){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}return new Uint8Array(Buffer.from(e,"base64"))}function encryptWithKey(e,t){const n=randomBytes$1(12),s=gcm(e,n),r=(new TextEncoder).encode(t),i=s.encrypt(r),a=new Uint8Array(n.length+i.length);return a.set(n,0),a.set(i,n.length),uint8ToBase64(a)}function decryptWithKey(e,t){const n=base64ToUint8(t),s=n.slice(0,12),r=n.slice(12),i=gcm(e,s).decrypt(r);return(new TextDecoder).decode(i)}function wrapKeyForRecipient(e,t,n){return encryptNIP44(t,n,uint8ToBase64(e))}function unwrapKey(e,t,n){return base64ToUint8(decryptNIP44(t,n,e))}function serializeLensKey(e,t,n){return{wrappedKey:wrapKeyForRecipient(e,t,n),algorithm:"aes-256-gcm",keyWrap:"nip44",version:"1.0"}}function deserializeLensKey(e,t,n){if("1.0"!==e.version)throw new Error(`Unsupported lens key version: ${e.version}`);return unwrapKey(e.wrappedKey,t,n)}function isEncrypted(e){if(!e||"string"!=typeof e)return!1;const t=e.trim();if(t.startsWith("{")||t.startsWith("["))return!1;if(e.length<38)return!1;try{return base64ToUint8(e).length>=29}catch{return!1}}const lensKeys=Object.freeze(Object.defineProperty({__proto__:null,decryptWithKey:decryptWithKey,deserializeLensKey:deserializeLensKey,encryptWithKey:encryptWithKey,generateLensKey:generateLensKey,isEncrypted:isEncrypted,serializeLensKey:serializeLensKey,unwrapKey:unwrapKey,wrapKeyForRecipient:wrapKeyForRecipient},Symbol.toStringTag,{value:"Module"})),globalSubscriptions=new Map,singlePathSubscriptions=new Map,pendingQueries=new Map,QUERY_DEDUP_WINDOW=2e3;function _parseEventContent(e,t=null){if(!e||!e.content)return null;try{const n=e.tags?.find(e=>"encrypted"===e[0]);if(n&&"symmetric"===n[1]){if(!t)return null;const n=decryptWithKey(t,e.content);return JSON.parse(n)}return JSON.parse(e.content)}catch(n){return null}}async function nostrPut(e,t,n,s=3e4){const r="number"==typeof s?{kind:s}:s,i=r.kind||3e4,{lensKey:a}=r;let o;const l=[["d",t]];a?(o=encryptWithKey(a,JSON.stringify(n)),l.push(["encrypted","symmetric"])):o=JSON.stringify(n);const c={kind:i,created_at:Math.floor(Date.now()/1e3),tags:l,content:o},u={...r.signingKey&&{signingKey:r.signingKey},...r.waitForRelays&&{waitForRelays:r.waitForRelays}};return await e.publish(c,u)}async function nostrGet(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=!0===s.skipAuthorFilter,a=i?null:s.authors||[e.publicKey],{lensKey:o}=s;if(!s.skipCache&&e.getCachedByPath){const r=e.getCachedByPath(t,n);if(r&&r.content&&(i||a.includes(r.pubkey))){const e=_parseEventContent(r,o);return!e||e._deleted?null:(s.includeAuthor&&(e._author=r.pubkey),e)}}if(!s.skipPersistent&&e.persistentGet){const l=await e.persistentGet(t);if(l&&l.content&&(i||a.includes(l.pubkey))){const i=_parseEventContent(l,o);return!i||i._deleted?(l.tags?.find(e=>"encrypted"===e[0]),null):(s.includeAuthor&&(i._author=l.pubkey),e.refreshPathInBackground&&e.refreshPathInBackground(t,n,{authors:a,timeout:r}),i)}}const l=i?"_all_":a?a.join(","):e.publicKey,c=`get:${e.publicKey}:${n}:${t}:${l}`,u=pendingQueries.get(c);if(u&&Date.now()-u.timestamp<QUERY_DEDUP_WINDOW)return u.promise;const d=_executeNostrGet(e,t,n,a,r,s);return pendingQueries.set(c,{promise:d,timestamp:Date.now()}),d.finally(()=>{setTimeout(()=>{const e=pendingQueries.get(c);e&&e.promise===d&&pendingQueries.delete(c)},QUERY_DEDUP_WINDOW)}),d}async function _executeNostrGet(e,t,n,s,r,i){const{lensKey:a}=i,o={kinds:[n],"#d":[t]};s&&s.length>0?(o.authors=s,o.limit=s.length):o.limit=10;const l=await e.query(o,{timeout:r,forceRelay:i.forceRelay}),c=s?l.filter(e=>s.includes(e.pubkey)):l;if(0===c.length)return null;const u=c.sort((e,t)=>t.created_at-e.created_at)[0],d=_parseEventContent(u,a);return!d||d._deleted?null:(i.includeAuthor&&(d._author=u.pubkey),d)}async function nostrGetAll(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=s.limit||1e3,a=!0===s.skipAuthorFilter,o=a?null:s.authors||[e.publicKey],{lensKey:l}=s;if(!s.skipPersistent&&e.persistentGetAll){const a=await e.persistentGetAll(t);if(a.length>0){const c=new Map;for(const e of a){if(!e||!e.tags)continue;if(o&&!o.includes(e.pubkey))continue;const n=e.tags.find(e=>"d"===e[0]);if(!n||!n[1]||!n[1].startsWith(t))continue;const r=n[1],i=c.get(r);if(!i||e.created_at>i.created_at){const t=_parseEventContent(e,l);if(!t||t._deleted){c.delete(r);continue}s.includeAuthor&&(t._author=e.pubkey),c.set(r,{data:t,created_at:e.created_at})}}return e.refreshPrefixInBackground&&e.refreshPrefixInBackground(t,n,{authors:o,timeout:r,limit:i}),Array.from(c.values()).map(e=>e.data)}}const c=a?"_all_":o?o.join(","):e.publicKey,u=`getAll:${e.publicKey}:${n}:${t}:${c}`,d=pendingQueries.get(u);if(d&&Date.now()-d.timestamp<QUERY_DEDUP_WINDOW)return d.promise;const f=_executeNostrGetAll(e,t,n,o,r,i,s);return pendingQueries.set(u,{promise:f,timestamp:Date.now()}),f.finally(()=>{setTimeout(()=>{const e=pendingQueries.get(u);e&&e.promise===f&&pendingQueries.delete(u)},QUERY_DEDUP_WINDOW)}),f}async function _executeNostrGetAll(e,t,n,s,r,i,a){const{lensKey:o}=a,l={kinds:[n],limit:i};s&&s.length>0&&(l.authors=s);const c=(await e.query(l,{timeout:r})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]),r=n&&n[1]&&n[1].startsWith(t),i=!s||s.includes(e.pubkey);return r&&i}),u=new Map;for(const d of c){const e=d.tags.find(e=>"d"===e[0])[1],t=u.get(e);if(!t||d.created_at>t.created_at){const t=_parseEventContent(d,o);if(!t||t._deleted){u.delete(e);continue}a.includeAuthor&&(t._author=d.pubkey),u.set(e,{data:t,created_at:d.created_at})}}return Array.from(u.values()).map(e=>e.data)}async function nostrGetAllHybrid(e,t,n=3e4,s={}){const r=void 0!==s.timeout?s.timeout:3e4,i=s.limit||1e3,a=s.authors||[e.publicKey],o=e.queryHybrid||e.query,l={kinds:[n],authors:a,limit:i},c=(await o.call(e,l,{timeout:r})).filter(e=>{const n=e.tags.find(e=>"d"===e[0]),s=n&&n[1]&&n[1].startsWith(t),r=a.includes(e.pubkey);return s&&r}),u=new Map;for(const f of c){const e=f.tags.find(e=>"d"===e[0])[1],t=u.get(e);if(!t||f.created_at>t.created_at)try{const t=JSON.parse(f.content);if(null===t||"object"!=typeof t)continue;if(t._deleted){u.delete(e);continue}s.includeAuthor&&(t._author=f.pubkey),u.set(e,{data:t,created_at:f.created_at})}catch(d){}}return Array.from(u.values()).map(e=>e.data)}async function nostrDelete(e,t,n=3e4){const s="number"==typeof n?{kind:n}:n,r=s.kind||3e4,{signingKey:i}=s,a=s.authorPubkey||e.publicKey,o=a!==e.publicKey?{authors:[a]}:{};if(!(await nostrGet(e,t,r,o)))return{reason:"not_found",results:[]};const l={_deleted:!0,_deletedAt:Date.now()},c={kind:r};i&&(c.signingKey=i);const u=await nostrPut(e,t,l,c),d=`${r}:${a}:${t}`,f={kind:5,created_at:Math.floor(Date.now()/1e3),tags:[["a",d]],content:""},h=i?{signingKey:i}:{};try{await e.publish(f,h)}catch(p){}return u}const DELETE_RATE_LIMIT_MS=100;async function nostrDeleteAll(e,t,n=3e4){const s="number"==typeof n?{kind:n}:n,r=s.kind||3e4,{signingKey:i}=s,a=s.authorPubkey||e.publicKey,o={kinds:[r],authors:[a],limit:1e3},l=await e.query(o,{timeout:3e4});let c=[];if(e.persistentStorage)try{c=await e.persistentStorage.getAll(t)}catch(g){}const u=new Map;for(const b of l){const e=b.tags?.find(e=>"d"===e[0]);e&&e[1]&&e[1].startsWith(t)&&u.set(e[1],b)}for(const b of c){const e=b.tags?.find(e=>"d"===e[0]);if(e&&e[1]&&e[1].startsWith(t)){const t=u.get(e[1]);(!t||b.created_at>t.created_at)&&u.set(e[1],b)}}const d=Array.from(u.values());if(0===d.length)return{success:!0,count:0,results:[]};const f={kind:r};i&&(f.signingKey=i);const h=[];for(let b=0;b<d.length;b++){const t=d[b].tags.find(e=>"d"===e[0])[1];try{const n={_deleted:!0,_deletedAt:Date.now()},s=await nostrPut(e,t,n,f);h.push(s),b<d.length-1&&DELETE_RATE_LIMIT_MS>0&&await new Promise(e=>setTimeout(e,DELETE_RATE_LIMIT_MS))}catch(m){console.error(`Failed to delete item ${t}:`,m)}}const p=d.map(e=>{const t=e.tags.find(e=>"d"===e[0])[1];return`${r}:${a}:${t}`}),y=i?{signingKey:i}:{};try{const t={kind:5,created_at:Math.floor(Date.now()/1e3),tags:p.map(e=>["a",e]),content:""};await e.publish(t,y)}catch(m){}return{success:!0,count:d.length,results:h}}async function nostrSubscribe(e,t,n,s={}){const r=s.kind||3e4,i=`single:${e.publicKey}:${r}:${t}`,a=singlePathSubscriptions.get(i);if(a)return a.callbacks.push(n),{unsubscribe:()=>{const e=a.callbacks.indexOf(n);e>-1&&a.callbacks.splice(e,1),0===a.callbacks.length&&(a.subscription.unsubscribe(),singlePathSubscriptions.delete(i))}};const o=[n],l={callbacks:o,subscription:null};singlePathSubscriptions.set(i,l);const c={kinds:[r],authors:[e.publicKey],"#d":[t],limit:10},u=await e.subscribe(c,t=>{if(t.pubkey===e.publicKey)try{const e=JSON.parse(t.content);if(!e||e._deleted)return;for(const s of o)try{s(e,t)}catch(n){console.error("Subscription callback error:",n)}}catch(s){console.error("Failed to parse event in subscription:",s)}},{onEOSE:()=>{}});return l.subscription=u,{unsubscribe:()=>{const e=o.indexOf(n);e>-1&&o.splice(e,1),0===o.length&&(u.unsubscribe(),singlePathSubscriptions.delete(i))}}}async function nostrSubscribeMany(e,t,n,s={}){const r=s.kind||3e4,i=t.split("/")[1]||e.publicKey,a=s.authors||[i],o=`${a.join(",")}:${r}:${t}`,l=globalSubscriptions.get(o);if(l)return l.callbacks.push(n),{unsubscribe:()=>{const e=l.callbacks.indexOf(n);e>-1&&l.callbacks.splice(e,1),0===l.callbacks.length&&(l.actualSubscription.unsubscribe(),globalSubscriptions.delete(o))}};const c=new Set,u=[n];let d=0,f=0,h=Date.now();const p=e=>{if(c.has(e.id))return;if(c.add(e.id),!a.includes(e.pubkey)){d++;const e=Date.now();return void(e-h>1e4&&(console.warn("[nostrSubscribeMany] ⚠️ Relay not respecting authors filter!",{rejectedCount:d,acceptedCount:f,expectedAuthors:a.length,message:"Consider using a different relay or implementing private relay"}),h=e))}const n=e.tags.find(e=>"d"===e[0]),s=n?.[1];if(s&&s.startsWith(t))try{const t=JSON.parse(e.content);if(!t||t._deleted)return;f++;for(const n of u)n(t,s,e)}catch(r){console.error("[nostrSubscribeMany] Failed to parse event:",r)}},y=Math.floor(Date.now()/1e3)-2,g={kinds:[r],authors:a,since:y},m=await e.subscribe(g,p);let b="undefined"!=typeof document&&document.hidden,w=y;const _=async()=>{if("undefined"==typeof document)return;const t=b;if(b=document.hidden,t&&!b){const t=Math.floor(Date.now()/1e3);try{const n={...g,since:w,until:t},s=await e.query(n,{timeout:3e4});for(const e of s)p(e);w=t}catch(n){}}};"undefined"!=typeof document&&document.addEventListener("visibilitychange",_);const v={unsubscribe:()=>{m&&m.unsubscribe&&m.unsubscribe(),"undefined"!=typeof document&&document.removeEventListener("visibilitychange",_),globalSubscriptions.delete(o)}},E={callbacks:u,actualSubscription:v};return globalSubscriptions.set(o,E),v}function buildPath$1(e,t,n,s=null){const r=encodePathComponent(t),i=encodePathComponent(n);if(s){return`${e}/${r}/${i}/${encodePathComponent(s)}`}return`${e}/${r}/${i}`}function encodePathComponent(e){return encodeURIComponent(e).replace(/%2F/g,"/")}async function write$1(e,t,n,s={}){try{const r={...s.signingKey&&{signingKey:s.signingKey},...s.waitForRelays&&{waitForRelays:s.waitForRelays}},i=await nostrPut(e,t,n,r);return 0===i.results.length||i.results.some(e=>"fulfilled"===e.status)}catch(r){throw console.error("Nostr write error:",r),r}}async function read$1(e,t,n={}){const s=await nostrGet(e,t,3e4,n);return!s||s._deleted?null:s}async function readAll$1(e,t,n={}){const s=n.hybrid&&"function"==typeof e.queryHybrid?nostrGetAllHybrid:nostrGetAll;return(await s(e,t,3e4,n)).filter(e=>!(!e||"object"!=typeof e)&&!e._deleted)}async function update$1(e,t,n){try{const s=await nostrGet(e,t);if(!s||!s.id||s._deleted)return!1;const r={...s,...n};r._meta||(r._meta={}),r._meta.timestamp=Date.now();const i=await nostrPut(e,t,r);return 0===i.results.length||i.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr update error:",s),s}}async function deleteData$1(e,t,n={}){try{const s={kind:3e4};n.signingKey&&(s.signingKey=n.signingKey),n.authorPubkey&&(s.authorPubkey=n.authorPubkey);const r=await nostrDelete(e,t,s);if("not_found"===r.reason)return!1;return 0===r.results.length||r.results.some(e=>"fulfilled"===e.status)}catch(s){throw console.error("Nostr delete error:",s),s}}async function deleteAll$1(e,t,n={}){try{const s={kind:3e4};n.signingKey&&(s.signingKey=n.signingKey),n.authorPubkey&&(s.authorPubkey=n.authorPubkey);return await nostrDeleteAll(e,t,s)}catch(s){throw console.error("Nostr deleteAll error:",s),s}}async function subscribe$1(e,t,n,s={}){return t.split("/").length<=3?await nostrSubscribeMany(e,t+"/",(e,t)=>{const s=t.split("/").pop();n(e,s)},s):await nostrSubscribe(e,t,e=>{n(e,t.split("/").pop())},s)}function buildPath(e,t,n,s=null){return buildPath$1(e,t,n,s)}async function write(e,t,n,s={}){return e.write&&e.gun?e.write(t,n,s):e.gun?write$2(e.gun,t,n):write$1(e,t,n,s)}async function read(e,t,n={}){return e.read&&e.gun?e.read(t,n):e.gun?read$2(e.gun,t):read$1(e,t,n)}async function readAll(e,t,n={}){return e.readAll&&e.gun?e.readAll(t,n):e.gun?readAll$2(e.gun,t):readAll$1(e,t,n)}async function update(e,t,n){return e.update&&e.gun?e.update(t,n):e.gun?update$2(e.gun,t,n):update$1(e,t,n)}async function deleteData(e,t,n={}){return e.delete&&e.gun?e.delete(t):e.gun?deleteData$2(e.gun,t):deleteData$1(e,t,n)}async function deleteAll(e,t,n={}){return e.gun?deleteAll$2(e.gun,t):deleteAll$1(e,t,n)}function subscribe(e,t,n,s={}){return e.subscribe&&e.gun?e.subscribe(t,n,s):e.gun?subscribe$2(e.gun,t,n,s):subscribe$1(e,t,n,s)}const unifiedStorage=Object.freeze(Object.defineProperty({__proto__:null,buildPath:buildPath,deleteAll:deleteAll,deleteData:deleteData,read:read,readAll:readAll,subscribe:subscribe,update:update,write:write},Symbol.toStringTag,{value:"Module"}));async function writeGlobal(e,t,n,s){s.id||(s.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`);return write(e,`${t}/${n}/${s.id}`,s)}async function readGlobal(e,t,n,s=null){if(s){return read(e,`${t}/${n}/${s}`)}return readAll(e,`${t}/${n}`)}async function updateGlobal(e,t,n,s,r){return update(e,`${t}/${n}/${s}`,r)}async function deleteGlobal(e,t,n,s){return deleteData(e,`${t}/${n}/${s}`)}async function deleteAllGlobal(e,t,n){return deleteAll(e,`${t}/${n}`)}async function getAllGlobal(e,t,n){return readAll(e,`${t}/${n}`)}async function subscribeGlobal(e,t,n,s,r,i={}){return subscribe(e,s?`${t}/${n}/${s}`:`${t}/${n}`,r,i)}const ajv=new Ajv({allErrors:!0,strict:!1}),schemaCache=new Map,CACHE_TTL=36e5;let ValidationError$1=class extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.errors=t}};function compileSchema(e,t){const n=t,s=schemaCache.get(n);if(s&&Date.now()-s.timestamp<CACHE_TTL)return s.validator;try{const t=ajv.compile(e);return schemaCache.set(n,{validator:t,timestamp:Date.now()}),t}catch(r){throw new Error(`Schema compilation failed: ${r.message}`)}}function validate(e,t,n,s=!1){const r=compileSchema(t,n);if(!r(e)){const e=r.errors||[],t=e.map(e=>`${e.instancePath} ${e.message}`).join("; ");if(s)throw new ValidationError$1(`ValidationError: Validation failed: ${t}`,e);return console.warn(`[Schema Validation Warning] ${n}: ${t}`),!1}return!0}function clearSchemaCache(e){schemaCache.delete(e)}function clearAllCaches(){schemaCache.clear()}const validator=Object.freeze(Object.defineProperty({__proto__:null,ValidationError:ValidationError$1,clearAllCaches:clearAllCaches,clearSchemaCache:clearSchemaCache,compileSchema:compileSchema,validate:validate},Symbol.toStringTag,{value:"Module"}));function number$1(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bool(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$1(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$1={number:number$1,bool:bool,bytes:bytes$1,hash:hash$1,exists:exists$1,output:output$1};function setBigUint64(e,t,n,s){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,s);const r=BigInt(32),i=BigInt(4294967295),a=Number(n>>r&i),o=Number(n&i),l=s?4:0,c=s?0:4;e.setUint32(t+l,a,s),e.setUint32(t+c,o,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$1(this.buffer)}update(e){assert$1.exists(this);const{view:t,buffer:n,blockLen:s}=this,r=(e=toBytes$1(e)).length;for(let i=0;i<r;){const a=Math.min(s-this.pos,r-i);if(a===s){const t=createView$1(e);for(;s<=r-i;i+=s)this.process(t,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){assert$1.exists(this),assert$1.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 u=i;u<s;u++)t[u]=0;setBigUint64(n,s-8,BigInt(8*this.length),r),this.process(n,0);const a=createView$1(e),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=o/4,c=this.get();if(l>c.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,c[u],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:a}=this;return e.length=s,e.pos=a,e.finished=r,e.destroyed=i,s%t&&e.buffer.set(n),e}}const Chi=(e,t,n)=>e&t^~e&n,Maj=(e,t,n)=>e&t^e&n^t&n,SHA256_K=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=new Uint32Array(64);class SHA256 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:a,H:o}=this;return[e,t,n,s,r,i,a,o]}set(e,t,n,s,r,i,a,o){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|a,this.H=0|o}process(e,t){for(let u=0;u<16;u++,t+=4)SHA256_W[u]=e.getUint32(t,!1);for(let u=16;u<64;u++){const e=SHA256_W[u-15],t=SHA256_W[u-2],n=rotr$1(e,7)^rotr$1(e,18)^e>>>3,s=rotr$1(t,17)^rotr$1(t,19)^t>>>10;SHA256_W[u]=s+SHA256_W[u-7]+n+SHA256_W[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:l,H:c}=this;for(let u=0;u<64;u++){const e=c+(rotr$1(a,6)^rotr$1(a,11)^rotr$1(a,25))+Chi(a,o,l)+SHA256_K[u]+SHA256_W[u]|0,t=(rotr$1(n,2)^rotr$1(n,13)^rotr$1(n,22))+Maj(n,s,r)|0;c=l,l=o,o=a,a=i+e|0,i=r,r=s,s=n,n=e+t|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(n,s,r,i,a,o,l,c)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class SHA224 extends SHA256{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=wrapConstructor$1(()=>new SHA256);function getPublicKey(e){return bytesToHex$1(schnorr.getPublicKey(e))}async function sign(e,t){try{const n=hashContent(e);return bytesToHex$1(schnorr.sign(n,t))}catch(n){throw new Error(`Signature generation failed: ${n.message}`)}}async function verify(e,t,n){try{if(!n||"string"!=typeof n||n.length<64)throw new Error("Invalid public key format");const s=hashContent(e);return schnorr.verify(t,s,n)}catch(s){if("Invalid public key format"===s.message)throw s;return!1}}function matchScope(e,t){if("string"==typeof e||"string"==typeof t){return("string"==typeof e?e:JSON.stringify(e))===("string"==typeof t?t:JSON.stringify(t))}return("*"===e.holonId||e.holonId===t.holonId)&&(("*"===e.lensName||e.lensName===t.lensName)&&(!e.dataId||"*"===e.dataId||!t.dataId||e.dataId===t.dataId))}async function issueCapability$1(e,t,n,s={}){const{expiresIn:r=36e5,issuer:i="holosphere",issuerKey:a,isSelfCapability:o}=s;if(!Array.isArray(e)||0===e.length)throw new Error("Permissions array cannot be empty");if("object"==typeof t){if(void 0===t.holonId||""===t.holonId)throw new Error('Invalid scope: holonId is required (use "*" for wildcard)');if(void 0===t.lensName||""===t.lensName)throw new Error('Invalid scope: lensName is required (use "*" for wildcard)')}else if("string"==typeof t&&""===t)throw new Error("Invalid scope: cannot be empty string");if(a&&("string"!=typeof a||a.length<32))throw new Error("Invalid issuer key");const l={type:"capability",permissions:e,scope:t,recipient:n,issuer:i,isSelfCapability:void 0!==o?o:i===n,nonce:generateNonce(),issued:Date.now(),expires:null!=r?Date.now()+r:null},c=JSON.stringify(l),u="function"==typeof btoa?btoa(c):Buffer.from(c).toString("base64");if(a){return`${u}.${await sign(c,a)}`}return u}async function issueSelfCapability(e,t,n,s={}){const{privateKey:r,expiresIn:i=31536e6}=s;return issueCapability$1(e,t,n,{expiresIn:i,issuer:n,issuerKey:r,isSelfCapability:!0})}async function verifyCapability$1(e,t,n){try{let r;if(e&&"object"==typeof e&&e.token&&(e=e.token),e&&"object"==typeof e&&"Buffer"===e.type&&Array.isArray(e.data))try{e=String.fromCharCode.apply(null,e.data)}catch(s){return console.log("[verifyCapability] ❌ Failed to decode Buffer object:",s.message),!1}if("string"==typeof e&&/^\d+(,\d+)+$/.test(e.substring(0,50)))try{const t=e.split(",").map(Number);e=String.fromCharCode.apply(null,t)}catch(s){return console.log("[verifyCapability] ❌ Failed to decode byte string:",s.message),!1}if("string"==typeof e)if(e.startsWith("ey")||!e.includes(".")&&!e.startsWith("{"))try{const t=e.includes(".")?e.split(".")[0]:e,n="function"==typeof atob?atob(t):Buffer.from(t,"base64").toString("utf8");r=JSON.parse(n)}catch(s){return console.log("[verifyCapability] ❌ Token is not valid base64 JSON:",{preview:e.substring(0,50),error:s.message}),!1}else{if(!e.startsWith("{"))return console.log("[verifyCapability] ❌ Unknown token format:",e.substring(0,50)),!1;try{r=JSON.parse(e)}catch(s){return console.log("[verifyCapability] ❌ Token is not valid JSON:",{preview:e.substring(0,50),error:s.message}),!1}}else{if(!e||"object"!=typeof e)return console.log("[verifyCapability] ❌ Invalid token:",typeof e),!1;r=e}return r&&"capability"===r.type?null!=r.expires&&Date.now()>r.expires?(console.log("[verifyCapability] ❌ Token expired:",{expires:r.expires,now:Date.now(),expiredAgo:(Date.now()-r.expires)/1e3+"s ago"}),!1):matchScope(r.scope,n)?r.permissions.includes(t)?(console.log("[verifyCapability] ✅ Capability valid"),!0):(console.log("[verifyCapability] ❌ Permission denied:",{required:t,has:r.permissions}),!1):(console.log("[verifyCapability] ❌ Scope mismatch:",{tokenScope:r.scope,requestedScope:n}),!1):(console.log("[verifyCapability] ❌ Invalid token type:",{type:r?.type,tokenObj:r}),!1)}catch(r){return console.log("[verifyCapability] ❌ Error:",r.message),!1}}async function verifyCapabilityIssuer(e,t){try{if(e&&"object"==typeof e&&e.token&&(e=e.token),e&&"object"==typeof e&&"Buffer"===e.type&&Array.isArray(e.data)&&(e=String.fromCharCode.apply(null,e.data)),"string"!=typeof e)return console.log("[verifyCapabilityIssuer] ❌ Token is not a string"),!1;let n,s,r;if(e.includes(".")){const t=e.split("."),i=t[0];s=t[1];const a="function"==typeof atob?atob(i):Buffer.from(i,"base64").toString("utf8");n=a,r=JSON.parse(a)}else if(e.startsWith("ey")){const t="function"==typeof atob?atob(e):Buffer.from(e,"base64").toString("utf8");n=t,r=JSON.parse(t)}else{if(!e.startsWith("{"))return console.log("[verifyCapabilityIssuer] ❌ Unknown token format"),!1;n=e,r=JSON.parse(e)}if(r.issuer!==t)return console.log("[verifyCapabilityIssuer] ❌ Issuer mismatch:",{tokenIssuer:r.issuer?.slice(0,12)+"...",expectedIssuer:t?.slice(0,12)+"..."}),!1;if(s){if(!(await verify(n,s,t)))return console.log("[verifyCapabilityIssuer] ❌ Signature verification failed - capability not signed by claimed issuer"),!1}else console.log("[verifyCapabilityIssuer] ⚠️ Token has no signature - cannot verify cryptographically");return console.log("[verifyCapabilityIssuer] ✅ Issuer verified"),!0}catch(n){return console.log("[verifyCapabilityIssuer] ❌ Error:",n.message),!1}}function decodeCapability(e){try{if(e&&"object"==typeof e&&e.token&&(e=e.token),e&&"object"==typeof e&&"Buffer"===e.type&&Array.isArray(e.data)&&(e=String.fromCharCode.apply(null,e.data)),"string"!=typeof e)return null;if(e.startsWith("ey")||!e.includes(".")&&!e.startsWith("{")){const t=e.includes(".")?e.split(".")[0]:e,n="function"==typeof atob?atob(t):Buffer.from(t,"base64").toString("utf8");return JSON.parse(n)}return e.startsWith("{")?JSON.parse(e):null}catch(t){return null}}function generateNonce(){return Date.now().toString(36)+Math.random().toString(36).substring(2,15)}function hashContent(e){const t="string"==typeof e?e:JSON.stringify(e),n=(new TextEncoder).encode(t);return bytesToHex$1(sha256(n))}wrapConstructor$1(()=>new SHA224);const secp256k1=Object.freeze(Object.defineProperty({__proto__:null,decodeCapability:decodeCapability,getPublicKey:getPublicKey,issueCapability:issueCapability$1,issueSelfCapability:issueSelfCapability,matchScope:matchScope,sign:sign,verify:verify,verifyCapability:verifyCapability$1,verifyCapabilityIssuer:verifyCapabilityIssuer},Symbol.toStringTag,{value:"Module"})),FEDERATION_TABLE="federations",registryCache=new Map,CACHE_TTL_MS=1e4;function buildPartnerIndex(e){const t=new Map;for(const n of e)n.pubKey&&t.set(n.pubKey,n);return t}function getCacheKey(e,t){return`${e.publicKey}:${t}`}function invalidateRegistryCache(e,t){const n=getCacheKey(e,t);registryCache.delete(n)}async function getFederationRegistry(e,t,n={}){const s=getCacheKey(e,t),r=Date.now();if(!n.skipCache){const e=registryCache.get(s);if(e&&r-e.timestamp<CACHE_TTL_MS)return e.registry}const i=await readGlobal(e,t,FEDERATION_TABLE,e.publicKey)||{id:e.publicKey,federatedWith:[],capabilityWriters:[],discoveryEnabled:!1,autoAccept:!1,defaultScope:{holonId:"*",lensName:"*"},defaultPermissions:["read"]};i.capabilityWriters||(i.capabilityWriters=[]);const a=buildPartnerIndex(i.federatedWith||[]);return registryCache.set(s,{registry:i,partnerIndex:a,timestamp:r}),i}async function getPartnerFromIndex(e,t,n){const s=getCacheKey(e,t);await getFederationRegistry(e,t);const r=registryCache.get(s);return r&&r.partnerIndex&&r.partnerIndex.get(n)||null}async function saveFederationRegistry(e,t,n){return invalidateRegistryCache(e,t),writeGlobal(e,t,FEDERATION_TABLE,n)}async function addFederatedPartner(e,t,n,s={}){const r=await getFederationRegistry(e,t),i=r.federatedWith.findIndex(e=>e.pubKey===n);if(i>=0){const e=r.federatedWith[i];if(s.alias&&(e.alias=s.alias),s.inboundCapabilities){const t=[...e.inboundCapabilities||[],...s.inboundCapabilities],n=new Map;for(const e of t){const t=`${e.scope?.holonId}:${e.scope?.lensName}:${e.scope?.dataId}`;n.set(t,e)}e.inboundCapabilities=Array.from(n.values())}e.updatedAt=Date.now(),r.federatedWith[i]=e}else r.federatedWith.push({pubKey:n,alias:s.alias||null,addedAt:Date.now(),addedVia:s.addedVia||"manual",inboundCapabilities:s.inboundCapabilities||[],outboundCapabilities:[]});return saveFederationRegistry(e,t,r)}async function removeFederatedPartner(e,t,n){const s=await getFederationRegistry(e,t),r=s.federatedWith.length;return s.federatedWith=s.federatedWith.filter(e=>e.pubKey!==n),s.federatedWith.length!==r&&saveFederationRegistry(e,t,s)}async function getFederatedAuthors(e,t){return(await getFederationRegistry(e,t)).federatedWith.map(e=>e.pubKey)}async function addCapabilityWriter(e,t,n){const s=await getFederationRegistry(e,t);return!!s.capabilityWriters.some(e=>e.pubKey===n)||(s.capabilityWriters.push({pubKey:n,addedAt:Date.now()}),saveFederationRegistry(e,t,s))}async function getCapabilityWriters(e,t){return((await getFederationRegistry(e,t)).capabilityWriters||[]).map(e=>e.pubKey)}async function removeCapabilityWriter(e,t,n){const s=await getFederationRegistry(e,t),r=s.capabilityWriters.length;return s.capabilityWriters=s.capabilityWriters.filter(e=>e.pubKey!==n),s.capabilityWriters.length!==r&&saveFederationRegistry(e,t,s)}async function getFederatedPartner(e,t,n){return getPartnerFromIndex(e,t,n)}async function getCapabilityForAuthor(e,t,n,s){const r=await getPartnerFromIndex(e,t,n);if(!r)return null;if(!r.inboundCapabilities||0===r.inboundCapabilities.length)return null;const i=Date.now();for(const a of r.inboundCapabilities)if(!(a.expires&&a.expires<i)&&matchScope(a.scope,s))return a;return null}async function storeInboundCapability(e,t,n,s){const r=await getFederationRegistry(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i)return addFederatedPartner(e,t,n,{addedVia:"capability_received",inboundCapabilities:[s]});i.inboundCapabilities||(i.inboundCapabilities=[]);const a=i.inboundCapabilities.findIndex(e=>JSON.stringify(e.scope)===JSON.stringify(s.scope));return a>=0?i.inboundCapabilities[a]={...s,updatedAt:Date.now()}:i.inboundCapabilities.push({...s,receivedAt:Date.now()}),saveFederationRegistry(e,t,r)}async function storeOutboundCapability(e,t,n,s){const r=await getFederationRegistry(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i)throw new Error(`Partner ${n} not found in federation registry`);return i.outboundCapabilities||(i.outboundCapabilities=[]),i.outboundCapabilities.push({tokenHash:s.tokenHash,scope:s.scope,permissions:s.permissions,issuedAt:Date.now(),expires:s.expires}),saveFederationRegistry(e,t,r)}async function revokeOutboundCapability(e,t,n,s){const r=await getFederationRegistry(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i||!i.outboundCapabilities)return!1;const a=i.outboundCapabilities.length;return i.outboundCapabilities=i.outboundCapabilities.filter(e=>e.tokenHash!==s),i.outboundCapabilities.length!==a&&saveFederationRegistry(e,t,r)}async function updateDiscoverySettings(e,t,n){const s=await getFederationRegistry(e,t);return void 0!==n.discoveryEnabled&&(s.discoveryEnabled=n.discoveryEnabled),void 0!==n.autoAccept&&(s.autoAccept=n.autoAccept),void 0!==n.defaultScope&&(s.defaultScope=n.defaultScope),void 0!==n.defaultPermissions&&(s.defaultPermissions=n.defaultPermissions),saveFederationRegistry(e,t,s)}async function getFederatedAuthorsForScope(e,t,n={},s="read"){const r=await getFederationRegistry(e,t),i=Date.now(),a=[];for(const o of r.federatedWith)if(o.inboundCapabilities&&0!==o.inboundCapabilities.length)for(const e of o.inboundCapabilities)if(!(e.expires&&e.expires<i)&&(!e.permissions||e.permissions.includes(s))&&matchScope(e.scope,n)){a.push({pubKey:o.pubKey,capability:e});break}return a}async function cleanupExpiredCapabilities(e,t){const n=await getFederationRegistry(e,t),s=Date.now();let r=0,i=0;for(const a of n.federatedWith){if(a.inboundCapabilities){const e=a.inboundCapabilities.length;a.inboundCapabilities=a.inboundCapabilities.filter(e=>!e.expires||e.expires>s),r+=e-a.inboundCapabilities.length}if(a.outboundCapabilities){const e=a.outboundCapabilities.length;a.outboundCapabilities=a.outboundCapabilities.filter(e=>!e.expires||e.expires>s),i+=e-a.outboundCapabilities.length}}return(r>0||i>0)&&await saveFederationRegistry(e,t,n),{inboundRemoved:r,outboundRemoved:i}}async function storeSelfCapability(e,t,n){const s=await getFederationRegistry(e,t),r=e.publicKey;let i=s.federatedWith.find(e=>e.pubKey===r);i||(i={pubKey:r,alias:"self",addedAt:Date.now(),addedVia:"self_capability",isSelf:!0,inboundCapabilities:[],outboundCapabilities:[],selfCapabilities:[]},s.federatedWith.push(i)),i.selfCapabilities||(i.selfCapabilities=[]);const a=i.selfCapabilities.findIndex(e=>JSON.stringify(e.scope)===JSON.stringify(n.scope));return a>=0?i.selfCapabilities[a]={...n,updatedAt:Date.now(),isSelfCapability:!0}:i.selfCapabilities.push({...n,issuedAt:Date.now(),isSelfCapability:!0}),saveFederationRegistry(e,t,s)}async function getSelfCapability(e,t,n){const s=(await getFederationRegistry(e,t)).federatedWith.find(t=>t.pubKey===e.publicKey&&t.isSelf);return s&&s.selfCapabilities&&s.selfCapabilities.find(e=>!(e.expires&&e.expires<Date.now())&&matchScope(e.scope,n))||null}function isSelfCapability(e){return e&&!0===e.isSelfCapability}async function grantWriteAccessToHolon(e,t,n,s,r={}){console.warn("[Deprecated] grantWriteAccessToHolon() is deprecated. Use grantAccess() instead.");const i=await getFederationRegistry(e,t);let a=i.federatedWith.find(e=>e.pubKey===n);a||(a={pubKey:n,alias:null,addedAt:Date.now(),addedVia:"write_grant",inboundCapabilities:[],outboundCapabilities:[],writeGrants:[]},i.federatedWith.push(a)),a.writeGrants||(a.writeGrants=[]);const o=a.writeGrants.findIndex(e=>e.lensName===s),l={lensName:s,grantedAt:Date.now(),expiresAt:r.expiresAt||null};return o>=0?a.writeGrants[o]=l:a.writeGrants.push(l),saveFederationRegistry(e,t,i)}async function revokeWriteAccess(e,t,n,s){console.warn("[Deprecated] revokeWriteAccess() is deprecated. Use revokeAccess() instead.");const r=await getFederationRegistry(e,t),i=r.federatedWith.find(e=>e.pubKey===n);if(!i||!i.writeGrants)return!1;const a=i.writeGrants.length;return i.writeGrants=i.writeGrants.filter(e=>e.lensName!==s),i.writeGrants.length!==a&&saveFederationRegistry(e,t,r)}async function getWriteGrantsForHolon(e,t,n){console.warn("[Deprecated] getWriteGrantsForHolon() is deprecated. Use getAccessGrants() instead.");const s=(await getFederationRegistry(e,t)).federatedWith.find(e=>e.pubKey===n);if(!s||!s.writeGrants)return[];const r=Date.now();return s.writeGrants.filter(e=>!e.expiresAt||e.expiresAt>r)}async function hasWriteAccess(e,t,n,s){console.warn("[Deprecated] hasWriteAccess() is deprecated. Use findAccessGrant() instead.");return(await getWriteGrantsForHolon(e,t,n)).some(e=>e.lensName===s||"*"===e.lensName)}async function getAllWriteGrants(e,t){console.warn("[Deprecated] getAllWriteGrants() is deprecated. Use getAccessGrants() instead.");const n=await getFederationRegistry(e,t),s=Date.now(),r=[];for(const i of n.federatedWith)if(i.writeGrants&&i.writeGrants.length>0){const e=i.writeGrants.filter(e=>!e.expiresAt||e.expiresAt>s);e.length>0&&r.push({holonId:i.pubKey,alias:i.alias,writeGrants:e})}return r}async function grantAccess(e,t,n,s,r,i={}){const a=await getFederationRegistry(e,t),{expiresAt:o=null,capabilityToken:l=null,direction:c="inbound"}=i;let u=a.federatedWith.find(e=>e.pubKey===n);u||(u={pubKey:n,alias:null,addedAt:Date.now(),addedVia:"access_grant",inboundCapabilities:[],outboundCapabilities:[],writeGrants:[],accessGrants:[]},a.federatedWith.push(u)),u.accessGrants||(u.accessGrants=[]);const d={holonId:s.holonId||"*",lensName:s.lensName||"*"},f=u.accessGrants.findIndex(e=>e.scope.holonId===d.holonId&&e.scope.lensName===d.lensName&&e.direction===c),h={scope:d,permissions:[...r],grantedAt:Date.now(),expiresAt:o,capabilityToken:l,direction:c};return f>=0?u.accessGrants[f]=h:u.accessGrants.push(h),saveFederationRegistry(e,t,a)}async function revokeAccess(e,t,n,s,r=null,i={}){const a=await getFederationRegistry(e,t),{direction:o="inbound"}=i,l=a.federatedWith.find(e=>e.pubKey===n);if(!l||!l.accessGrants)return!1;const c=s.holonId||"*",u=s.lensName||"*",d=l.accessGrants.findIndex(e=>e.scope.holonId===c&&e.scope.lensName===u&&e.direction===o);if(d<0)return!1;if(null===r)l.accessGrants.splice(d,1);else{const e=l.accessGrants[d];e.permissions=e.permissions.filter(e=>!r.includes(e)),0===e.permissions.length&&l.accessGrants.splice(d,1)}return saveFederationRegistry(e,t,a)}async function findAccessGrant(e,t,n,s,r,i={}){const a=await getFederationRegistry(e,t),{direction:o="inbound"}=i,l=Date.now(),c=a.federatedWith.find(e=>e.pubKey===n);if(!c)return null;if(c.accessGrants&&c.accessGrants.length>0)for(const u of c.accessGrants)if(!(u.expiresAt&&u.expiresAt<l)&&u.direction===o&&u.permissions.includes(r)&&matchScope(u.scope,s))return u;if("read"===r&&"inbound"===o&&c.inboundCapabilities)for(const u of c.inboundCapabilities)if(!(u.expires&&u.expires<l)&&(!u.permissions||u.permissions.includes("read"))&&matchScope(u.scope,s))return{scope:u.scope,permissions:u.permissions||["read"],grantedAt:u.receivedAt||Date.now(),expiresAt:u.expires||null,capabilityToken:u.token,direction:"inbound",_legacy:!0};if("write"===r&&"inbound"===o&&c.writeGrants)for(const u of c.writeGrants)if(!(u.expiresAt&&u.expiresAt<l||u.lensName!==s.lensName&&"*"!==u.lensName))return{scope:{holonId:"*",lensName:u.lensName},permissions:["write"],grantedAt:u.grantedAt||Date.now(),expiresAt:u.expiresAt||null,direction:"inbound",_legacy:!0};return null}async function getAccessGrants(e,t,n,s={}){const r=await getFederationRegistry(e,t),{direction:i="all",includeLegacy:a=!0}=s,o=Date.now(),l=r.federatedWith.find(e=>e.pubKey===n);if(!l)return[];const c=[];if(l.accessGrants)for(const u of l.accessGrants)u.expiresAt&&u.expiresAt<o||"all"!==i&&u.direction!==i||c.push(u);if(a){if(l.inboundCapabilities&&("all"===i||"inbound"===i))for(const e of l.inboundCapabilities)e.expires&&e.expires<o||c.push({scope:e.scope,permissions:e.permissions||["read"],grantedAt:e.receivedAt||Date.now(),expiresAt:e.expires||null,capabilityToken:e.token,direction:"inbound",_legacy:!0});if(l.writeGrants&&("all"===i||"inbound"===i))for(const e of l.writeGrants)e.expiresAt&&e.expiresAt<o||c.push({scope:{holonId:"*",lensName:e.lensName},permissions:["write"],grantedAt:e.grantedAt||Date.now(),expiresAt:e.expiresAt||null,direction:"inbound",_legacy:!0})}return c}async function migrateToUnifiedGrants(e,t){const n=await getFederationRegistry(e,t);let s=0,r=0;for(const i of n.federatedWith){let e=!1;if(i.accessGrants||(i.accessGrants=[]),i.inboundCapabilities&&i.inboundCapabilities.length>0)for(const t of i.inboundCapabilities){!i.accessGrants.some(e=>e.scope.holonId===t.scope?.holonId&&e.scope.lensName===t.scope?.lensName&&"inbound"===e.direction&&"inboundCapability"===e._migratedFrom)&&t.scope&&(i.accessGrants.push({scope:{holonId:t.scope.holonId||"*",lensName:t.scope.lensName||"*"},permissions:t.permissions||["read"],grantedAt:t.receivedAt||Date.now(),expiresAt:t.expires||null,capabilityToken:t.token,direction:"inbound",_migratedFrom:"inboundCapability"}),r++,e=!0)}if(i.writeGrants&&i.writeGrants.length>0)for(const t of i.writeGrants){i.accessGrants.some(e=>e.scope.lensName===t.lensName&&e.permissions.includes("write")&&"inbound"===e.direction&&"writeGrant"===e._migratedFrom)||(i.accessGrants.push({scope:{holonId:"*",lensName:t.lensName},permissions:["write"],grantedAt:t.grantedAt||Date.now(),expiresAt:t.expiresAt||null,direction:"inbound",_migratedFrom:"writeGrant"}),r++,e=!0)}e&&s++}return r>0&&await saveFederationRegistry(e,t,n),{migratedPartners:s,migratedGrants:r}}function convertLegacyLensConfig(e){if(!e)return{version:"2.0",permissions:{}};const t={};for(const n of e.inbound||[])t[n]||(t[n]={receive:[],share:[]}),t[n].receive.includes("read")||t[n].receive.push("read");for(const n of e.outbound||[])t[n]||(t[n]={receive:[],share:[]}),t[n].share.includes("read")||t[n].share.push("read");for(const n of e.writeInbound||[])t[n]||(t[n]={receive:[],share:[]}),t[n].receive.includes("write")||t[n].receive.push("write");for(const n of e.writeOutbound||[])t[n]||(t[n]={receive:[],share:[]}),t[n].share.includes("write")||t[n].share.push("write");return{version:"2.0",permissions:t}}function convertToLegacyLensConfig(e){if(!e||!e.permissions)return{inbound:[],outbound:[],writeInbound:[],writeOutbound:[]};const t={inbound:[],outbound:[],writeInbound:[],writeOutbound:[]};for(const[n,s]of Object.entries(e.permissions))s.receive?.includes("read")&&t.inbound.push(n),s.share?.includes("read")&&t.outbound.push(n),s.receive?.includes("write")&&t.writeInbound.push(n),s.share?.includes("write")&&t.writeOutbound.push(n);return t}const registry=Object.freeze(Object.defineProperty({__proto__:null,addCapabilityWriter:addCapabilityWriter,addFederatedPartner:addFederatedPartner,cleanupExpiredCapabilities:cleanupExpiredCapabilities,convertLegacyLensConfig:convertLegacyLensConfig,convertToLegacyLensConfig:convertToLegacyLensConfig,findAccessGrant:findAccessGrant,getAccessGrants:getAccessGrants,getAllWriteGrants:getAllWriteGrants,getCapabilityForAuthor:getCapabilityForAuthor,getCapabilityWriters:getCapabilityWriters,getFederatedAuthors:getFederatedAuthors,getFederatedAuthorsForScope:getFederatedAuthorsForScope,getFederatedPartner:getFederatedPartner,getFederationRegistry:getFederationRegistry,getSelfCapability:getSelfCapability,getWriteGrantsForHolon:getWriteGrantsForHolon,grantAccess:grantAccess,grantWriteAccessToHolon:grantWriteAccessToHolon,hasWriteAccess:hasWriteAccess,invalidateRegistryCache:invalidateRegistryCache,isSelfCapability:isSelfCapability,migrateToUnifiedGrants:migrateToUnifiedGrants,removeCapabilityWriter:removeCapabilityWriter,removeFederatedPartner:removeFederatedPartner,revokeAccess:revokeAccess,revokeOutboundCapability:revokeOutboundCapability,revokeWriteAccess:revokeWriteAccess,saveFederationRegistry:saveFederationRegistry,storeInboundCapability:storeInboundCapability,storeOutboundCapability:storeOutboundCapability,storeSelfCapability:storeSelfCapability,updateDiscoverySettings:updateDiscoverySettings},Symbol.toStringTag,{value:"Module"})),MAX_RESOLUTION_DEPTH=10;async function wouldCreateCircularHologram(e,t,n,s,r,i){const a=new Set,o=[];let l=n,c=r,u=i,d=t;for(;a.size<MAX_RESOLUTION_DEPTH;){const t=`${d}:${l}:${c}:${u}`;if(a.has(t))return{isCircular:!0,chain:o,reason:"existing_cycle"};if(a.add(t),o.push({holon:l,lens:c,dataId:u}),l===s)return{isCircular:!0,chain:o,reason:"would_create_cycle"};const n=buildPath(d,l,c,u),r=await read(e,n);if(!r)return{isCircular:!1,chain:o};if(!r.hologram||!r.target)return{isCircular:!1,chain:o};d=r.target.appname||d,l=r.target.holonId,c=r.target.lensName||c,u=r.target.dataId||u}return{isCircular:!0,chain:o,reason:"max_depth_exceeded"}}function createHologram(e,t,n,s,r,i={}){const{authorPubKey:a}=i;let{capability:o}=i;if(!a)throw new Error("authorPubKey is required for hologram creation (unified model)");if(!o)throw new Error("capability is required for hologram creation (unified model)");"object"==typeof o&&o.token&&(o=o.token);return{id:s,hologram:!0,soul:buildPath(r,e,n,s),target:{appname:r,holonId:e,lensName:n,dataId:s,authorPubKey:a},capability:o,_meta:{created:Date.now(),lastUpdated:Date.now(),sourceHolon:e,source:e,sourcePubKey:a,grantedAt:Date.now()}}}async function createHologramWithCapability(e,t,n,s,r,i,a={}){const{sourceAuthorPubKey:o=e.publicKey,sourceAuthorPrivKey:l=e.privateKey,targetAuthorPubKey:c=e.publicKey,capability:u=null,permissions:d=["read"],expiresIn:f=null}=a;let h=u;if(!h){const n=o===c;h=await issueCapability$1(d,{holonId:t,lensName:s,dataId:r},c,{expiresIn:void 0!==f?f:null,issuer:o,issuerKey:l}),!n&&e.privateKey&&await storeInboundCapability(e,i,o,{token:h,scope:{holonId:t,lensName:s,dataId:r},permissions:d,isSelfCapability:!1})}return createHologram(t,n,s,r,i,{authorPubKey:o,capability:h})}async function resolveHologram(e,t,n=new Set,s=[],r={}){const{deleteCircular:i=!0,hologramPath:a=null,skipCapabilityVerification:o=!1}=r;if(!t||!t.hologram)return t;const{soul:l}=t,c=t.target||{};if(n.has(l)){const r=[...s,l].join(" → ");return console.warn("🔄 Circular reference detected - removing hologram"),console.warn(` Soul: ${l}`),console.warn(` Chain: ${r}`),console.warn(` Source holon: ${c.holonId||"unknown"}`),console.warn(` Lens: ${c.lensName||"unknown"}`),console.warn(` Data ID: ${c.dataId||t.id||"unknown"}`),console.warn(` Resolution depth: ${n.size}`),i&&a&&(console.info(` 🗑️ Deleting circular hologram at: ${a}`),await write(e,a,null)),null}if(n.size>=MAX_RESOLUTION_DEPTH){const t=[...s,l].join(" → ");return console.warn(`⚠️ Max resolution depth (${MAX_RESOLUTION_DEPTH}) exceeded - removing hologram`),console.warn(` Current soul: ${l}`),console.warn(` Chain: ${t}`),console.warn(` Source holon: ${c.holonId||"unknown"}`),console.warn(` Lens: ${c.lensName||"unknown"}`),i&&a&&(console.info(` 🗑️ Deleting deep chain hologram at: ${a}`),await write(e,a,null)),null}let u;n.add(l),s.push(l);let d=t.capability;const f=c.authorPubKey;if(d&&"object"==typeof d&&d.token&&(d=d.token),!d&&r.appname&&f){const t=await getCapabilityForAuthor(e,r.appname,f,{holonId:c.holonId,lensName:c.lensName,dataId:c.dataId});t&&(d=t.token||t)}if(!o){if(!d)return console.warn(`❌ Hologram missing capability: ${l}`),null;if(f){if(!(await verifyCapabilityIssuer(d,f))){console.warn(`❌ Capability issuer does not match authorPubKey for hologram: ${l}`),console.warn(` Expected author: ${f?.slice(0,12)}...`);const e=decodeCapability(d);return e&&console.warn(` Actual issuer: ${e.issuer?.slice(0,12)}...`),null}}if(!(await verifyCapability$1(d,"read",{holonId:c.holonId,lensName:c.lensName,dataId:c.dataId})))return console.warn(`❌ Capability verification failed for hologram: ${l}`),null}return u=f?await read(e,l,{authors:[f]}):await read(e,l),u?u.hologram?resolveHologram(e,u,n,s,{...r,hologramPath:l}):mergeHologramWithSource(t,u):null}function mergeHologramWithSource(e,t){const n=["hologram","soul","target","_meta","id","capability"],s={},r=[];for(const l of Object.keys(e))n.includes(l)||(s[l]=e[l],r.push(l));const i=e._meta?.sourceHolon||e._meta?.source||e.target?.holonId,a=e.target?.authorPubKey||e._meta?.sourcePubKey||null,o={...t,...s,_hologram:{isHologram:!0,soul:e.soul,sourceHolon:i,localOverrides:r,sourcePubKey:a}};return t._meta?o._meta={...t._meta,source:i}:o._meta={source:i},o}async function setupFederation(e,t,n,s,r,i={}){const{direction:a="outbound",mode:o="reference"}=i,l={sourceHolon:n,targetHolon:s,lensName:r,direction:a,mode:o,created:Date.now()};return write(e,buildPath(t,n,r,"_federation"),l)}async function propagateData(e,t,n,s,r,i,a="reference",o={}){const l=n.id;if(s===r)return console.info(`⏭️ Skipping propagation - source and target are the same holon: ${s}`),!0;if(!0===n.hologram){if(n.target&&n.target.holonId===r)return console.info("🔄 Skipping propagation - would create circular reference:"),console.info(` Data ID: ${l}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),console.info(` Hologram points to: ${n.target.holonId}`),console.info(` Lens: ${i}`),console.info(` Original soul: ${n.soul||"unknown"}`),!0;if(n.target){const s=buildPath(n.target.appname||t,n.target.holonId,n.target.lensName||i,n.target.dataId||l),a=await read(e,s);if(a?._meta?.activeHolograms){if(a._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${l}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Target holon: ${r}`),!0}}const a=n.target.holonId,o=n.target.dataId||l,c=n.target.lensName||i,u=n.target.appname||t,d=await wouldCreateCircularHologram(e,u,a,r,c,o);if(d.isCircular){const e=d.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram copy:"),console.warn(` Data ID: ${l}`),console.warn(` Original source: ${a}`),console.warn(` Would copy to: ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${d.reason}`),!1}const f=buildPath(t,r,i,l),h={...n,_meta:{...n._meta,copiedFrom:s,copiedAt:Date.now()}},p=await write(e,f,h);return p&&n.target&&(await addActiveHologram(e,n.target.appname||t,n.target.holonId,n.target.lensName||i,n.target.dataId||l,r),console.info(`📋 Copied hologram to ${r}:`),console.info(` Data ID: ${l}`),console.info(` Original source: ${n.target.holonId}`),console.info(` Copied from: ${s}`)),p}if("reference"===a&&n._meta?.activeHolograms){if(n._meta.activeHolograms.some(e=>e.targetHolon===r))return console.info("⏭️ Skipping propagation - target already in activeHolograms:"),console.info(` Data ID: ${l}`),console.info(` Source holon: ${s}`),console.info(` Target holon: ${r}`),!0}if("reference"===a){const n=await wouldCreateCircularHologram(e,t,s,r,i,l);if(n.isCircular){const e=n.chain.map(e=>e.holon).join(" → ");return console.warn("🔄 Preventing circular hologram creation:"),console.warn(` Data ID: ${l}`),console.warn(` Would create: ${s} → ${r}`),console.warn(` Existing chain: ${e}`),console.warn(` Reason: ${n.reason}`),!1}const a=o.sourceAuthorPubKey||e.publicKey,c="string"==typeof r&&/^[0-9a-f]{64}$/i.test(r),u=o.targetAuthorPubKey||(c?r:e.publicKey),d=await createHologramWithCapability(e,s,r,i,l,t,{sourceAuthorPubKey:a,sourceAuthorPrivKey:o.sourceAuthorPrivKey,targetAuthorPubKey:u,capability:o.capability,permissions:["read"]}),f=buildPath(t,r,i,l),h=await write(e,f,d);return h&&await addActiveHologram(e,t,s,i,l,r),h}return write(e,buildPath(t,r,i,l),{...n,_meta:{...n._meta,source:s}})}async function updateHologramOverrides(e,t,n,s,r,i){const a=buildPath(t,n,s,r),o=await read(e,a);if(!o)return console.warn(`Hologram not found at ${a}`),!1;if(!o.hologram)return console.warn(`Data at ${a} is not a hologram, cannot update overrides`),!1;const l=["hologram","soul","target","_meta","id"],c={};for(const[u,d]of Object.entries(i))l.includes(u)||(c[u]=d);return write(e,a,{...o,...c})}function isHologram(e){return e&&!0===e.hologram}function isResolvedHologram(e){return e&&e._hologram&&!0===e._hologram.isHologram}function getHologramSource(e){return isResolvedHologram(e)?{soul:e._hologram.soul,sourceHolon:e._hologram.sourceHolon,localOverrides:e._hologram.localOverrides||[]}:null}async function addActiveHologram(e,t,n,s,r,i){let a=t,o=n,l=s,c=r,u=buildPath(a,o,l,c),d=await read(e,u);if(!d)return!1;let f=0;for(;!0===d.hologram&&d.target&&f<10;)if(f++,a=d.target.appname||a,o=d.target.holonId,l=d.target.lensName||l,c=d.target.dataId||c,u=buildPath(a,o,l,c),d=await read(e,u),!d)return!1;d._meta||(d._meta={}),Array.isArray(d._meta.activeHolograms)||(d._meta.activeHolograms=[]);const h=Date.now(),p=d._meta.activeHolograms.findIndex(e=>e.targetHolon===i);return p>=0?d._meta.activeHolograms[p].lastUpdated=h:d._meta.activeHolograms.push({targetHolon:i,created:h,lastUpdated:h,platforms:{}}),write(e,u,d)}async function removeActiveHologram(e,t,n,s,r,i){let a=t,o=n,l=s,c=r,u=buildPath(a,o,l,c),d=await read(e,u);if(!d)return!1;let f=0;for(;!0===d.hologram&&d.target&&f<10;)if(f++,a=d.target.appname||a,o=d.target.holonId,l=d.target.lensName||l,c=d.target.dataId||c,u=buildPath(a,o,l,c),d=await read(e,u),!d)return!1;if(!d._meta||!Array.isArray(d._meta.activeHolograms))return!1;const h=d._meta.activeHolograms.length;return d._meta.activeHolograms=d._meta.activeHolograms.filter(e=>e.targetHolon!==i),d._meta.activeHolograms.length<h&&write(e,u,d)}async function updateActiveHologramPlatform(e,t,n,s,r,i,a,o){let l=t,c=n,u=s,d=r,f=buildPath(l,c,u,d),h=await read(e,f);if(!h)return!1;let p=0;for(;!0===h.hologram&&h.target&&p<10;)if(p++,l=h.target.appname||l,c=h.target.holonId,u=h.target.lensName||u,d=h.target.dataId||d,f=buildPath(l,c,u,d),h=await read(e,f),!h)return!1;if(!h._meta||!Array.isArray(h._meta.activeHolograms))return console.warn(`No activeHolograms found for ${f}`),!1;const y=h._meta.activeHolograms.find(e=>e.targetHolon===i);return y?(y.platforms||(y.platforms={}),y.platforms[a]={...y.platforms[a],...o,lastUpdated:Date.now()},y.lastUpdated=Date.now(),write(e,f,h)):(console.warn(`No hologram entry found for target ${i}`),!1)}async function getActiveHolograms(e,t,n,s,r,i=null){const a=buildPath(t,n,s,r),o=await read(e,a);if(!o?._meta?.activeHolograms)return[];let l=o._meta.activeHolograms;return i&&(l=l.filter(e=>e.platforms?.[i])),l}async function refreshActiveHolograms(e,t,n,s,r,i=null){if(!i){const a=buildPath(t,n,s,r);i=await read(e,a)}if(!i||!i._meta||!Array.isArray(i._meta.activeHolograms))return{refreshed:0,holograms:[]};const a=Date.now(),o=[];for(const l of i._meta.activeHolograms){l.lastUpdated=a;const n=buildPath(t,l.targetHolon,s,r),i=await read(e,n);i&&!0===i.hologram&&(i._meta||(i._meta={}),i._meta.lastUpdated=a,await write(e,n,i),o.push({targetHolon:l.targetHolon,dataId:r,timestamp:a}))}return{refreshed:o.length,holograms:o,sourceData:i}}async function deleteHologram(e,t,n,s,r,i={}){const{deleteData:a=!0}=i,o=buildPath(t,n,s,r),l={success:!1,wasHologram:!1,sourceHolon:null,activeHologramsUpdated:!1,error:null};try{const i=await read(e,o);if(!i)return console.warn(`🗑️ Hologram not found at ${o}`),l.error="Hologram not found",l;if(!0===i.hologram&&i.target){l.wasHologram=!0,l.sourceHolon=i.target.holonId,console.info("🗑️ Deleting hologram:"),console.info(` Path: ${o}`),console.info(` Data ID: ${r}`),console.info(` From holon: ${n}`),console.info(` Source holon: ${i.target.holonId}`),console.info(` Lens: ${s}`);const a=await removeActiveHologram(e,i.target.appname||t,i.target.holonId,i.target.lensName||s,i.target.dataId||r,n);l.activeHologramsUpdated=a,a?console.info(" ✓ Removed from activeHolograms on source"):console.warn(" ⚠️ Could not update activeHolograms on source (may already be removed)")}else console.info(`🗑️ Deleting non-hologram data at ${o}`);if(a){const t=await write(e,o,null);l.success=t,t?console.info(" ✓ Hologram deleted successfully"):(console.warn(" ⚠️ Failed to delete hologram data"),l.error="Failed to delete hologram data")}else l.success=!0;return l}catch(c){return console.error(`❌ Error deleting hologram at ${o}:`,c),l.error=c.message||"Unknown error",l}}async function cleanupCircularHolograms(e,t,n,s,r={}){const{dryRun:i=!1}=r,a={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${i?"[DRY RUN] ":""}Cleaning up circular holograms in ${n}/${s}...`);try{buildPath(t,n,s);const r=buildPath(t,n,s,"_index"),o=await read(e,r);if(!o||!Array.isArray(o.items))return console.warn(` No index found for ${n}/${s}, cannot scan for circular references`),console.info(" Tip: Provide specific IDs to check using cleanupCircularHologramsByIds()"),a;for(const l of o.items){a.scanned++;const r=buildPath(t,n,s,l),o=await read(e,r);if(!o||!0!==o.hologram||!o.target)continue;const c=o.target.holonId,u=o.target.dataId||l,d=o.target.lensName||s,f=buildPath(o.target.appname||t,c,d,u),h=await read(e,f);if(h&&!0===h.hologram&&h.target&&h.target.holonId===n){a.circularFound++;const o={itemId:l,path:r,pointsTo:`${c}/${d}/${u}`,circularWith:`${h.target.holonId}/${h.target.lensName}/${h.target.dataId}`};if(a.details.push(o),console.warn(" 🔄 Found circular hologram:"),console.warn(` ${n}/${s}/${l} → ${c}/${d}/${u} → ${n}`),!i){const r=await deleteHologram(e,t,n,s,l);r.success?(a.deleted++,console.info(" ✓ Deleted circular hologram")):(a.errors.push({itemId:l,error:r.error}),console.error(` ❌ Failed to delete: ${r.error}`))}}}return console.info(`🧹 Cleanup complete for ${n}/${s}:`),console.info(` Scanned: ${a.scanned}`),console.info(` Circular found: ${a.circularFound}`),console.info(` Deleted: ${a.deleted}`),a.errors.length>0&&console.warn(` Errors: ${a.errors.length}`),a}catch(o){return console.error("❌ Error during cleanup:",o),a.errors.push({error:o.message}),a}}async function cleanupCircularHologramsByIds(e,t,n,s,r,i={}){const{dryRun:a=!1}=i,o={scanned:0,circularFound:0,deleted:0,errors:[],details:[]};console.info(`🧹 ${a?"[DRY RUN] ":""}Cleaning up circular holograms for ${r.length} IDs in ${n}/${s}...`);for(const l of r){o.scanned++;const r=buildPath(t,n,s,l),i=await read(e,r);if(!i||!0!==i.hologram||!i.target)continue;const c=i.target.holonId,u=i.target.dataId||l,d=i.target.lensName||s,f=buildPath(i.target.appname||t,c,d,u),h=await read(e,f);if(h&&!0===h.hologram&&h.target&&h.target.holonId===n){o.circularFound++;const i={itemId:l,path:r,pointsTo:`${c}/${d}/${u}`,circularWith:`${h.target.holonId}/${h.target.lensName}/${h.target.dataId}`};if(o.details.push(i),console.warn(` 🔄 Found circular hologram: ${l}`),console.warn(` Chain: ${n} → ${c} → ${n}`),!a){const r=await deleteHologram(e,t,n,s,l);r.success?(o.deleted++,console.info(" ✓ Deleted")):(o.errors.push({itemId:l,error:r.error}),console.error(` ❌ Failed: ${r.error}`))}}}return console.info(`🧹 Cleanup complete: scanned=${o.scanned}, circular=${o.circularFound}, deleted=${o.deleted}`),o}const hologram=Object.freeze(Object.defineProperty({__proto__:null,addActiveHologram:addActiveHologram,cleanupCircularHolograms:cleanupCircularHolograms,cleanupCircularHologramsByIds:cleanupCircularHologramsByIds,createHologram:createHologram,createHologramWithCapability:createHologramWithCapability,deleteHologram:deleteHologram,getActiveHolograms:getActiveHolograms,getHologramSource:getHologramSource,isHologram:isHologram,isResolvedHologram:isResolvedHologram,propagateData:propagateData,refreshActiveHolograms:refreshActiveHolograms,removeActiveHologram:removeActiveHologram,resolveHologram:resolveHologram,setupFederation:setupFederation,updateActiveHologramPlatform:updateActiveHologramPlatform,updateHologramOverrides:updateHologramOverrides,wouldCreateCircularHologram:wouldCreateCircularHologram},Symbol.toStringTag,{value:"Module"})),HOLON_REGISTRY_TABLE="_holon-registry";function isPubkey(e){return"string"==typeof e&&/^[0-9a-f]{64}$/i.test(e)}async function registerHolon(e,t,n,s,r={}){if(!isPubkey(s))throw new Error(`Invalid public key format: ${s}`);if(isPubkey(n))return console.log("[HolonRegistry] registerHolon: holonId is already a pubkey, skipping registration"),!0;const i={id:n,holonId:n,publicKey:s,alias:r.alias||null,createdAt:Date.now(),updatedAt:Date.now(),createdBy:e.publicKey};console.log("[HolonRegistry] 📝 registerHolon:",{holonId:n,publicKey:s?.slice(0,12)+"...",alias:r.alias});const a=await writeGlobal(e,t,HOLON_REGISTRY_TABLE,i);return console.log("[HolonRegistry] registerHolon result:",a),a}async function lookupHolon(e,t,n){return isPubkey(n)?{holonId:n,publicKey:n,isDirect:!0}:readGlobal(e,t,HOLON_REGISTRY_TABLE,n)}async function resolveHolonToPubkey(e,t,n){if(isPubkey(n))return console.log("[HolonRegistry] resolveHolonToPubkey: holonId is already a pubkey:",n?.slice(0,12)+"..."),n;const s=await lookupHolon(e,t,n);return s?.publicKey?console.log("[HolonRegistry] ✅ resolveHolonToPubkey: Found mapping",{holonId:n,publicKey:s.publicKey?.slice(0,12)+"...",alias:s.alias}):console.log("[HolonRegistry] ❌ resolveHolonToPubkey: No mapping found for holonId:",n),s?.publicKey||null}async function unregisterHolon(e,t,n){if(isPubkey(n))return!1;const s={id:n,holonId:n,publicKey:null,_deleted:!0,deletedAt:Date.now(),deletedBy:e.publicKey};return writeGlobal(e,t,HOLON_REGISTRY_TABLE,s)}async function updateHolon(e,t,n,s={}){const r=await lookupHolon(e,t,n);if(!r||r.isDirect)return!1;const i={...r,...s,updatedAt:Date.now()};return writeGlobal(e,t,HOLON_REGISTRY_TABLE,i)}async function listRegisteredHolons(e,t){return(await getAllGlobal(e,t,HOLON_REGISTRY_TABLE)||[]).filter(e=>!e._deleted)}async function findHolonsByPubkey(e,t,n){return(await listRegisteredHolons(e,t)).filter(e=>e.publicKey===n)}const holonRegistry=Object.freeze(Object.defineProperty({__proto__:null,findHolonsByPubkey:findHolonsByPubkey,isPubkey:isPubkey,listRegisteredHolons:listRegisteredHolons,lookupHolon:lookupHolon,registerHolon:registerHolon,resolveHolonToPubkey:resolveHolonToPubkey,unregisterHolon:unregisterHolon,updateHolon:updateHolon},Symbol.toStringTag,{value:"Module"}));async function issueCapability(e,t,n,s,r={}){const{expiresIn:i=36e5,isSelfCapability:a=!1}=r;return await issueCapability$1(s,n,t,{expiresIn:i,issuer:e.publicKey,issuerKey:e.privateKey,isSelfCapability:a})}async function issueCapabilityForLens(e,t,n,s,r={}){const{permissions:i=["read"],expiresIn:a=31536e6}=r,o={holonId:t,lensName:n,dataId:"*"};return{token:await issueCapability(e,s,o,i,{expiresIn:a,isSelfCapability:e.publicKey===s}),scope:o,permissions:i,expiresAt:Date.now()+a}}async function issueCapabilitiesForLenses(e,t,n,s,r={}){const i=[];for(const o of n)try{const n=await issueCapabilityForLens(e,t,o,s,r);i.push(n)}catch(a){console.warn(`[Capabilities] Failed to issue capability for ${o}:`,a.message)}return i}async function storeCapability(e,t,n,s,r={}){const{isSelf:i=!1}=r;return i?storeSelfCapability(e,t,s):storeInboundCapability(e,t,n,s)}function hashToken(e){const t=new TextEncoder;return bytesToHex$1(sha256(t.encode(e)))}async function verifyCapability(e,t,n){return verifyCapability$1(e,t,n)}async function getCapabilityForPartner(e,t,n,s){return getCapabilityForAuthor(e,t,n,s)}const capabilities={issueCapability:issueCapability,issueCapabilityForLens:issueCapabilityForLens,issueCapabilitiesForLenses:issueCapabilitiesForLenses,storeCapability:storeCapability,hashToken:hashToken,verifyCapability:verifyCapability,getCapabilityForPartner:getCapabilityForPartner},capabilities$1=Object.freeze(Object.defineProperty({__proto__:null,default:capabilities,getCapabilityForPartner:getCapabilityForPartner,hashToken:hashToken,issueCapabilitiesForLenses:issueCapabilitiesForLenses,issueCapability:issueCapability,issueCapabilityForLens:issueCapabilityForLens,storeCapability:storeCapability,verifyCapability:verifyCapability},Symbol.toStringTag,{value:"Module"})),DEFAULT_INITIAL_LENS_COUNT=3;function createFederationCard({partnerPubKey:e,partnerName:t=null,holonId:n,holonName:s,availableLenses:r=[],defaultConfig:i={}}){const{defaultDirection:a="bidirectional",defaultPermissions:o=["read"],enabledByDefault:l=!0}=i,c=r.map(e=>({name:e,enabled:l,direction:a,permissions:[...o]}));return{id:`fedcard_${e.substring(0,8)}_${Date.now()}`,partnerPubKey:e,partnerName:t,holonId:n,holonName:s,lenses:c,message:"",createdAt:Date.now(),status:"pending",expanded:!1}}function updateLensConfig(e,t,n){const s=e.lenses.findIndex(e=>e.name===t);if(-1===s)return e;const r=[...e.lenses];return r[s]={...r[s],...n},{...e,lenses:r}}function toggleLens(e,t){const n=e.lenses.find(e=>e.name===t);return n?updateLensConfig(e,t,{enabled:!n.enabled}):e}function enableAllLenses(e){return{...e,lenses:e.lenses.map(e=>({...e,enabled:!0}))}}function disableAllLenses(e){return{...e,lenses:e.lenses.map(e=>({...e,enabled:!1}))}}function toggleCardExpansion(e){return{...e,expanded:!e.expanded}}function getVisibleLenses(e,t=DEFAULT_INITIAL_LENS_COUNT){const n=e.lenses;return e.expanded||n.length<=t?{visibleLenses:n,hiddenCount:0,isExpanded:!0}:{visibleLenses:n.slice(0,t),hiddenCount:n.length-t,isExpanded:!1}}function getEnabledLenses(e){return e.lenses.filter(e=>e.enabled)}function getLensConfigForHandshake(e){const t=[],n=[];for(const s of e.lenses)s.enabled&&("inbound"!==s.direction&&"bidirectional"!==s.direction||t.push(s.name),"outbound"!==s.direction&&"bidirectional"!==s.direction||n.push(s.name));return{inbound:t,outbound:n}}function updateCardStatus$1(e,t){return{...e,status:t,updatedAt:Date.now()}}function dismissCard$1(e){return updateCardStatus$1(e,"dismissed")}function shouldDisplayCard(e){return"dismissed"!==e.status&&"rejected"!==e.status}function cardToHandshakeParams(e){const t=getLensConfigForHandshake(e);return{partnerPubKey:e.partnerPubKey,holonId:e.holonId,holonName:e.holonName,lensConfig:t,message:e.message}}async function generateCapabilitiesForCard(e,t){const{outbound:n}=getLensConfigForHandshake(t);return 0===n.length?[]:issueCapabilitiesForLenses(e,t.holonId,n,t.partnerPubKey,{permissions:["read"]})}function renderCardAsText(e,t={}){const{initialLensCount:n=DEFAULT_INITIAL_LENS_COUNT}=t,{visibleLenses:s,hiddenCount:r,isExpanded:i}=getVisibleLenses(e,n),{inbound:a,outbound:o}=getLensConfigForHandshake(e),l=["┌─────────────────────────────────────────────────────┐","│ Federation Request │","├─────────────────────────────────────────────────────┤",`│ Partner: ${(e.partnerName||e.partnerPubKey.substring(0,16)+"...").padEnd(40)}│`,`│ Status: ${e.status.padEnd(40)}│`,"├─────────────────────────────────────────────────────┤","│ Lenses: │"];for(const c of s){const e=c.enabled?"✓":"○",t="bidirectional"===c.direction?"↔":"inbound"===c.direction?"←":"→";l.push(`│ ${e} ${c.name.padEnd(20)} ${t.padEnd(22)}│`)}return r>0&&l.push(`│ ... and ${r} more lenses (click to expand) │`),l.push("├─────────────────────────────────────────────────────┤"),l.push(`│ Sharing: ${o.length} lenses | Receiving: ${a.length} lenses`.padEnd(52)+"│"),l.push("└─────────────────────────────────────────────────────┘"),l.join("\n")}function serializeCard(e){return{...e,serializedAt:Date.now()}}function deserializeCard(e){return{...e,expanded:e.expanded||!1,lenses:e.lenses||[]}}const requestCard={createFederationCard:createFederationCard,updateLensConfig:updateLensConfig,toggleLens:toggleLens,enableAllLenses:enableAllLenses,disableAllLenses:disableAllLenses,toggleCardExpansion:toggleCardExpansion,getVisibleLenses:getVisibleLenses,getEnabledLenses:getEnabledLenses,getLensConfigForHandshake:getLensConfigForHandshake,updateCardStatus:updateCardStatus$1,dismissCard:dismissCard$1,shouldDisplayCard:shouldDisplayCard,cardToHandshakeParams:cardToHandshakeParams,generateCapabilitiesForCard:generateCapabilitiesForCard,renderCardAsText:renderCardAsText,serializeCard:serializeCard,deserializeCard:deserializeCard,DEFAULT_INITIAL_LENS_COUNT:DEFAULT_INITIAL_LENS_COUNT},requestCard$1=Object.freeze(Object.defineProperty({__proto__:null,cardToHandshakeParams:cardToHandshakeParams,createFederationCard:createFederationCard,default:requestCard,deserializeCard:deserializeCard,disableAllLenses:disableAllLenses,dismissCard:dismissCard$1,enableAllLenses:enableAllLenses,generateCapabilitiesForCard:generateCapabilitiesForCard,getEnabledLenses:getEnabledLenses,getLensConfigForHandshake:getLensConfigForHandshake,getVisibleLenses:getVisibleLenses,renderCardAsText:renderCardAsText,serializeCard:serializeCard,shouldDisplayCard:shouldDisplayCard,toggleCardExpansion:toggleCardExpansion,toggleLens:toggleLens,updateCardStatus:updateCardStatus$1,updateLensConfig:updateLensConfig},Symbol.toStringTag,{value:"Module"})),FEDERATION_CARDS_TABLE="_federation-cards",DISMISSED_REQUESTS_TABLE="_dismissed-federation-requests",PROCESSED_RESPONSES_TABLE="_processed-federation-responses",DM_STATE_TABLE="_federation-dm-state",PROCESSED_DMS_TABLE="_processed-federation-dms";async function saveCard(e,t,n){const s=serializeCard(n);return s.id=n.id,writeGlobal(e,t,FEDERATION_CARDS_TABLE,s)}async function getCard(e,t,n){const s=await readGlobal(e,t,FEDERATION_CARDS_TABLE,n);return s?deserializeCard(s):null}async function getAllCards(e,t){return(await getAllGlobal(e,t,FEDERATION_CARDS_TABLE)||[]).filter(e=>e&&!e._deleted).map(e=>deserializeCard(e))}async function getDisplayableCards(e,t){return(await getAllCards(e,t)).filter(shouldDisplayCard)}async function getCardByPartner(e,t,n){return(await getAllCards(e,t)).find(e=>e.partnerPubKey===n)||null}async function deleteCard(e,t,n){const s=await getCard(e,t,n);if(!s)return!1;const r={...s,id:n,_deleted:!0,deletedAt:Date.now()};return writeGlobal(e,t,FEDERATION_CARDS_TABLE,r)}async function dismissCard(e,t,n){const s=await getCard(e,t,n);return!!s&&(s.status="dismissed",s.dismissedAt=Date.now(),saveCard(e,t,s))}async function dismissRequest(e,t,n){const s={id:n,dismissedAt:Date.now()};return writeGlobal(e,t,DISMISSED_REQUESTS_TABLE,s)}async function isRequestDismissed(e,t,n){return!!(await readGlobal(e,t,DISMISSED_REQUESTS_TABLE,n))}async function getDismissedRequestIds(e,t){const n=await getAllGlobal(e,t,DISMISSED_REQUESTS_TABLE);return new Set((n||[]).map(e=>e.id))}async function markResponseProcessed(e,t,n,s){const r={id:`${n}_${s}`,requestId:n,responderPubKey:s,processedAt:Date.now()};return writeGlobal(e,t,PROCESSED_RESPONSES_TABLE,r)}async function isResponseProcessed(e,t,n,s){const r=`${n}_${s}`;return!!(await readGlobal(e,t,PROCESSED_RESPONSES_TABLE,r))}async function getProcessedResponseIds(e,t){const n=await getAllGlobal(e,t,PROCESSED_RESPONSES_TABLE);return new Set((n||[]).map(e=>e.id))}async function updateCardStatus(e,t,n,s){const r=await getCard(e,t,n);return!!r&&(r.status=s,r.statusUpdatedAt=Date.now(),saveCard(e,t,r))}async function findPendingCardsForPartner(e,t,n){return(await getAllCards(e,t)).filter(e=>e.partnerPubKey===n&&"pending"===e.status)}async function cleanupOldEntries(e,t,n=2592e6){const s={dismissedCleaned:0,responsesCleaned:0,cardsCleaned:0},r=Date.now()-n,i=await getAllGlobal(e,t,DISMISSED_REQUESTS_TABLE);for(const l of i||[])l.dismissedAt&&l.dismissedAt<r&&(await writeGlobal(e,t,DISMISSED_REQUESTS_TABLE,{id:l.id,_deleted:!0}),s.dismissedCleaned++);const a=await getAllGlobal(e,t,PROCESSED_RESPONSES_TABLE);for(const l of a||[])l.processedAt&&l.processedAt<r&&(await writeGlobal(e,t,PROCESSED_RESPONSES_TABLE,{id:l.id,_deleted:!0}),s.responsesCleaned++);const o=await getAllCards(e,t);for(const l of o)"dismissed"===l.status&&l.dismissedAt&&l.dismissedAt<r&&(await deleteCard(e,t,l.id),s.cardsCleaned++);return s}async function getLastDMFetchTime(e,t){const n=await readGlobal(e,t,DM_STATE_TABLE,"lastFetch");return n?.timestamp||0}async function setLastDMFetchTime(e,t,n){return writeGlobal(e,t,DM_STATE_TABLE,{id:"lastFetch",timestamp:n,updatedAt:Date.now()})}async function markDMProcessed(e,t,n,s="unknown"){return writeGlobal(e,t,PROCESSED_DMS_TABLE,{id:n,type:s,processedAt:Date.now()})}async function isDMProcessed(e,t,n){return!!(await readGlobal(e,t,PROCESSED_DMS_TABLE,n))}async function getProcessedDMIds(e,t){const n=await getAllGlobal(e,t,PROCESSED_DMS_TABLE);return new Set((n||[]).map(e=>e.id))}const cardStorage={saveCard:saveCard,getCard:getCard,getAllCards:getAllCards,getDisplayableCards:getDisplayableCards,getCardByPartner:getCardByPartner,deleteCard:deleteCard,dismissCard:dismissCard,dismissRequest:dismissRequest,isRequestDismissed:isRequestDismissed,getDismissedRequestIds:getDismissedRequestIds,markResponseProcessed:markResponseProcessed,isResponseProcessed:isResponseProcessed,getProcessedResponseIds:getProcessedResponseIds,updateCardStatus:updateCardStatus,findPendingCardsForPartner:findPendingCardsForPartner,cleanupOldEntries:cleanupOldEntries,getLastDMFetchTime:getLastDMFetchTime,setLastDMFetchTime:setLastDMFetchTime,markDMProcessed:markDMProcessed,isDMProcessed:isDMProcessed,getProcessedDMIds:getProcessedDMIds},cardStorage$1=Object.freeze(Object.defineProperty({__proto__:null,cleanupOldEntries:cleanupOldEntries,default:cardStorage,deleteCard:deleteCard,dismissCard:dismissCard,dismissRequest:dismissRequest,findPendingCardsForPartner:findPendingCardsForPartner,getAllCards:getAllCards,getCard:getCard,getCardByPartner:getCardByPartner,getDismissedRequestIds:getDismissedRequestIds,getDisplayableCards:getDisplayableCards,getLastDMFetchTime:getLastDMFetchTime,getProcessedDMIds:getProcessedDMIds,getProcessedResponseIds:getProcessedResponseIds,isDMProcessed:isDMProcessed,isRequestDismissed:isRequestDismissed,isResponseProcessed:isResponseProcessed,markDMProcessed:markDMProcessed,markResponseProcessed:markResponseProcessed,saveCard:saveCard,setLastDMFetchTime:setLastDMFetchTime,updateCardStatus:updateCardStatus},Symbol.toStringTag,{value:"Module"}));class LensKeyStore{constructor(){this.ownKeys=new Map,this.receivedKeys=new Map,this.partnerWrappedKeys=new Map}storeOwnKey(e,t,n){this.ownKeys.set(e,{key:t,wrappedForSelf:n,createdAt:Date.now()})}storeReceivedKey(e,t,n){this.receivedKeys.set(e,{key:t,fromPubKey:n,receivedAt:Date.now()})}getKey(e){const t=this.ownKeys.get(e);if(t)return t.key;const n=this.receivedKeys.get(e);return n?n.key:null}hasKey(e){return this.ownKeys.has(e)||this.receivedKeys.has(e)}isOwnKey(e){return this.ownKeys.has(e)}getOrCreateKey(e,t,n){const s=this.ownKeys.get(e);if(s)return{key:s.key,isNew:!1,wrappedForSelf:s.wrappedForSelf};if(this.receivedKeys.has(e)){return{key:this.receivedKeys.get(e).key,isNew:!1,wrappedForSelf:null}}const r=generateLensKey(),i=wrapKeyForRecipient(r,t,n);return this.storeOwnKey(e,r,i),{key:r,isNew:!0,wrappedForSelf:i}}wrapKeyForPartner(e,t,n){const s=this.getKey(e);if(!s)return null;const r=wrapKeyForRecipient(s,t,n);return this.partnerWrappedKeys.has(e)||this.partnerWrappedKeys.set(e,new Map),this.partnerWrappedKeys.get(e).set(n,r),r}getPartnersWithAccess(e){const t=this.partnerWrappedKeys.get(e);return t?Array.from(t.keys()):[]}revokePartnerAccess(e,t){const n=this.partnerWrappedKeys.get(e);return!!n&&n.delete(t)}rekeyLens(e,t,n,s=[]){const r=this.getPartnersWithAccess(e).filter(e=>!s.includes(e)),i=generateLensKey(),a=wrapKeyForRecipient(i,t,n);this.storeOwnKey(e,i,a);const o=new Map;this.partnerWrappedKeys.set(e,new Map);for(const l of r){const n=wrapKeyForRecipient(i,t,l);this.partnerWrappedKeys.get(e).set(l,n),o.set(l,n)}return{newKey:i,wrappedForSelf:a,partnerKeys:o}}receiveKey(e,t,n,s){const r=unwrapKey(t,n,s);return this.storeReceivedKey(e,r,s),r}exportOwnKeys(){const e=[];for(const[t,n]of this.ownKeys.entries())e.push({lensPath:t,wrappedForSelf:n.wrappedForSelf,createdAt:n.createdAt});return e}importOwnKeys(e,t,n){for(const s of e){const e=unwrapKey(s.wrappedForSelf,t,n);this.ownKeys.set(s.lensPath,{key:e,wrappedForSelf:s.wrappedForSelf,createdAt:s.createdAt})}}clear(){this.ownKeys.clear(),this.receivedKeys.clear(),this.partnerWrappedKeys.clear()}getStats(){let e=0;for(const t of this.partnerWrappedKeys.values())e+=t.size;return{ownKeyCount:this.ownKeys.size,receivedKeyCount:this.receivedKeys.size,totalPartnerGrants:e}}}function buildLensPath(e,t,n){return`${e}/${t}/${n}`}function parseLensPath(e){const t=e.split("/");if(t.length<3)throw new Error(`Invalid lens path: ${e}`);return{appName:t[0],holonId:t[1],lensName:t[2]}}function isV2LensConfig(e){return e&&"2.0"===e.version&&e.permissions}function normalizeLensConfig(e){return e?isV2LensConfig(e)?convertToLegacyLensConfig(e):{inbound:e.inbound||[],outbound:e.outbound||[],writeInbound:e.writeInbound||[],writeOutbound:e.writeOutbound||[]}:{inbound:[],outbound:[],writeInbound:[],writeOutbound:[]}}function toUnifiedPermissions(e){return e?isV2LensConfig(e)?e:convertLegacyLensConfig(e):{version:"2.0",permissions:{}}}function createFederationRequest({senderHolonId:e,senderHolonName:t,senderPubKey:n,lensConfig:s={inbound:[],outbound:[],writeInbound:[],writeOutbound:[]},capabilities:r=[],message:i,useV2:a=!1}){const o=a?toUnifiedPermissions(s):normalizeLensConfig(s);return{type:"federation_request",version:a?"2.0":"1.0",requestId:generateNonce$1(),timestamp:Date.now(),senderHolonId:e,senderHolonName:t,senderNpub:hexToNpub(n),lensConfig:o,capabilities:r,message:i}}function createFederationResponse({requestId:e,status:t,responderHolonId:n,responderHolonName:s,responderPubKey:r,lensConfig:i,capabilities:a,message:o,useV2:l=!1}){let c;return i&&(c=l?toUnifiedPermissions(i):normalizeLensConfig(i)),{type:"federation_response",version:l?"2.0":"1.0",requestId:e,timestamp:Date.now(),status:t,responderHolonId:n,responderHolonName:s,responderNpub:r?hexToNpub(r):void 0,lensConfig:c,capabilities:a,message:o}}async function sendFederationRequest$1(e,t,n,s){try{const r=JSON.stringify(s),i=createDMEvent(n,encryptNIP44(t,n,r),t);return e?.publish?(await e.publish(i),console.log("[Handshake] Federation request sent to:",n.substring(0,8)+"..."),!0):(console.error("[Handshake] No publish method on client"),!1)}catch(r){return console.error("[Handshake] Failed to send federation request:",r),!1}}async function sendFederationResponse(e,t,n,s){try{const r=JSON.stringify(s),i=createDMEvent(n,encryptNIP44(t,n,r),t);return e?.publish?(await e.publish(i),console.log("[Handshake] Federation response sent to:",n.substring(0,8)+"..."),!0):(console.error("[Handshake] No publish method on client"),!1)}catch(r){return console.error("[Handshake] Failed to send federation response:",r),!1}}async function sendLensKeyShare(e,t,n,s){try{const r={type:"lens_key_share",version:"1.0",lensPath:s.lensPath,wrappedKey:s.wrappedKey,timestamp:Date.now()},i=JSON.stringify(r),a=createDMEvent(n,encryptNIP44(t,n,i),t);return e?.publish?(await e.publish(a),console.log("[Handshake] Lens key share sent to:",n.substring(0,8)+"...","for lens:",s.lensPath),!0):(console.error("[Handshake] No publish method on client"),!1)}catch(r){return console.error("[Handshake] Failed to send lens key share:",r),!1}}function subscribeToFederationDMs(e,t,n,s,r={}){const{onRequest:i,onResponse:a,onUpdate:o,onUpdateResponse:l,onKeyShare:c}=s,{appname:u}=r;let d=!0;const f=new Set;let h=new Set,p=new Set,y=0;const g=async s=>{if(!d)return;if(f.has(s.id))return;if(f.add(s.id),h.has(s.id))return;if(4!==s.kind)return;const r=s.tags?.find(e=>"p"===e[0]);if(r&&r[1]===n)try{let n;try{n=decryptNIP44(t,s.pubkey,s.content)}catch(y){n=await decryptNIP04(t,s.pubkey,s.content)}const r=JSON.parse(n);if("federation_request"===r.type&&"1.0"===r.version){if(u&&e?.client){if(await isRequestDismissed(e.client,u,r.requestId))return console.log("[Handshake] Skipping dismissed request:",r.requestId),await markDMProcessed(e.client,u,s.id,"request"),void h.add(s.id)}u&&e?.client&&(await markDMProcessed(e.client,u,s.id,"request"),h.add(s.id)),console.log("[Handshake] Received federation request from:",s.pubkey.substring(0,8)+"..."),i?.(r,s.pubkey)}else if("federation_response"===r.type&&"1.0"===r.version){const t=`${r.requestId}_${s.pubkey}`;if(p.has(t))return void console.log("[Handshake] Skipping already processed response:",t);u&&e?.client&&(await markResponseProcessed(e.client,u,r.requestId,s.pubkey),await markDMProcessed(e.client,u,s.id,"response"),p.add(t),h.add(s.id)),console.log("[Handshake] Received federation response from:",s.pubkey.substring(0,8)+"..."),a?.(r,s.pubkey)}else if("federation_update"===r.type&&"1.0"===r.version){if(u&&e?.client){if(await isRequestDismissed(e.client,u,r.updateId))return console.log("[Handshake] Skipping dismissed update:",r.updateId),await markDMProcessed(e.client,u,s.id,"update"),void h.add(s.id)}u&&e?.client&&(await markDMProcessed(e.client,u,s.id,"update"),h.add(s.id)),console.log("[Handshake] Received federation update from:",s.pubkey.substring(0,8)+"..."),o?.(r,s.pubkey)}else if("federation_update_response"===r.type&&"1.0"===r.version){const t=`update_${r.updateId}_${s.pubkey}`;if(p.has(t))return void console.log("[Handshake] Skipping already processed update response:",t);u&&e?.client&&(await markResponseProcessed(e.client,u,r.updateId,s.pubkey),await markDMProcessed(e.client,u,s.id,"update_response"),p.add(t),h.add(s.id)),console.log("[Handshake] Received federation update response from:",s.pubkey.substring(0,8)+"..."),l?.(r,s.pubkey)}else if("lens_key_share"===r.type&&"1.0"===r.version){const t=`key_${r.lensPath}_${s.pubkey}`;if(p.has(t))return void console.log("[Handshake] Skipping already processed key share:",t);u&&e?.client&&(await markDMProcessed(e.client,u,s.id,"key_share"),p.add(t),h.add(s.id)),console.log("[Handshake] Received lens key share from:",s.pubkey.substring(0,8)+"...","for lens:",r.lensPath),c?.(r,s.pubkey)}}catch(g){}};let m=null;return(async()=>{await(async()=>{if(u&&e?.client)try{h=await getProcessedDMIds(e.client,u),p=await getProcessedResponseIds(e.client,u),y=await getLastDMFetchTime(e.client,u),console.log("[Handshake] Loaded persisted state - last fetch:",y,"processed DMs:",h.size)}catch(t){console.warn("[Handshake] Could not load persisted state:",t.message)}})();const t=e?.client;if(!t?.subscribe)return void console.warn("[Handshake] No NostrClient subscribe method available");const s=y||0;console.log("[Handshake] Fetching DMs since:",s?new Date(1e3*s).toISOString():"beginning of time");const r={kinds:[4],"#p":[n],since:s};try{if(m=await t.subscribe(r,g,{}),console.log("[Handshake] Federation DM subscription started"),u&&e?.client){const t=Math.floor(Date.now()/1e3);await setLastDMFetchTime(e.client,u,t)}}catch(i){console.error("[Handshake] Failed to subscribe:",i)}})(),()=>{d=!1,m?.unsubscribe?m.unsubscribe():m?.close&&m.close()}}async function initiateFederationHandshake(e,t,n){const{partnerPubKey:s,holonId:r,holonName:i,lensConfig:a={inbound:[],outbound:[],writeInbound:[],writeOutbound:[]},message:o}=n;try{const n=getPublicKey$1(t),c={inbound:a.inbound||[],outbound:a.outbound||[],writeInbound:a.writeInbound||[],writeOutbound:a.writeOutbound||[]},u=[];for(const e of c.outbound)try{const i=await issueCapability$1(["read"],{holonId:r,lensName:e,dataId:"*"},s,{expiresIn:31536e6,issuer:n,issuerKey:t});u.push({token:i,scope:{holonId:r,lensName:e},permissions:["read"]})}catch(l){console.warn(`[Handshake] Failed to issue capability for ${e}:`,l.message)}if(e.client){for(const t of c.writeOutbound)try{await grantAccess(e.client,e.config.appName,s,{holonId:"*",lensName:t},["write"],{direction:"inbound"}),console.log(`[Handshake] Pre-granted write access to partner for lens "${t}"`)}catch(l){console.warn(`[Handshake] Failed to grant write access for ${t}:`,l.message)}for(const t of c.outbound)try{await grantAccess(e.client,e.config.appName,s,{holonId:"*",lensName:t},["read"],{direction:"outbound"})}catch(l){console.warn(`[Handshake] Failed to grant read access for ${t}:`,l.message)}}const d=createFederationRequest({senderHolonId:r,senderHolonName:i,senderPubKey:n,lensConfig:c,capabilities:u,message:o});e.client&&await addFederatedPartner(e.client,e.config.appName,s,{alias:null,addedVia:"handshake_initiated"});return await sendFederationRequest$1(e.client,t,s,d)?{success:!0,requestId:d.requestId}:{success:!1,error:"Failed to send DM"}}catch(c){return{success:!1,error:c.message}}}async function acceptFederationRequest$1(e,t,n){const{request:s,senderPubKey:r,holonId:i,holonName:a,lensConfig:o={inbound:[],outbound:[],writeInbound:[],writeOutbound:[]},message:l}=n;try{const n=getPublicKey$1(t),u={inbound:o.inbound||[],outbound:o.outbound||[],writeInbound:o.writeInbound||[],writeOutbound:o.writeOutbound||[]};if(e.client){if(await addFederatedPartner(e.client,e.config.appName,r,{alias:s.senderHolonName,addedVia:"handshake_accepted"}),s.capabilities&&s.capabilities.length>0)for(const n of s.capabilities)await storeInboundCapability(e.client,e.config.appName,r,n);const t=s.lensConfig?.writeOutbound||[];t.length>0&&console.log("[Handshake] Sender is granting write access for lenses:",t);for(const n of u.writeOutbound)try{await grantAccess(e.client,e.config.appName,r,{holonId:"*",lensName:n},["write"],{direction:"inbound"}),console.log(`[Handshake] Granted write access to sender for lens "${n}"`)}catch(c){console.warn(`[Handshake] Failed to grant write access for ${n}:`,c.message)}for(const n of u.outbound)try{await grantAccess(e.client,e.config.appName,r,{holonId:"*",lensName:n},["read"],{direction:"outbound"})}catch(c){console.warn(`[Handshake] Failed to grant read access for ${n}:`,c.message)}s.senderHolonId&&(await registerHolon(e.client,e.config.appName,s.senderHolonId,r,{alias:s.senderHolonName}),console.log("[Handshake] Registered partner holon:",{holonId:s.senderHolonId,pubKey:r?.slice(0,12)+"..."}))}await e.federateHolon(i,r,{lensConfig:u,partnerName:s.senderHolonName});const d=[];for(const e of u.outbound)try{const s=await issueCapability$1(["read"],{holonId:i,lensName:e,dataId:"*"},r,{expiresIn:31536e6,issuer:n,issuerKey:t});d.push({token:s,scope:{holonId:i,lensName:e},permissions:["read"]})}catch(c){console.warn(`[Handshake] Failed to issue capability for ${e}:`,c.message)}if(e.keyStore&&e.client?.privateKey)for(const s of u.outbound){const i=buildLensPath(e.config.appName,n,s);if(e.keyStore.getKey(i))try{const n=e.keyStore.wrapKeyForPartner(i,e.client.privateKey,r);n&&(await sendLensKeyShare(e.client,t,r,{lensPath:i,wrappedKey:n}),console.log(`[Handshake] Shared lens key for "${s}" with partner`))}catch(c){console.warn(`[Handshake] Failed to share lens key for ${s}:`,c.message)}}const f=createFederationResponse({requestId:s.requestId,status:"accepted",responderHolonId:i,responderHolonName:a,responderPubKey:n,lensConfig:u,capabilities:d,message:l});if(await sendFederationResponse(e.client,t,r,f)){e.client&&s.requestId&&(await dismissRequest(e.client,e.config.appName,s.requestId),console.log("[Handshake] Request dismissed after acceptance:",s.requestId));const t={},n=u.inbound;if(n.length>0&&e.receiveFederatedLens){console.log("[Handshake] Receiving federated lens data as holograms...");for(const a of n)try{const n=s.senderHolonId,o=await e.receiveFederatedLens(r,n,a,i,{overwrite:!1});t[a]=o,console.log(`[Handshake] Received ${o.received} holograms for lens "${a}"`)}catch(c){console.warn(`[Handshake] Failed to receive holograms for lens "${a}":`,c.message),t[a]={error:c.message}}}return{success:!0,requestId:s.requestId,receivedHolograms:t}}return{success:!1,error:"Failed to send response DM"}}catch(u){return{success:!1,error:u.message}}}async function rejectFederationRequest(e,t,n){const{requestId:s,senderPubKey:r,message:i}=n;try{const n=createFederationResponse({requestId:s,status:"rejected",message:i}),a=await sendFederationResponse(e.client,t,r,n);return{success:a,error:a?void 0:"Failed to send response DM"}}catch(a){return{success:!1,error:a.message}}}async function processFederationResponse(e,t,n,s={}){if(!t||"accepted"!==t.status)return{success:!1,error:"Response not accepted",storedCapabilities:0};const{holonId:r,inboundLenses:i=[]}=s;let a=0;if(e.client&&t.capabilities&&t.capabilities.length>0)for(const u of t.capabilities)try{await storeInboundCapability(e.client,e.config.appName,n,u),a++}catch(c){console.warn("[Handshake] Failed to store capability:",c.message)}e.client&&(await addFederatedPartner(e.client,e.config.appName,n,{alias:t.responderHolonName,addedVia:"handshake_accepted"}),t.responderHolonId&&(await registerHolon(e.client,e.config.appName,t.responderHolonId,n,{alias:t.responderHolonName}),console.log("[Handshake] Registered partner holon from response:",{holonId:t.responderHolonId,pubKey:n?.slice(0,12)+"..."})));const o={},l=t.responderHolonId;if(r&&l&&i.length>0&&e.receiveFederatedLens){console.log("[Handshake] Receiving federated lens data as holograms from responder...");for(const t of i)try{const s=await e.receiveFederatedLens(n,l,t,r,{overwrite:!1});o[t]=s,console.log(`[Handshake] Received ${s.received} holograms for lens "${t}"`)}catch(c){console.warn(`[Handshake] Failed to receive holograms for lens "${t}":`,c.message),o[t]={error:c.message}}}return{success:!0,storedCapabilities:a,receivedHolograms:o}}function isFederationRequest(e){return"federation_request"===e?.type&&"1.0"===e?.version}function isFederationResponse(e){return"federation_response"===e?.type&&"1.0"===e?.version}function createFederationUpdate({senderHolonId:e,senderHolonName:t,senderPubKey:n,newLensConfig:s,message:r}){return{type:"federation_update",version:"1.0",updateId:generateNonce$1(),timestamp:Date.now(),senderHolonId:e,senderHolonName:t,senderNpub:hexToNpub(n),newLensConfig:s,message:r}}function createFederationUpdateResponse({updateId:e,status:t,message:n}){return{type:"federation_update_response",version:"1.0",updateId:e,timestamp:Date.now(),status:t,message:n}}async function sendFederationUpdate(e,t,n,s){try{const r=JSON.stringify(s),i=createDMEvent(n,encryptNIP44(t,n,r),t);return!!e?.publish&&(await e.publish(i),console.log("[Handshake] Federation update sent to:",n.substring(0,8)+"..."),!0)}catch(r){return console.error("[Handshake] Failed to send federation update:",r),!1}}async function sendFederationUpdateResponse(e,t,n,s){try{const r=JSON.stringify(s),i=createDMEvent(n,encryptNIP44(t,n,r),t);return!!e?.publish&&(await e.publish(i),console.log("[Handshake] Federation update response sent to:",n.substring(0,8)+"..."),!0)}catch(r){return console.error("[Handshake] Failed to send federation update response:",r),!1}}async function requestFederationUpdate(e,t,n){const{partnerPubKey:s,holonId:r,holonName:i,newLensConfig:a,message:o}=n;try{const n=createFederationUpdate({senderHolonId:r,senderHolonName:i,senderPubKey:getPublicKey$1(t),newLensConfig:a,message:o});return await sendFederationUpdate(e.client,t,s,n)?{success:!0,updateId:n.updateId}:{success:!1,error:"Failed to send update DM"}}catch(l){return{success:!1,error:l.message}}}async function acceptFederationUpdate(e,t,n){const{updateId:s,senderPubKey:r,holonId:i,newLensConfig:a,message:o}=n;try{e.federateHolon&&await e.federateHolon(i,r,{lensConfig:a});const n=createFederationUpdateResponse({updateId:s,status:"accepted",message:o}),l=await sendFederationUpdateResponse(e.client,t,r,n);return{success:l,error:l?void 0:"Failed to send response"}}catch(l){return{success:!1,error:l.message}}}async function rejectFederationUpdate(e,t,n){const{updateId:s,senderPubKey:r,message:i}=n;try{const n=createFederationUpdateResponse({updateId:s,status:"rejected",message:i}),a=await sendFederationUpdateResponse(e.client,t,r,n);return{success:a,error:a?void 0:"Failed to send response"}}catch(a){return{success:!1,error:a.message}}}function isFederationUpdate(e){return"federation_update"===e?.type&&"1.0"===e?.version}function isFederationUpdateResponse(e){return"federation_update_response"===e?.type&&"1.0"===e?.version}const handshake=Object.freeze(Object.defineProperty({__proto__:null,acceptFederationRequest:acceptFederationRequest$1,acceptFederationUpdate:acceptFederationUpdate,createFederationRequest:createFederationRequest,createFederationResponse:createFederationResponse,createFederationUpdate:createFederationUpdate,createFederationUpdateResponse:createFederationUpdateResponse,initiateFederationHandshake:initiateFederationHandshake,isFederationRequest:isFederationRequest,isFederationResponse:isFederationResponse,isFederationUpdate:isFederationUpdate,isFederationUpdateResponse:isFederationUpdateResponse,isV2LensConfig:isV2LensConfig,normalizeLensConfig:normalizeLensConfig,processFederationResponse:processFederationResponse,rejectFederationRequest:rejectFederationRequest,rejectFederationUpdate:rejectFederationUpdate,requestFederationUpdate:requestFederationUpdate,sendFederationRequest:sendFederationRequest$1,sendFederationResponse:sendFederationResponse,sendFederationUpdate:sendFederationUpdate,sendFederationUpdateResponse:sendFederationUpdateResponse,sendLensKeyShare:sendLensKeyShare,subscribeToFederationDMs:subscribeToFederationDMs,toUnifiedPermissions:toUnifiedPermissions},Symbol.toStringTag,{value:"Module"}));function validateNostrEvent(e,t=!0,n=!1){if(!e||"object"!=typeof e){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format");return!1}if("number"!=typeof e.kind){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - kind must be a number");return!1}if(!Array.isArray(e.tags)){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - tags must be an array");return!1}if("string"!=typeof e.content){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - content must be a string");return!1}if("number"!=typeof e.created_at){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - created_at must be a number");return!1}if(!t){if("string"!=typeof e.id){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - id must be a string");return!1}if("string"!=typeof e.pubkey){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - pubkey must be a string");return!1}if("string"!=typeof e.sig){if(n)throw new ValidationError$1("ValidationError: Invalid Nostr event format - sig must be a string");return!1}}return!0}function validateActivityPubObject(e,t=!1,n=!1){if(!e||"object"!=typeof e){if(t)throw new ValidationError$1("ValidationError: Invalid ActivityPub object format");return!1}if(!e["@context"]){if(t)throw new ValidationError$1("ValidationError: Invalid ActivityPub object format - @context is required");return!1}if("string"!=typeof e.type){if(t)throw new ValidationError$1("ValidationError: Invalid ActivityPub object format - type must be a string");return!1}if(n&&"string"!=typeof e.id){if(t)throw new ValidationError$1("ValidationError: Invalid ActivityPub object format - id must be a string");return!1}return!0}function transformNostrEvent(e){const t=e.id||`nostr-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n=e.pubkey||"anonymous",s=e.sig||"";return{id:t,protocol:"nostr",originalFormat:"nip-01",pubkey:n,sig:s,created_at:e.created_at,kind:e.kind,tags:JSON.stringify(e.tags),content:e.content,signature:s,_meta:{timestamp:1e3*e.created_at,protocol:"nostr"}}}function transformActivityPubObject(e){const t=e.id||`ap-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return{id:t,protocol:"activitypub",type:e.type,actor:e.actor,published:e.published,content:e.content||e.name,originalObject:{...e,id:t},_meta:{timestamp:e.published?new Date(e.published).getTime():Date.now(),protocol:"activitypub"}}}function filterByAccessLevel(e,t){return t?e.filter(e=>!e.accessLevel||e.accessLevel===t):e}function filterByProtocol(e,t){return t&&"all"!==t?Array.isArray(e)?e.filter(e=>e.protocol===t):[]:e}const socialProtocols=Object.freeze(Object.defineProperty({__proto__:null,filterByAccessLevel:filterByAccessLevel,filterByProtocol:filterByProtocol,transformActivityPubObject:transformActivityPubObject,transformNostrEvent:transformNostrEvent,validateActivityPubObject:validateActivityPubObject,validateNostrEvent:validateNostrEvent},Symbol.toStringTag,{value:"Module"}));async function createSubscription(e,t,n,s={}){const{throttle:r=0,filter:i=null,includeFederated:a=!1,triggerInitial:o=!1,realtimeOnly:l=!0,resolveHolograms:c=!0,appname:u=null}=s;let d=0,f=null;const h=new Set;let p=!0;const y=await subscribe(e,t,async(t,s)=>{if(!p)return;const a=`${s}-${t?.id||""}-${t?._meta?.lastUpdated||t?._meta?.timestamp||Date.now()}`;if(h.has(a))return;h.add(a);let o=t;if(c&&t&&!0===t.hologram)try{if(o=await resolveHologram(e,t,void 0,void 0,{appname:u}),!o)return void console.debug("[subscription] Hologram resolution returned null, skipping:",{id:t.id,soul:t.soul,target:t.target?.holonId?.slice(0,12)})}catch(y){return void console.warn("Failed to resolve hologram in subscription:",y,{id:t?.id,soul:t?.soul,target:t?.target?.holonId?.slice(0,12)})}if(i&&!i(o,s))return;const l=Date.now();if(r>0&&l-d<r)return f&&clearTimeout(f),void(f=setTimeout(()=>{d=Date.now(),n(o,s)},r-(l-d)));d=l,n(o,s)},{realtimeOnly:l,...s.authors&&{authors:s.authors}});return{path:t,unsubscribe:()=>{p=!1,f&&clearTimeout(f),y&&y.unsubscribe&&y.unsubscribe(),h.clear()}}}class SubscriptionRegistry{constructor(){this.subscriptions=new Map}register(e,t){this.subscriptions.set(e,t)}unregister(e){const t=this.subscriptions.get(e);t&&(t.unsubscribe(),this.subscriptions.delete(e))}unsubscribeAll(){for(const[e,t]of this.subscriptions)t.unsubscribe();this.subscriptions.clear()}count(){return this.subscriptions.size}}const manager=Object.freeze(Object.defineProperty({__proto__:null,SubscriptionRegistry:SubscriptionRegistry,createSubscription:createSubscription},Symbol.toStringTag,{value:"Module"}));async function upcast(e,t,n,s,r={}){const{maxLevel:i=3,operation:a="concatenate"}=r,o=e.client,l=e.config.appName;if(!isValidH3(t))throw new Error("Upcast only supported for geographic (H3) holons, not noospheric holons");const c=getParents(t).slice(0,i);if(0===c.length)return!0;const u=c.map(async e=>propagateToParent(o,l,t,e,n,s,a));return await Promise.all(u),!0}async function propagateToParent(e,t,n,s,r,i,a){const o=await createHologramWithCapability(e,n,s,r,i,t,{sourceAuthorPubKey:e.publicKey,permissions:["read"]});o._meta.operation=a,o._meta.upcast=!0;return write(e,`${t}/${s}/${r}/${i}`,o)}function summarize(e){return{operation:"summarize",count:e.length,summary:!0}}function aggregate(e){const t={operation:"aggregate"};for(const n of e)Object.assign(t,n);return t}function concatenate(e){return{operation:"concatenate",items:e.flat()}}const upcast$1=Object.freeze(Object.defineProperty({__proto__:null,aggregate:aggregate,concatenate:concatenate,summarize:summarize,upcast:upcast},Symbol.toStringTag,{value:"Module"})),default_format="RFC3986",formatters={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},RFC1738="RFC1738",is_array$1=Array.isArray,hex_table=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),limit=1024,encode=(e,t,n,s,r)=>{if(0===e.length)return e;let i=e;if("symbol"==typeof e?i=Symbol.prototype.toString.call(e):"string"!=typeof e&&(i=String(e)),"iso-8859-1"===n)return escape(i).replace(/%u[0-9a-f]{4}/gi,function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"});let a="";for(let o=0;o<i.length;o+=limit){const e=i.length>=limit?i.slice(o,o+limit):i,t=[];for(let n=0;n<e.length;++n){let s=e.charCodeAt(n);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||r===RFC1738&&(40===s||41===s)?t[t.length]=e.charAt(n):s<128?t[t.length]=hex_table[s]:s<2048?t[t.length]=hex_table[192|s>>6]+hex_table[128|63&s]:s<55296||s>=57344?t[t.length]=hex_table[224|s>>12]+hex_table[128|s>>6&63]+hex_table[128|63&s]:(n+=1,s=65536+((1023&s)<<10|1023&e.charCodeAt(n)),t[t.length]=hex_table[240|s>>18]+hex_table[128|s>>12&63]+hex_table[128|s>>6&63]+hex_table[128|63&s])}a+=t.join("")}return a};function is_buffer(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function maybe_map(e,t){if(is_array$1(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const has=Object.prototype.hasOwnProperty,array_prefix_generators={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},is_array=Array.isArray,push=Array.prototype.push,push_to_array=function(e,t){push.apply(e,is_array(t)?t:[t])},to_ISO=Date.prototype.toISOString,defaults={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:encode,encodeValuesOnly:!1,format:default_format,formatter:formatters[default_format],indices:!1,serializeDate:e=>to_ISO.call(e),skipNulls:!1,strictNullHandling:!1};function is_non_nullish_primitive(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}const sentinel={};function inner_stringify(e,t,n,s,r,i,a,o,l,c,u,d,f,h,p,y,g,m){let b=e,w=m,_=0,v=!1;for(;void 0!==(w=w.get(sentinel))&&!v;){const t=w.get(e);if(_+=1,void 0!==t){if(t===_)throw new RangeError("Cyclic object value");v=!0}void 0===w.get(sentinel)&&(_=0)}if("function"==typeof c?b=c(t,b):b instanceof Date?b=f?.(b):"comma"===n&&is_array(b)&&(b=maybe_map(b,function(e){return e instanceof Date?f?.(e):e})),null===b){if(i)return l&&!y?l(t,defaults.encoder,g,"key",h):t;b=""}if(is_non_nullish_primitive(b)||is_buffer(b)){if(l){const e=y?t:l(t,defaults.encoder,g,"key",h);return[p?.(e)+"="+p?.(l(b,defaults.encoder,g,"value",h))]}return[p?.(t)+"="+p?.(String(b))]}const E=[];if(void 0===b)return E;let A;if("comma"===n&&is_array(b))y&&l&&(b=maybe_map(b,l)),A=[{value:b.length>0?b.join(",")||null:void 0}];else if(is_array(c))A=c;else{const e=Object.keys(b);A=u?e.sort(u):e}const S=o?String(t).replace(/\./g,"%2E"):String(t),k=s&&is_array(b)&&1===b.length?S+"[]":S;if(r&&is_array(b)&&0===b.length)return k+"[]";for(let T=0;T<A.length;++T){const t=A[T],w="object"==typeof t&&void 0!==t.value?t.value:b[t];if(a&&null===w)continue;const v=d&&o?t.replace(/\./g,"%2E"):t,S=is_array(b)?"function"==typeof n?n(k,v):k:k+(d?"."+v:"["+v+"]");m.set(e,_);const C=new WeakMap;C.set(sentinel,m),push_to_array(E,inner_stringify(w,S,n,s,r,i,a,o,"comma"===n&&y&&is_array(b)?null:l,c,u,d,f,h,p,y,g,C))}return E}function normalize_stringify_options(e=defaults){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||defaults.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=default_format;if(void 0!==e.format){if(!has.call(formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=formatters[n];let r,i=defaults.filter;if(("function"==typeof e.filter||is_array(e.filter))&&(i=e.filter),r=e.arrayFormat&&e.arrayFormat in array_prefix_generators?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":defaults.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=void 0===e.allowDots?!0==!!e.encodeDotInKeys||defaults.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:defaults.addQueryPrefix,allowDots:a,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:defaults.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?defaults.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:defaults.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:defaults.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:defaults.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:defaults.encodeValuesOnly,filter:i,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:defaults.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:defaults.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults.strictNullHandling}}function stringify$1(e,t={}){let n=e;const s=normalize_stringify_options(t);let r,i;"function"==typeof s.filter?(i=s.filter,n=i("",n)):is_array(s.filter)&&(i=s.filter,r=i);const a=[];if("object"!=typeof n||null===n)return"";const o=array_prefix_generators[s.arrayFormat],l="comma"===o&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let f=0;f<r.length;++f){const e=r[f];s.skipNulls&&null===n[e]||push_to_array(a,inner_stringify(n[e],e,o,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,c))}const u=a.join(s.delimiter);let d=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}const VERSION="4.104.0";let auto=!1,kind,fetch$1,FormData$1,File$1,ReadableStream$1,getMultipartRequestOptions,getDefaultAgent,fileFromPath,isFsReadStream;function setShims(e,t={auto:!1}){if(auto)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(kind)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${kind}'\``);auto=t.auto,kind=e.kind,fetch$1=e.fetch,FormData$1=e.FormData,File$1=e.File,ReadableStream$1=e.ReadableStream,getMultipartRequestOptions=e.getMultipartRequestOptions,getDefaultAgent=e.getDefaultAgent,fileFromPath=e.fileFromPath,isFsReadStream=e.isFsReadStream}class MultipartBody{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function getRuntime({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let n,s,r,i;try{n=fetch,s=Request,r=Response,i=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${t}`)}return{kind:"web",fetch:n,Request:s,Response:r,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new MultipartBody(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}const init=()=>{kind||setShims(getRuntime(),{auto:!0})};init();class OpenAIError extends Error{}class APIError extends OpenAIError{constructor(e,t,n,s){super(`${APIError.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new APIConnectionError({message:n,cause:castToError(t)});const r=t?.error;return 400===e?new BadRequestError(e,r,n,s):401===e?new AuthenticationError(e,r,n,s):403===e?new PermissionDeniedError(e,r,n,s):404===e?new NotFoundError(e,r,n,s):409===e?new ConflictError(e,r,n,s):422===e?new UnprocessableEntityError(e,r,n,s):429===e?new RateLimitError(e,r,n,s):e>=500?new InternalServerError(e,r,n,s):new APIError(e,r,n,s)}}class APIUserAbortError extends APIError{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class APIConnectionError extends APIError{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class APIConnectionTimeoutError extends APIConnectionError{constructor({message:e}={}){super({message:e??"Request timed out."})}}class BadRequestError extends APIError{}class AuthenticationError extends APIError{}class PermissionDeniedError extends APIError{}class NotFoundError extends APIError{}class ConflictError extends APIError{}class UnprocessableEntityError extends APIError{}class RateLimitError extends APIError{}class InternalServerError extends APIError{}class LengthFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the length limit was reached")}}class ContentFilterFinishReasonError extends OpenAIError{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var __classPrivateFieldSet$5=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},__classPrivateFieldGet$6=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_LineDecoder_carriageReturnIndex;class LineDecoder{constructor(){_LineDecoder_carriageReturnIndex.set(this,void 0),this.buffer=new Uint8Array,__classPrivateFieldSet$5(this,_LineDecoder_carriageReturnIndex,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let r;for(;null!=(r=findNewlineIndex(this.buffer,__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")));){if(r.carriage&&null==__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")){__classPrivateFieldSet$5(this,_LineDecoder_carriageReturnIndex,r.index,"f");continue}if(null!=__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")&&(r.index!==__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")+1||r.carriage)){s.push(this.decodeText(this.buffer.slice(0,__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")-1))),this.buffer=this.buffer.slice(__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")),__classPrivateFieldSet$5(this,_LineDecoder_carriageReturnIndex,null,"f");continue}const e=null!==__classPrivateFieldGet$6(this,_LineDecoder_carriageReturnIndex,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));s.push(t),this.buffer=this.buffer.slice(r.index),__classPrivateFieldSet$5(this,_LineDecoder_carriageReturnIndex,null,"f")}return s}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new OpenAIError(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new OpenAIError("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function findNewlineIndex(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function findDoubleNewlineIndex(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function ReadableStreamToAsyncIterable(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}_LineDecoder_carriageReturnIndex=new WeakMap,LineDecoder.NEWLINE_CHARS=new Set(["\n","\r"]),LineDecoder.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Stream{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new Stream(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of _iterSSEMessages(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event||n.event.startsWith("response.")||n.event.startsWith("transcript.")){let t;try{t=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if(t&&t.error)throw new APIError(void 0,t.error,void 0,createResponseHeaders(e.headers));yield t}else{let e;try{e=JSON.parse(n.data)}catch(r){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),r}if("error"==n.event)throw new APIError(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}static fromReadableStream(e,t){let n=!1;return new Stream(async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new LineDecoder,n=ReadableStreamToAsyncIterable(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(r){if(r instanceof Error&&"AbortError"===r.name)return;throw r}finally{s||t.abort()}},t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new Stream(()=>s(e),this.controller),new Stream(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new ReadableStream$1({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const i=n.encode(JSON.stringify(s)+"\n");e.enqueue(i)}catch(s){e.error(s)}},async cancel(){await(t.return?.())}})}}async function*_iterSSEMessages(e,t){if(!e.body)throw t.abort(),new OpenAIError("Attempted to iterate over a response with no body");const n=new SSEDecoder,s=new LineDecoder,r=ReadableStreamToAsyncIterable(e.body);for await(const i of iterSSEChunks(r))for(const e of s.decode(i)){const t=n.decode(e);t&&(yield t)}for(const i of s.flush()){const e=n.decode(i);e&&(yield e)}}async function*iterSSEChunks(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=findDoubleNewlineIndex(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}class SSEDecoder{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=partition(e,":");return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}function partition(e,t){const n=e.indexOf(t);return-1!==n?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}const isResponseLike=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,isFileLike=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&isBlobLike(e),isBlobLike=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,isUploadable=e=>isFileLike(e)||isResponseLike(e)||isFsReadStream(e);async function toFile(e,t,n){if(e=await e,isFileLike(e))return e;if(isResponseLike(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=isBlobLike(s)?[await s.arrayBuffer()]:[s];return new File$1(r,t,n)}const s=await getBytes$1(e);if(t||(t=getName(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new File$1(s,t,n)}async function getBytes$1(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(isBlobLike(e))t.push(await e.arrayBuffer());else{if(!isAsyncIterableIterator(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${propsForError(e)}`);for await(const n of e)t.push(n)}return t}function propsForError(e){return`[${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(", ")}]`}function getName(e){return getStringFromMaybeBuffer(e.name)||getStringFromMaybeBuffer(e.filename)||getStringFromMaybeBuffer(e.path)?.split(/[\\/]/).pop()}const getStringFromMaybeBuffer=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,isAsyncIterableIterator=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],isMultipartBody=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],multipartFormRequestOptions=async e=>{const t=await createForm(e.body);return getMultipartRequestOptions(t,e)},createForm=async e=>{const t=new FormData$1;return await Promise.all(Object.entries(e||{}).map(([e,n])=>addFormValue(t,e,n))),t},addFormValue=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if(isUploadable(n)){const s=await toFile(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map(n=>addFormValue(e,t+"[]",n)));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map(([n,s])=>addFormValue(e,`${t}[${n}]`,s)))}}};var __classPrivateFieldSet$4=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},__classPrivateFieldGet$5=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_AbstractPage_client;async function defaultParseResponse(e){const{response:t}=e;if(e.options.stream)return debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Stream.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const e=await t.json();return debug("response",t.status,t.url,t.headers,e),_addRequestID(e,t)}const r=await t.text();return debug("response",t.status,t.url,t.headers,r),r}function _addRequestID(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}init();class APIPromise extends Promise{constructor(e,t=defaultParseResponse){super(e=>{e(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new APIPromise(this.responsePromise,async t=>_addRequestID(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class APIClient{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=validatePositiveInteger("maxRetries",t),this.timeout=validatePositiveInteger("timeout",n),this.httpAgent=s,this.fetch=r??fetch$1}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...getPlatformHeaders(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${uuid4()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async n=>{const s=n&&isBlobLike(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:r,query:i,headers:a={}}=n,o=ArrayBuffer.isView(n.body)||n.__binaryRequest&&"string"==typeof n.body?n.body:isMultipartBody(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,l=this.calculateContentLength(o),c=this.buildURL(r,i);"timeout"in n&&validatePositiveInteger("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const u=n.httpAgent??this.httpAgent??getDefaultAgent(c),d=n.timeout+1e3;"number"==typeof u?.options?.timeout&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:s,...o&&{body:o},headers:this.buildHeaders({options:n,headers:a,contentLength:l,retryCount:t}),...u&&{agent:u},signal:n.signal??null},url:c,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const i=this.defaultHeaders(e);return applyHeadersMut(r,i),applyHeadersMut(r,t),isMultipartBody(e.body)&&"node"!==kind&&delete r["content-type"],void 0===getHeader(i,"x-stainless-retry-count")&&void 0===getHeader(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),void 0===getHeader(i,"x-stainless-timeout")&&void 0===getHeader(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(e=>[...e])):{...e}:{}}makeStatusError(e,t,n,s){return APIError.generate(e,t,n,s)}request(e,t=null){return new APIPromise(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:i,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:i,options:n}),debug("request",i,n,r.headers),n.signal?.aborted)throw new APIUserAbortError;const o=new AbortController,l=await this.fetchWithTimeout(i,r,a,o).catch(castToError);if(l instanceof Error){if(n.signal?.aborted)throw new APIUserAbortError;if(t)return this.retryRequest(n,t);if("AbortError"===l.name)throw new APIConnectionTimeoutError;throw new APIConnectionError({cause:l})}const c=createResponseHeaders(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return debug(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,i,c),this.retryRequest(n,t,c)}const e=await l.text().catch(e=>castToError(e).message),s=safeJSON(e),r=s?void 0:e;debug(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,c,r);throw this.makeStatusError(l.status,s,r,c)}return{response:l,options:n,controller:o}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new PagePromise(this,n,e)}buildURL(e,t){const n=isAbsoluteURL(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return isEmptyObj(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new OpenAIError(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:r,...i}=t||{};r&&r.addEventListener("abort",()=>s.abort());const a=setTimeout(()=>s.abort(),n),o={signal:s.signal,...i};return o.method&&(o.method=o.method.toUpperCase()),this.fetch.call(void 0,e,o).finally(()=>{clearTimeout(a)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const i=n?.["retry-after"];if(i&&!s){const e=parseFloat(i);s=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await sleep(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${VERSION}`}}class AbstractPage{constructor(e,t,n,s){_AbstractPage_client.set(this,void 0),__classPrivateFieldSet$4(this,_AbstractPage_client,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await __classPrivateFieldGet$5(this,_AbstractPage_client,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(_AbstractPage_client=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class PagePromise extends APIPromise{constructor(e,t,n){super(t,async t=>new n(e,t.response,await defaultParseResponse(t),t.options))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const createResponseHeaders=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),requestOptionsKeys={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},isRequestOptions=e=>"object"==typeof e&&null!==e&&!isEmptyObj(e)&&Object.keys(e).every(e=>hasOwn(requestOptionsKeys,e)),getPlatformProperties=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(Deno.build.os),"X-Stainless-Arch":normalizeArch(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":normalizePlatform(process.platform),"X-Stainless-Arch":normalizeArch(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=getBrowserInfo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function getBrowserInfo(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}const normalizeArch=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",normalizePlatform=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let _platformHeaders;const getPlatformHeaders=()=>_platformHeaders??(_platformHeaders=getPlatformProperties()),safeJSON=e=>{try{return JSON.parse(e)}catch(t){return}},startsWithSchemeRegexp=/^[a-z][a-z0-9+.-]*:/i,isAbsoluteURL=e=>startsWithSchemeRegexp.test(e),sleep=e=>new Promise(t=>setTimeout(t,e)),validatePositiveInteger=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new OpenAIError(`${e} must be an integer`);if(t<0)throw new OpenAIError(`${e} must be a positive integer`);return t},castToError=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},readEnv=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function isEmptyObj(e){if(!e)return!0;for(const t in e)return!1;return!0}function hasOwn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function applyHeadersMut(e,t){for(const n in t){if(!hasOwn(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}const SENSITIVE_HEADERS=new Set(["authorization","api-key"]);function debug(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const n=t.map(e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const n in e.headers)SENSITIVE_HEADERS.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)SENSITIVE_HEADERS.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e});console.log(`OpenAI:DEBUG:${e}`,...n)}}const uuid4=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),isRunningInBrowser=()=>"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator,isHeadersProtocol=e=>"function"==typeof e?.get,getHeader=(e,t)=>{const n=t.toLowerCase();if(isHeadersProtocol(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,(e,t,n)=>t+n.toUpperCase());for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r},toFloat32Array=e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++)s[e]=t.charCodeAt(e);return Array.from(new Float32Array(s.buffer))}};function isObj(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Page extends AbstractPage{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class CursorPage extends AbstractPage{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class APIResource{constructor(e){this._client=e}}let Messages$1=class extends APIResource{list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,ChatCompletionStoreMessagesPage,{query:t,...n})}},Completions$2=class extends APIResource{constructor(){super(...arguments),this.messages=new Messages$1(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/chat/completions",ChatCompletionsPage,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class ChatCompletionsPage extends CursorPage{}class ChatCompletionStoreMessagesPage extends CursorPage{}Completions$2.ChatCompletionsPage=ChatCompletionsPage,Completions$2.Messages=Messages$1;let Chat$1=class extends APIResource{constructor(){super(...arguments),this.completions=new Completions$2(this._client)}};Chat$1.Completions=Completions$2,Chat$1.ChatCompletionsPage=ChatCompletionsPage;class Speech extends APIResource{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Transcriptions extends APIResource{create(e,t){return this._client.post("/audio/transcriptions",multipartFormRequestOptions({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Translations extends APIResource{create(e,t){return this._client.post("/audio/translations",multipartFormRequestOptions({body:e,...t,__metadata:{model:e.model}}))}}class Audio extends APIResource{constructor(){super(...arguments),this.transcriptions=new Transcriptions(this._client),this.translations=new Translations(this._client),this.speech=new Speech(this._client)}}Audio.Transcriptions=Transcriptions,Audio.Translations=Translations,Audio.Speech=Speech;class Batches extends APIResource{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/batches",BatchesPage,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class BatchesPage extends CursorPage{}Batches.BatchesPage=BatchesPage;var __classPrivateFieldSet$3=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},__classPrivateFieldGet$4=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_EventStream_instances,_EventStream_connectedPromise,_EventStream_resolveConnectedPromise,_EventStream_rejectConnectedPromise,_EventStream_endPromise,_EventStream_resolveEndPromise,_EventStream_rejectEndPromise,_EventStream_listeners,_EventStream_ended,_EventStream_errored,_EventStream_aborted,_EventStream_catchingPromiseCreated,_EventStream_handleError;class EventStream{constructor(){_EventStream_instances.add(this),this.controller=new AbortController,_EventStream_connectedPromise.set(this,void 0),_EventStream_resolveConnectedPromise.set(this,()=>{}),_EventStream_rejectConnectedPromise.set(this,()=>{}),_EventStream_endPromise.set(this,void 0),_EventStream_resolveEndPromise.set(this,()=>{}),_EventStream_rejectEndPromise.set(this,()=>{}),_EventStream_listeners.set(this,{}),_EventStream_ended.set(this,!1),_EventStream_errored.set(this,!1),_EventStream_aborted.set(this,!1),_EventStream_catchingPromiseCreated.set(this,!1),__classPrivateFieldSet$3(this,_EventStream_connectedPromise,new Promise((e,t)=>{__classPrivateFieldSet$3(this,_EventStream_resolveConnectedPromise,e,"f"),__classPrivateFieldSet$3(this,_EventStream_rejectConnectedPromise,t,"f")}),"f"),__classPrivateFieldSet$3(this,_EventStream_endPromise,new Promise((e,t)=>{__classPrivateFieldSet$3(this,_EventStream_resolveEndPromise,e,"f"),__classPrivateFieldSet$3(this,_EventStream_rejectEndPromise,t,"f")}),"f"),__classPrivateFieldGet$4(this,_EventStream_connectedPromise,"f").catch(()=>{}),__classPrivateFieldGet$4(this,_EventStream_endPromise,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},__classPrivateFieldGet$4(this,_EventStream_instances,"m",_EventStream_handleError).bind(this))},0)}_connected(){this.ended||(__classPrivateFieldGet$4(this,_EventStream_resolveConnectedPromise,"f").call(this),this._emit("connect"))}get ended(){return __classPrivateFieldGet$4(this,_EventStream_ended,"f")}get errored(){return __classPrivateFieldGet$4(this,_EventStream_errored,"f")}get aborted(){return __classPrivateFieldGet$4(this,_EventStream_aborted,"f")}abort(){this.controller.abort()}on(e,t){return(__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e]||(__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e];if(!n)return this;const s=n.findIndex(e=>e.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e]||(__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{__classPrivateFieldSet$3(this,_EventStream_catchingPromiseCreated,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)})}async done(){__classPrivateFieldSet$3(this,_EventStream_catchingPromiseCreated,!0,"f"),await __classPrivateFieldGet$4(this,_EventStream_endPromise,"f")}_emit(e,...t){if(__classPrivateFieldGet$4(this,_EventStream_ended,"f"))return;"end"===e&&(__classPrivateFieldSet$3(this,_EventStream_ended,!0,"f"),__classPrivateFieldGet$4(this,_EventStream_resolveEndPromise,"f").call(this));const n=__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e];if(n&&(__classPrivateFieldGet$4(this,_EventStream_listeners,"f")[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),"abort"===e){const e=t[0];return __classPrivateFieldGet$4(this,_EventStream_catchingPromiseCreated,"f")||n?.length||Promise.reject(e),__classPrivateFieldGet$4(this,_EventStream_rejectConnectedPromise,"f").call(this,e),__classPrivateFieldGet$4(this,_EventStream_rejectEndPromise,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];__classPrivateFieldGet$4(this,_EventStream_catchingPromiseCreated,"f")||n?.length||Promise.reject(e),__classPrivateFieldGet$4(this,_EventStream_rejectConnectedPromise,"f").call(this,e),__classPrivateFieldGet$4(this,_EventStream_rejectEndPromise,"f").call(this,e),this._emit("end")}}_emitFinal(){}}_EventStream_connectedPromise=new WeakMap,_EventStream_resolveConnectedPromise=new WeakMap,_EventStream_rejectConnectedPromise=new WeakMap,_EventStream_endPromise=new WeakMap,_EventStream_resolveEndPromise=new WeakMap,_EventStream_rejectEndPromise=new WeakMap,_EventStream_listeners=new WeakMap,_EventStream_ended=new WeakMap,_EventStream_errored=new WeakMap,_EventStream_aborted=new WeakMap,_EventStream_catchingPromiseCreated=new WeakMap,_EventStream_instances=new WeakSet,_EventStream_handleError=function(e){if(__classPrivateFieldSet$3(this,_EventStream_errored,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new APIUserAbortError),e instanceof APIUserAbortError)return __classPrivateFieldSet$3(this,_EventStream_aborted,!0,"f"),this._emit("abort",e);if(e instanceof OpenAIError)return this._emit("error",e);if(e instanceof Error){const t=new OpenAIError(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new OpenAIError(String(e)))};var __classPrivateFieldGet$3=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},__classPrivateFieldSet$2=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},_AssistantStream_instances,_AssistantStream_events,_AssistantStream_runStepSnapshots,_AssistantStream_messageSnapshots,_AssistantStream_messageSnapshot,_AssistantStream_finalRun,_AssistantStream_currentContentIndex,_AssistantStream_currentContent,_AssistantStream_currentToolCallIndex,_AssistantStream_currentToolCall,_AssistantStream_currentEvent,_AssistantStream_currentRunSnapshot,_AssistantStream_currentRunStepSnapshot,_AssistantStream_addEvent,_AssistantStream_endRequest,_AssistantStream_handleMessage,_AssistantStream_handleRunStep,_AssistantStream_handleEvent,_AssistantStream_accumulateRunStep,_AssistantStream_accumulateMessage,_AssistantStream_accumulateContent,_AssistantStream_handleRun;class AssistantStream extends EventStream{constructor(){super(...arguments),_AssistantStream_instances.add(this),_AssistantStream_events.set(this,[]),_AssistantStream_runStepSnapshots.set(this,{}),_AssistantStream_messageSnapshots.set(this,{}),_AssistantStream_messageSnapshot.set(this,void 0),_AssistantStream_finalRun.set(this,void 0),_AssistantStream_currentContentIndex.set(this,void 0),_AssistantStream_currentContent.set(this,void 0),_AssistantStream_currentToolCallIndex.set(this,void 0),_AssistantStream_currentToolCall.set(this,void 0),_AssistantStream_currentEvent.set(this,void 0),_AssistantStream_currentRunSnapshot.set(this,void 0),_AssistantStream_currentRunStepSnapshot.set(this,void 0)}[(_AssistantStream_events=new WeakMap,_AssistantStream_runStepSnapshots=new WeakMap,_AssistantStream_messageSnapshots=new WeakMap,_AssistantStream_messageSnapshot=new WeakMap,_AssistantStream_finalRun=new WeakMap,_AssistantStream_currentContentIndex=new WeakMap,_AssistantStream_currentContent=new WeakMap,_AssistantStream_currentToolCallIndex=new WeakMap,_AssistantStream_currentToolCall=new WeakMap,_AssistantStream_currentEvent=new WeakMap,_AssistantStream_currentRunSnapshot=new WeakMap,_AssistantStream_currentRunStepSnapshot=new WeakMap,_AssistantStream_instances=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new AssistantStream;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Stream.fromReadableStream(e,this.controller);for await(const r of s)__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,r);if(s.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const i=new AssistantStream;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},o=await e.submitToolOutputs(t,n,a,{...r,signal:this.controller.signal});this._connected();for await(const l of o)__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,l);if(o.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static createThreadAssistantStream(e,t,n){const s=new AssistantStream;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const r=new AssistantStream;return r._run(()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}currentEvent(){return __classPrivateFieldGet$3(this,_AssistantStream_currentEvent,"f")}currentRun(){return __classPrivateFieldGet$3(this,_AssistantStream_currentRunSnapshot,"f")}currentMessageSnapshot(){return __classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f")}currentRunStepSnapshot(){return __classPrivateFieldGet$3(this,_AssistantStream_currentRunStepSnapshot,"f")}async finalRunSteps(){return await this.done(),Object.values(__classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f"))}async finalMessages(){return await this.done(),Object.values(__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshots,"f"))}async finalRun(){if(await this.done(),!__classPrivateFieldGet$3(this,_AssistantStream_finalRun,"f"))throw Error("Final run was not received.");return __classPrivateFieldGet$3(this,_AssistantStream_finalRun,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const a of i)__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,a);if(i.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},a=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const o of a)__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_addEvent).call(this,o);if(a.controller.signal?.aborted)throw new APIUserAbortError;return this._addRun(__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_endRequest).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!isObj(t)||!isObj(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every(e=>"string"==typeof e||"number"==typeof e)){t.push(...s);continue}for(const e of s){if(!isObj(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}_AssistantStream_addEvent=function(e){if(!this.ended)switch(__classPrivateFieldSet$2(this,_AssistantStream_currentEvent,e,"f"),__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_handleEvent).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_handleRun).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_handleRunStep).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_handleMessage).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},_AssistantStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");if(!__classPrivateFieldGet$3(this,_AssistantStream_finalRun,"f"))throw Error("Final run has not been received");return __classPrivateFieldGet$3(this,_AssistantStream_finalRun,"f")},_AssistantStream_handleMessage=function(e){const[t,n]=__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_accumulateMessage).call(this,e,__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f"));__classPrivateFieldSet$2(this,_AssistantStream_messageSnapshot,t,"f"),__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshots,"f")[t.id]=t;for(const s of n){const e=t.content[s.index];"text"==e?.type&&this._emit("textCreated",e.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=__classPrivateFieldGet$3(this,_AssistantStream_currentContentIndex,"f")){if(__classPrivateFieldGet$3(this,_AssistantStream_currentContent,"f"))switch(__classPrivateFieldGet$3(this,_AssistantStream_currentContent,"f").type){case"text":this._emit("textDone",__classPrivateFieldGet$3(this,_AssistantStream_currentContent,"f").text,__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f"));break;case"image_file":this._emit("imageFileDone",__classPrivateFieldGet$3(this,_AssistantStream_currentContent,"f").image_file,__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f"))}__classPrivateFieldSet$2(this,_AssistantStream_currentContentIndex,n.index,"f")}__classPrivateFieldSet$2(this,_AssistantStream_currentContent,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==__classPrivateFieldGet$3(this,_AssistantStream_currentContentIndex,"f")){const t=e.data.content[__classPrivateFieldGet$3(this,_AssistantStream_currentContentIndex,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f"));break;case"text":this._emit("textDone",t.text,__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f"))}}__classPrivateFieldGet$3(this,_AssistantStream_messageSnapshot,"f")&&this._emit("messageDone",e.data),__classPrivateFieldSet$2(this,_AssistantStream_messageSnapshot,void 0,"f")}},_AssistantStream_handleRunStep=function(e){const t=__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_accumulateRunStep).call(this,e);switch(__classPrivateFieldSet$2(this,_AssistantStream_currentRunStepSnapshot,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==__classPrivateFieldGet$3(this,_AssistantStream_currentToolCallIndex,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")&&this._emit("toolCallDone",__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet$2(this,_AssistantStream_currentToolCallIndex,e.index,"f"),__classPrivateFieldSet$2(this,_AssistantStream_currentToolCall,t.step_details.tool_calls[e.index],"f"),__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")&&this._emit("toolCallCreated",__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":__classPrivateFieldSet$2(this,_AssistantStream_currentRunStepSnapshot,void 0,"f");"tool_calls"==e.data.step_details.type&&__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")&&(this._emit("toolCallDone",__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet$2(this,_AssistantStream_currentToolCall,void 0,"f")),this._emit("runStepDone",e.data,t)}},_AssistantStream_handleEvent=function(e){__classPrivateFieldGet$3(this,_AssistantStream_events,"f").push(e),this._emit("event",e)},_AssistantStream_accumulateRunStep=function(e){switch(e.event){case"thread.run.step.created":return __classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=__classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=AssistantStream.accumulateDelta(t,n.delta);__classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id]=s}return __classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":__classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id]=e.data}if(__classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id])return __classPrivateFieldGet$3(this,_AssistantStream_runStepSnapshots,"f")[e.data.id];throw new Error("No snapshot available")},_AssistantStream_accumulateMessage=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=__classPrivateFieldGet$3(this,_AssistantStream_instances,"m",_AssistantStream_accumulateContent).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_AssistantStream_accumulateContent=function(e,t){return AssistantStream.accumulateDelta(t,e)},_AssistantStream_handleRun=function(e){switch(__classPrivateFieldSet$2(this,_AssistantStream_currentRunSnapshot,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":__classPrivateFieldSet$2(this,_AssistantStream_finalRun,e.data,"f"),__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")&&(this._emit("toolCallDone",__classPrivateFieldGet$3(this,_AssistantStream_currentToolCall,"f")),__classPrivateFieldSet$2(this,_AssistantStream_currentToolCall,void 0,"f"))}};class Assistants extends APIResource{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/assistants",AssistantsPage,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class AssistantsPage extends CursorPage{}function isRunnableFunctionWithParse(e){return"function"==typeof e.parse}Assistants.AssistantsPage=AssistantsPage;const isAssistantMessage=e=>"assistant"===e?.role,isFunctionMessage=e=>"function"===e?.role,isToolMessage=e=>"tool"===e?.role;function isAutoParsableResponseFormat(e){return"auto-parseable-response-format"===e?.$brand}function isAutoParsableTool$1(e){return"auto-parseable-tool"===e?.$brand}function maybeParseChatCompletion(e,t){return t&&hasAutoParseableInput$1(t)?parseChatCompletion(e,t):{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}}function parseChatCompletion(e,t){const n=e.choices.map(e=>{if("length"===e.finish_reason)throw new LengthFinishReasonError;if("content_filter"===e.finish_reason)throw new ContentFilterFinishReasonError;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>parseToolCall$1(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?parseResponseFormat(t,e.message.content):null}}});return{...e,choices:n}}function parseResponseFormat(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function parseToolCall$1(e,t){const n=e.tools?.find(e=>e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:isAutoParsableTool$1(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function shouldParseToolCall(e,t){if(!e)return!1;const n=e.tools?.find(e=>e.function?.name===t.function.name);return isAutoParsableTool$1(n)||n?.function.strict||!1}function hasAutoParseableInput$1(e){return!!isAutoParsableResponseFormat(e.response_format)||(e.tools?.some(e=>isAutoParsableTool$1(e)||"function"===e.type&&!0===e.function.strict)??!1)}function validateInputTools(e){for(const t of e??[]){if("function"!==t.type)throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new OpenAIError(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var __classPrivateFieldGet$2=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_AbstractChatCompletionRunner_instances,_AbstractChatCompletionRunner_getFinalContent,_AbstractChatCompletionRunner_getFinalMessage,_AbstractChatCompletionRunner_getFinalFunctionCall,_AbstractChatCompletionRunner_getFinalFunctionCallResult,_AbstractChatCompletionRunner_calculateTotalUsage,_AbstractChatCompletionRunner_validateParams,_AbstractChatCompletionRunner_stringifyFunctionCallResult;const DEFAULT_MAX_CHAT_COMPLETIONS=10;class AbstractChatCompletionRunner extends EventStream{constructor(){super(...arguments),_AbstractChatCompletionRunner_instances.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(isFunctionMessage(e)||isToolMessage(e))&&e.content)this._emit("functionCallResult",e.content);else if(isAssistantMessage(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(isAssistantMessage(e)&&e.tool_calls)for(const n of e.tool_calls)"function"===n.type&&this._emit("functionCall",n.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new OpenAIError("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this)}async finalMessage(){return await this.done(),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this)}async finalFunctionCall(){return await this.done(),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this)}async finalFunctionCallResult(){return await this.done(),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this)}async totalUsage(){return await this.done(),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this);t&&this._emit("finalMessage",t);const n=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalContent).call(this);n&&this._emit("finalContent",n);const s=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCall).call(this);s&&this._emit("finalFunctionCall",s);const r=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some(e=>e.usage)&&this._emit("totalUsage",__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_calculateTotalUsage).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_validateParams).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(parseChatCompletion(r,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:i,...a}=t,o="string"!=typeof r&&r?.name,{maxChatCompletions:l=DEFAULT_MAX_CHAT_COMPLETIONS}=n||{},c={};for(const f of t.functions)c[f.name||f.function.name]=f;const u=t.functions.map(e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description}));for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<l;++f){const t=await this._createChatCompletion(e,{...a,function_call:r,functions:u,messages:[...this.messages]},n),i=t.choices[0]?.message;if(!i)throw new OpenAIError("missing message in ChatCompletion response");if(!i.function_call)return;const{name:l,arguments:f}=i.function_call,h=c[l];if(!h){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map(e=>JSON.stringify(e.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:l,content:e});continue}if(o&&o!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:s,name:l,content:e});continue}let p;try{p=isRunnableFunctionWithParse(h)?await h.parse(f):f}catch(d){this._addMessage({role:s,name:l,content:d instanceof Error?d.message:String(d)});continue}const y=await h.function(p,this),g=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,y);if(this._addMessage({role:s,name:l,content:g}),o)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:i,...a}=t,o="string"!=typeof r&&r?.function?.name,{maxChatCompletions:l=DEFAULT_MAX_CHAT_COMPLETIONS}=n||{},c=t.tools.map(e=>{if(isAutoParsableTool$1(e)){if(!e.$callback)throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(const h of c)"function"===h.type&&(u[h.function.name||h.function.function.name]=h.function);const d="tools"in t?c.map(e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(const h of t.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:d,messages:[...this.messages]},n),i=t.choices[0]?.message;if(!i)throw new OpenAIError("missing message in ChatCompletion response");if(!i.tool_calls?.length)return;for(const e of i.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:n,arguments:r}=e.function,i=u[n];if(!i){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(o&&o!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(o)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let a;try{a=isRunnableFunctionWithParse(i)?await i.parse(r):r}catch(f){const e=f instanceof Error?f.message:String(f);this._addMessage({role:s,tool_call_id:t,content:e});continue}const l=await i.function(a,this),c=__classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),o)return}}}}_AbstractChatCompletionRunner_instances=new WeakSet,_AbstractChatCompletionRunner_getFinalContent=function(){return __classPrivateFieldGet$2(this,_AbstractChatCompletionRunner_instances,"m",_AbstractChatCompletionRunner_getFinalMessage).call(this).content??null},_AbstractChatCompletionRunner_getFinalMessage=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(isAssistantMessage(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},_AbstractChatCompletionRunner_getFinalFunctionCall=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(isAssistantMessage(t)&&t?.function_call)return t.function_call;if(isAssistantMessage(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},_AbstractChatCompletionRunner_getFinalFunctionCallResult=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(isFunctionMessage(t)&&null!=t.content)return t.content;if(isToolMessage(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some(e=>"assistant"===e.role&&e.tool_calls?.some(e=>"function"===e.type&&e.id===t.tool_call_id)))return t.content}},_AbstractChatCompletionRunner_calculateTotalUsage=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},_AbstractChatCompletionRunner_validateParams=function(e){if(null!=e.n&&e.n>1)throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_AbstractChatCompletionRunner_stringifyFunctionCallResult=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class ChatCompletionRunner extends AbstractChatCompletionRunner{static runFunctions(e,t,n){const s=new ChatCompletionRunner,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new ChatCompletionRunner,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}_addMessage(e,t=!0){super._addMessage(e,t),isAssistantMessage(e)&&e.content&&this._emit("content",e.content)}}const STR=1,NUM=2,ARR=4,OBJ=8,NULL=16,BOOL=32,NAN=64,INFINITY=128,MINUS_INFINITY=256,INF=INFINITY|MINUS_INFINITY,SPECIAL=NULL|BOOL|INF|NAN,ATOM=STR|NUM|SPECIAL,COLLECTION=ARR|OBJ,ALL=ATOM|COLLECTION,Allow={STR:STR,NUM:NUM,ARR:ARR,OBJ:OBJ,NULL:NULL,BOOL:BOOL,NAN:NAN,INFINITY:INFINITY,MINUS_INFINITY:MINUS_INFINITY,INF:INF,SPECIAL:SPECIAL,ATOM:ATOM,COLLECTION:COLLECTION,ALL:ALL};class PartialJSON extends Error{}class MalformedJSON extends Error{}function parseJSON(e,t=Allow.ALL){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return _parseJSON(e.trim(),t)}const _parseJSON=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new PartialJSON(`${e} at position ${s}`)},i=e=>{throw new MalformedJSON(`${e} at position ${s}`)},a=()=>(d(),s>=n&&r("Unexpected end of input"),'"'===e[s]?o():"{"===e[s]?l():"["===e[s]?c():"null"===e.substring(s,s+4)||Allow.NULL&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||Allow.BOOL&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||Allow.BOOL&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||Allow.INFINITY&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||Allow.MINUS_INFINITY&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||Allow.NAN&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):u()),o=()=>{const a=s;let o=!1;for(s++;s<n&&('"'!==e[s]||o&&"\\"===e[s-1]);)o="\\"===e[s]&&!o,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(a,++s-Number(o)))}catch(l){i(String(l))}else if(Allow.STR&t)try{return JSON.parse(e.substring(a,s-Number(o))+'"')}catch(l){return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,d();const i={};try{for(;"}"!==e[s];){if(d(),s>=n&&Allow.OBJ&t)return i;const r=o();d(),s++;try{const e=a();Object.defineProperty(i,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(l){if(Allow.OBJ&t)return i;throw l}d(),","===e[s]&&s++}}catch(l){if(Allow.OBJ&t)return i;r("Expected '}' at end of object")}return s++,i},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(a()),d(),","===e[s]&&s++}catch(i){if(Allow.ARR&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&Allow.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(o){if(Allow.NUM&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(l){}i(String(o))}}const a=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||Allow.NUM&t||r("Unterminated number literal");try{return JSON.parse(e.substring(a,s))}catch(o){"-"===e.substring(a,s)&&Allow.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(l){i(String(l))}}},d=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return a()},partialParse=e=>parseJSON(e,Allow.ALL^Allow.NUM);var __classPrivateFieldSet$1=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},__classPrivateFieldGet$1=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_ChatCompletionStream_instances,_ChatCompletionStream_params,_ChatCompletionStream_choiceEventStates,_ChatCompletionStream_currentChatCompletionSnapshot,_ChatCompletionStream_beginRequest,_ChatCompletionStream_getChoiceEventState,_ChatCompletionStream_addChunk,_ChatCompletionStream_emitToolCallDoneEvent,_ChatCompletionStream_emitContentDoneEvents,_ChatCompletionStream_endRequest,_ChatCompletionStream_getAutoParseableResponseFormat,_ChatCompletionStream_accumulateChatCompletion;class ChatCompletionStream extends AbstractChatCompletionRunner{constructor(e){super(),_ChatCompletionStream_instances.add(this),_ChatCompletionStream_params.set(this,void 0),_ChatCompletionStream_choiceEventStates.set(this,void 0),_ChatCompletionStream_currentChatCompletionSnapshot.set(this,void 0),__classPrivateFieldSet$1(this,_ChatCompletionStream_params,e,"f"),__classPrivateFieldSet$1(this,_ChatCompletionStream_choiceEventStates,[],"f")}get currentChatCompletionSnapshot(){return __classPrivateFieldGet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f")}static fromReadableStream(e){const t=new ChatCompletionStream(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new ChatCompletionStream(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const i of r)__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,i);if(r.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_beginRequest).call(this),this._connected();const s=Stream.fromReadableStream(e,this.controller);let r;for await(const i of s)r&&r!==i.id&&this._addChatCompletion(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this)),__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_addChunk).call(this,i),r=i.id;if(s.controller.signal?.aborted)throw new APIUserAbortError;return this._addChatCompletion(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_endRequest).call(this))}[(_ChatCompletionStream_params=new WeakMap,_ChatCompletionStream_choiceEventStates=new WeakMap,_ChatCompletionStream_currentChatCompletionSnapshot=new WeakMap,_ChatCompletionStream_instances=new WeakSet,_ChatCompletionStream_beginRequest=function(){this.ended||__classPrivateFieldSet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f")},_ChatCompletionStream_getChoiceEventState=function(e){let t=__classPrivateFieldGet$1(this,_ChatCompletionStream_choiceEventStates,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},__classPrivateFieldGet$1(this,_ChatCompletionStream_choiceEventStates,"f")[e.index]=t,t)},_ChatCompletionStream_addChunk=function(e){if(this.ended)return;const t=__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_accumulateChatCompletion).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,e);e.finish_reason&&(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,e),null!=s.current_tool_call_index&&__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitContentDoneEvents).call(this,e),null!=s.current_tool_call_index&&__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_emitToolCallDoneEvent).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type?this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}):assertNever(n?.type))}}},_ChatCompletionStream_emitToolCallDoneEvent=function(e,t){if(__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f")?.tools?.find(e=>"function"===e.type&&e.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:isAutoParsableTool$1(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else assertNever(n.type)},_ChatCompletionStream_emitContentDoneEvents=function(e){const t=__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getChoiceEventState).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},_ChatCompletionStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");const e=__classPrivateFieldGet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f");if(!e)throw new OpenAIError("request ended without sending any chunks");return __classPrivateFieldSet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,void 0,"f"),__classPrivateFieldSet$1(this,_ChatCompletionStream_choiceEventStates,[],"f"),finalizeChatCompletion(e,__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f"))},_ChatCompletionStream_getAutoParseableResponseFormat=function(){const e=__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f")?.response_format;return isAutoParsableResponseFormat(e)?e:null},_ChatCompletionStream_accumulateChatCompletion=function(e){var t,n,s,r;let i=__classPrivateFieldGet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,"f");const{choices:a,...o}=e;i?Object.assign(i,o):i=__classPrivateFieldSet$1(this,_ChatCompletionStream_currentChatCompletionSnapshot,{...o,choices:[]},"f");for(const{delta:l,finish_reason:c,index:u,logprobs:d=null,...f}of e.choices){let e=i.choices[u];if(e||(e=i.choices[u]={finish_reason:c,index:u,message:{},logprobs:d,...f}),d)if(e.logprobs){const{content:s,refusal:r,...i}=d;Object.assign(e.logprobs,i),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},d);if(c&&(e.finish_reason=c,__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f")&&hasAutoParseableInput$1(__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f")))){if("length"===c)throw new LengthFinishReasonError;if("content_filter"===c)throw new ContentFilterFinishReasonError}if(Object.assign(e,f),!l)continue;const{content:a,refusal:o,function_call:h,role:p,tool_calls:y,...g}=l;if(Object.assign(e.message,g),o&&(e.message.refusal=(e.message.refusal||"")+o),p&&(e.message.role=p),h&&(e.message.function_call?(h.name&&(e.message.function_call.name=h.name),h.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=h.arguments)):e.message.function_call=h),a&&(e.message.content=(e.message.content||"")+a,!e.message.refusal&&__classPrivateFieldGet$1(this,_ChatCompletionStream_instances,"m",_ChatCompletionStream_getAutoParseableResponseFormat).call(this)&&(e.message.parsed=partialParse(e.message.content))),y){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:i,...a}of y){const o=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(o,a),n&&(o.id=n),s&&(o.type=s),i&&(o.function??(o.function={name:i.name??"",arguments:""})),i?.name&&(o.function.name=i.name),i?.arguments&&(o.function.arguments+=i.arguments,shouldParseToolCall(__classPrivateFieldGet$1(this,_ChatCompletionStream_params,"f"),o)&&(o.function.parsed_arguments=partialParse(o.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function finalizeChatCompletion(e,t){const{id:n,choices:s,created:r,model:i,system_fingerprint:a,...o}=e;return maybeParseChatCompletion({...o,id:n,choices:s.map(({message:t,finish_reason:n,index:s,logprobs:r,...i})=>{if(!n)throw new OpenAIError(`missing finish_reason for choice ${s}`);const{content:a=null,function_call:o,tool_calls:l,...c}=t,u=t.role;if(!u)throw new OpenAIError(`missing role for choice ${s}`);if(o){const{arguments:e,name:l}=o;if(null==e)throw new OpenAIError(`missing function_call.arguments for choice ${s}`);if(!l)throw new OpenAIError(`missing function_call.name for choice ${s}`);return{...i,message:{content:a,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return l?{...i,index:s,finish_reason:n,logprobs:r,message:{...c,role:u,content:a,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{const{function:r,type:i,id:a,...o}=t,{arguments:l,name:c,...u}=r||{};if(null==a)throw new OpenAIError(`missing choices[${s}].tool_calls[${n}].id\n${str(e)}`);if(null==i)throw new OpenAIError(`missing choices[${s}].tool_calls[${n}].type\n${str(e)}`);if(null==c)throw new OpenAIError(`missing choices[${s}].tool_calls[${n}].function.name\n${str(e)}`);if(null==l)throw new OpenAIError(`missing choices[${s}].tool_calls[${n}].function.arguments\n${str(e)}`);return{...o,id:a,type:i,function:{...u,name:c,arguments:l}}})}}:{...i,message:{...c,content:a,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}},t)}function str(e){return JSON.stringify(e)}function assertNever(e){}class ChatCompletionStreamingRunner extends ChatCompletionStream{static fromReadableStream(e){const t=new ChatCompletionStreamingRunner(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new ChatCompletionStreamingRunner(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,r)),s}static runTools(e,t,n){const s=new ChatCompletionStreamingRunner(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,r)),s}}let Completions$1=class extends APIResource{parse(e,t){return validateInputTools(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>parseChatCompletion(t,e))}runFunctions(e,t){return e.stream?ChatCompletionStreamingRunner.runFunctions(this._client,e,t):ChatCompletionRunner.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?ChatCompletionStreamingRunner.runTools(this._client,e,t):ChatCompletionRunner.runTools(this._client,e,t)}stream(e,t){return ChatCompletionStream.createChatCompletion(this._client,e,t)}};class Chat extends APIResource{constructor(){super(...arguments),this.completions=new Completions$1(this._client)}}(Chat||(Chat={})).Completions=Completions$1;class Sessions extends APIResource{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class TranscriptionSessions extends APIResource{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Realtime extends APIResource{constructor(){super(...arguments),this.sessions=new Sessions(this._client),this.transcriptionSessions=new TranscriptionSessions(this._client)}}Realtime.Sessions=Sessions,Realtime.TranscriptionSessions=TranscriptionSessions;class Messages extends APIResource{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,MessagesPage,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class MessagesPage extends CursorPage{}Messages.MessagesPage=MessagesPage;class Steps extends APIResource{retrieve(e,t,n,s={},r){return isRequestOptions(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return isRequestOptions(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,RunStepsPage,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class RunStepsPage extends CursorPage{}Steps.RunStepsPage=RunStepsPage;let Runs$1=class extends APIResource{constructor(){super(...arguments),this.steps=new Steps(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,RunsPage,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return AssistantStream.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:i}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await sleep(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return AssistantStream.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return AssistantStream.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class RunsPage extends CursorPage{}Runs$1.RunsPage=RunsPage,Runs$1.Steps=Steps,Runs$1.RunStepsPage=RunStepsPage;class Threads extends APIResource{constructor(){super(...arguments),this.runs=new Runs$1(this._client),this.messages=new Messages(this._client)}create(e={},t){return isRequestOptions(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return AssistantStream.createThreadAssistantStream(e,this._client.beta.threads,t)}}Threads.Runs=Runs$1,Threads.RunsPage=RunsPage,Threads.Messages=Messages,Threads.MessagesPage=MessagesPage;class Beta extends APIResource{constructor(){super(...arguments),this.realtime=new Realtime(this._client),this.chat=new Chat(this._client),this.assistants=new Assistants(this._client),this.threads=new Threads(this._client)}}Beta.Realtime=Realtime,Beta.Assistants=Assistants,Beta.AssistantsPage=AssistantsPage,Beta.Threads=Threads;class Completions extends APIResource{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Content extends APIResource{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}}let Files$2=class extends APIResource{constructor(){super(...arguments),this.content=new Content(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,multipartFormRequestOptions({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,FileListResponsesPage,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}};class FileListResponsesPage extends CursorPage{}Files$2.FileListResponsesPage=FileListResponsesPage,Files$2.Content=Content;class Containers extends APIResource{constructor(){super(...arguments),this.files=new Files$2(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/containers",ContainerListResponsesPage,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class ContainerListResponsesPage extends CursorPage{}Containers.ContainerListResponsesPage=ContainerListResponsesPage,Containers.Files=Files$2,Containers.FileListResponsesPage=FileListResponsesPage;let Embeddings$1=class extends APIResource{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&debug("Request","User defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?r:(debug("response","Decoding base64 embeddings to float32 array"),r._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{const t=e.embedding;e.embedding=toFloat32Array(t)}),e)))}};class OutputItems extends APIResource{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return isRequestOptions(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,OutputItemListResponsesPage,{query:n,...s})}}class OutputItemListResponsesPage extends CursorPage{}OutputItems.OutputItemListResponsesPage=OutputItemListResponsesPage;class Runs extends APIResource{constructor(){super(...arguments),this.outputItems=new OutputItems(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,RunListResponsesPage,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class RunListResponsesPage extends CursorPage{}Runs.RunListResponsesPage=RunListResponsesPage,Runs.OutputItems=OutputItems,Runs.OutputItemListResponsesPage=OutputItemListResponsesPage;class Evals extends APIResource{constructor(){super(...arguments),this.runs=new Runs(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/evals",EvalListResponsesPage,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class EvalListResponsesPage extends CursorPage{}Evals.EvalListResponsesPage=EvalListResponsesPage,Evals.Runs=Runs,Evals.RunListResponsesPage=RunListResponsesPage;let Files$1=class extends APIResource{create(e,t){return this._client.post("/files",multipartFormRequestOptions({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/files",FileObjectsPage,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await sleep(t),i=await this.retrieve(e),Date.now()-r>n)throw new APIConnectionTimeoutError({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class FileObjectsPage extends CursorPage{}Files$1.FileObjectsPage=FileObjectsPage;class Methods extends APIResource{}let Graders$1=class extends APIResource{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Alpha extends APIResource{constructor(){super(...arguments),this.graders=new Graders$1(this._client)}}Alpha.Graders=Graders$1;class Permissions extends APIResource{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,PermissionCreateResponsesPage,{body:t,method:"post",...n})}retrieve(e,t={},n){return isRequestOptions(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class PermissionCreateResponsesPage extends Page{}Permissions.PermissionCreateResponsesPage=PermissionCreateResponsesPage;let Checkpoints$1=class extends APIResource{constructor(){super(...arguments),this.permissions=new Permissions(this._client)}};Checkpoints$1.Permissions=Permissions,Checkpoints$1.PermissionCreateResponsesPage=PermissionCreateResponsesPage;class Checkpoints extends APIResource{list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,FineTuningJobCheckpointsPage,{query:t,...n})}}class FineTuningJobCheckpointsPage extends CursorPage{}Checkpoints.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage;class Jobs extends APIResource{constructor(){super(...arguments),this.checkpoints=new Checkpoints(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",FineTuningJobsPage,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return isRequestOptions(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,FineTuningJobEventsPage,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class FineTuningJobsPage extends CursorPage{}class FineTuningJobEventsPage extends CursorPage{}Jobs.FineTuningJobsPage=FineTuningJobsPage,Jobs.FineTuningJobEventsPage=FineTuningJobEventsPage,Jobs.Checkpoints=Checkpoints,Jobs.FineTuningJobCheckpointsPage=FineTuningJobCheckpointsPage;class FineTuning extends APIResource{constructor(){super(...arguments),this.methods=new Methods(this._client),this.jobs=new Jobs(this._client),this.checkpoints=new Checkpoints$1(this._client),this.alpha=new Alpha(this._client)}}FineTuning.Methods=Methods,FineTuning.Jobs=Jobs,FineTuning.FineTuningJobsPage=FineTuningJobsPage,FineTuning.FineTuningJobEventsPage=FineTuningJobEventsPage,FineTuning.Checkpoints=Checkpoints$1,FineTuning.Alpha=Alpha;class GraderModels extends APIResource{}class Graders extends APIResource{constructor(){super(...arguments),this.graderModels=new GraderModels(this._client)}}Graders.GraderModels=GraderModels;class Images extends APIResource{createVariation(e,t){return this._client.post("/images/variations",multipartFormRequestOptions({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",multipartFormRequestOptions({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Models extends APIResource{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ModelsPage,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class ModelsPage extends Page{}Models.ModelsPage=ModelsPage;class Moderations extends APIResource{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function maybeParseResponse(e,t){return t&&hasAutoParseableInput(t)?parseResponse(e,t):{...e,output_parsed:null,output:e.output.map(e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}}function parseResponse(e,t){const n=e.output.map(e=>{if("function_call"===e.type)return{...e,parsed_arguments:parseToolCall(t,e)};if("message"===e.type){const n=e.content.map(e=>"output_text"===e.type?{...e,parsed:parseTextFormat(t,e.text)}:e);return{...e,content:n}}return e}),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||addOutputText(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function parseTextFormat(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function hasAutoParseableInput(e){return!!isAutoParsableResponseFormat(e.text?.format)}function isAutoParsableTool(e){return"auto-parseable-tool"===e?.$brand}function getInputToolByName(e,t){return e.find(e=>"function"===e.type&&e.name===t)}function parseToolCall(e,t){const n=getInputToolByName(e.tools??[],t.name);return{...t,...t,parsed_arguments:isAutoParsableTool(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function addOutputText(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class InputItems extends APIResource{list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,ResponseItemsPage,{query:t,...n})}}var __classPrivateFieldSet=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},__classPrivateFieldGet=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},_ResponseStream_instances,_ResponseStream_params,_ResponseStream_currentResponseSnapshot,_ResponseStream_finalResponse,_ResponseStream_beginRequest,_ResponseStream_addEvent,_ResponseStream_endRequest,_ResponseStream_accumulateResponse;class ResponseStream extends EventStream{constructor(e){super(),_ResponseStream_instances.add(this),_ResponseStream_params.set(this,void 0),_ResponseStream_currentResponseSnapshot.set(this,void 0),_ResponseStream_finalResponse.set(this,void 0),__classPrivateFieldSet(this,_ResponseStream_params,e,"f")}static createResponse(e,t,n){const s=new ResponseStream(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_beginRequest).call(this);let i=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const a of r)__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_addEvent).call(this,a,i);if(r.controller.signal?.aborted)throw new APIUserAbortError;return __classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_endRequest).call(this)}[(_ResponseStream_params=new WeakMap,_ResponseStream_currentResponseSnapshot=new WeakMap,_ResponseStream_finalResponse=new WeakMap,_ResponseStream_instances=new WeakSet,_ResponseStream_beginRequest=function(){this.ended||__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,void 0,"f")},_ResponseStream_addEvent=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},s=__classPrivateFieldGet(this,_ResponseStream_instances,"m",_ResponseStream_accumulateResponse).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=s.output[e.output_index];if(!t)throw new OpenAIError(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new OpenAIError(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new OpenAIError(`expected content to be 'output_text', got ${s.type}`);n("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=s.output[e.output_index];if(!t)throw new OpenAIError(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},_ResponseStream_endRequest=function(){if(this.ended)throw new OpenAIError("stream has ended, this shouldn't happen");const e=__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f");if(!e)throw new OpenAIError("request ended without sending any events");__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,void 0,"f");const t=finalizeResponse(e,__classPrivateFieldGet(this,_ResponseStream_params,"f"));return __classPrivateFieldSet(this,_ResponseStream_finalResponse,t,"f"),t},_ResponseStream_accumulateResponse=function(e){let t=__classPrivateFieldGet(this,_ResponseStream_currentResponseSnapshot,"f");if(!t){if("response.created"!==e.type)throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new OpenAIError(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new OpenAIError(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new OpenAIError(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new OpenAIError(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new OpenAIError(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":__classPrivateFieldSet(this,_ResponseStream_currentResponseSnapshot,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",n=>{const s=t.shift();s?s.resolve(n):e.push(n)}),this.on("end",()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0}),this.on("abort",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),this.on("error",e=>{n=!0;for(const n of t)n.reject(e);t.length=0}),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=__classPrivateFieldGet(this,_ResponseStream_finalResponse,"f");if(!e)throw new OpenAIError("stream ended without producing a ChatCompletion");return e}}function finalizeResponse(e,t){return maybeParseResponse(e,t)}class Responses extends APIResource{constructor(){super(...arguments),this.inputItems=new InputItems(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>("object"in e&&"response"===e.object&&addOutputText(e),e))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>parseResponse(t,e))}stream(e,t){return ResponseStream.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}}class ResponseItemsPage extends CursorPage{}Responses.InputItems=InputItems;class Parts extends APIResource{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,multipartFormRequestOptions({body:t,...n}))}}class Uploads extends APIResource{constructor(){super(...arguments),this.parts=new Parts(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}Uploads.Parts=Parts;const allSettledWithThrow=async e=>{const t=await Promise.allSettled(e),n=t.filter(e=>"rejected"===e.status);if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of t)"fulfilled"===r.status&&s.push(r.value);return s};class Files extends APIResource{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return isRequestOptions(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,VectorStoreFilesPage,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=r.data;switch(i.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await sleep(e);break;case"failed":case"completed":return i}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,FileContentResponsesPage,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class VectorStoreFilesPage extends CursorPage{}class FileContentResponsesPage extends Page{}Files.VectorStoreFilesPage=VectorStoreFilesPage,Files.FileContentResponsesPage=FileContentResponsesPage;class FileBatches extends APIResource{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return isRequestOptions(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,VectorStoreFilesPage,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=i.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await sleep(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=s?.maxConcurrency??5,i=Math.min(r,t.length),a=this._client,o=t.values(),l=[...n];const c=Array(i).fill(o).map(async function(e){for(let t of e){const e=await a.files.create({file:t,purpose:"assistants"},s);l.push(e.id)}});return await allSettledWithThrow(c),await this.createAndPoll(e,{file_ids:l})}}class VectorStores extends APIResource{constructor(){super(...arguments),this.files=new Files(this._client),this.fileBatches=new FileBatches(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return isRequestOptions(e)?this.list({},e):this._client.getAPIList("/vector_stores",VectorStoresPage,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,VectorStoreSearchResponsesPage,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class VectorStoresPage extends CursorPage{}class VectorStoreSearchResponsesPage extends Page{}var _a;VectorStores.VectorStoresPage=VectorStoresPage,VectorStores.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage,VectorStores.Files=Files,VectorStores.VectorStoreFilesPage=VectorStoreFilesPage,VectorStores.FileContentResponsesPage=FileContentResponsesPage,VectorStores.FileBatches=FileBatches;class OpenAI extends APIClient{constructor({baseURL:e=readEnv("OPENAI_BASE_URL"),apiKey:t=readEnv("OPENAI_API_KEY"),organization:n=readEnv("OPENAI_ORG_ID")??null,project:s=readEnv("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&isRunningInBrowser())throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Completions(this),this.chat=new Chat$1(this),this.embeddings=new Embeddings$1(this),this.files=new Files$1(this),this.images=new Images(this),this.audio=new Audio(this),this.moderations=new Moderations(this),this.models=new Models(this),this.fineTuning=new FineTuning(this),this.graders=new Graders(this),this.vectorStores=new VectorStores(this),this.beta=new Beta(this),this.batches=new Batches(this),this.uploads=new Uploads(this),this.responses=new Responses(this),this.evals=new Evals(this),this.containers=new Containers(this),this._options=i,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return stringify$1(e,{arrayFormat:"brackets"})}}_a=OpenAI,OpenAI.OpenAI=_a,OpenAI.DEFAULT_TIMEOUT=6e5,OpenAI.OpenAIError=OpenAIError,OpenAI.APIError=APIError,OpenAI.APIConnectionError=APIConnectionError,OpenAI.APIConnectionTimeoutError=APIConnectionTimeoutError,OpenAI.APIUserAbortError=APIUserAbortError,OpenAI.NotFoundError=NotFoundError,OpenAI.ConflictError=ConflictError,OpenAI.RateLimitError=RateLimitError,OpenAI.BadRequestError=BadRequestError,OpenAI.AuthenticationError=AuthenticationError,OpenAI.InternalServerError=InternalServerError,OpenAI.PermissionDeniedError=PermissionDeniedError,OpenAI.UnprocessableEntityError=UnprocessableEntityError,OpenAI.toFile=toFile,OpenAI.fileFromPath=fileFromPath,OpenAI.Completions=Completions,OpenAI.Chat=Chat$1,OpenAI.ChatCompletionsPage=ChatCompletionsPage,OpenAI.Embeddings=Embeddings$1,OpenAI.Files=Files$1,OpenAI.FileObjectsPage=FileObjectsPage,OpenAI.Images=Images,OpenAI.Audio=Audio,OpenAI.Moderations=Moderations,OpenAI.Models=Models,OpenAI.ModelsPage=ModelsPage,OpenAI.FineTuning=FineTuning,OpenAI.Graders=Graders,OpenAI.VectorStores=VectorStores,OpenAI.VectorStoresPage=VectorStoresPage,OpenAI.VectorStoreSearchResponsesPage=VectorStoreSearchResponsesPage,OpenAI.Beta=Beta,OpenAI.Batches=Batches,OpenAI.BatchesPage=BatchesPage,OpenAI.Uploads=Uploads,OpenAI.Responses=Responses,OpenAI.Evals=Evals,OpenAI.EvalListResponsesPage=EvalListResponsesPage,OpenAI.Containers=Containers,OpenAI.ContainerListResponsesPage=ContainerListResponsesPage;class LLMService{constructor(e,t={}){if(!e)throw new Error("OpenAI API key is required");this.openai=new OpenAI({apiKey:e}),this.model=t.model||"gpt-4o-mini",this.maxTokens=t.maxTokens||2e3,this.temperature=t.temperature||.7}async sendMessage(e,t,n={}){try{const s=await this.openai.chat.completions.create({model:n.model||this.model,messages:[{role:"system",content:e},{role:"user",content:t}],max_tokens:n.maxTokens||this.maxTokens,temperature:n.temperature??this.temperature});return s.choices[0]?.message?.content?.trim()||""}catch(s){throw new Error(`LLM request failed: ${s.message}`)}}async chat(e,t={}){try{const n=await this.openai.chat.completions.create({model:t.model||this.model,messages:e,max_tokens:t.maxTokens||this.maxTokens,temperature:t.temperature??this.temperature});return n.choices[0]?.message?.content?.trim()||""}catch(n){throw new Error(`LLM chat failed: ${n.message}`)}}async summarize(e,t={}){const n=`You are a helpful assistant that summarizes text concisely while preserving key information. Keep summaries clear and focused.${t.maxLength?` Keep the summary under ${t.maxLength} words.`:""}${t.style?` Style: ${t.style}.`:""}`;return this.sendMessage(n,e,{temperature:.5})}async analyze(e,t){const n=`You are an expert analyst. Analyze the following text from the perspective of "${t}". Provide a clear, structured analysis.`;return this.sendMessage(n,e,{temperature:.3})}async extractKeywords(e,t=10){const n=`Extract the ${t} most important keywords or key phrases from the text. Return ONLY a JSON array of strings, nothing else. Example: ["keyword1", "keyword2"]`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split(",").map(e=>e.trim().replace(/["\[\]]/g,""))}}async categorize(e,t){const n=`Categorize the following text into one of these categories: ${t.join(", ")}.\nReturn ONLY a JSON object with: {"category": "chosen_category", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`,s=await this.sendMessage(n,e,{temperature:.2});try{return JSON.parse(s)}catch{const e=s.match(/\{[\s\S]*\}/);return e?JSON.parse(e[0]):{category:t[0],confidence:.5,reasoning:s}}}async translate(e,t){const n=`Translate the following text to ${t}. Return ONLY the translation, nothing else.`;return this.sendMessage(n,e,{temperature:.3})}async generateQuestions(e,t=5){const n=`Generate ${t} insightful questions about the following text. Return ONLY a JSON array of question strings, nothing else. Example: ["Question 1?", "Question 2?"]`,s=await this.sendMessage(n,e,{temperature:.7});try{return JSON.parse(s)}catch{const e=s.match(/\[[\s\S]*\]/);return e?JSON.parse(e[0]):s.split("\n").filter(e=>e.trim().endsWith("?"))}}async getJSON(e,t,n={}){const s=await this.sendMessage(e+"\n\nReturn ONLY valid JSON, no additional text.",t,{...n,temperature:n.temperature??.2});try{return JSON.parse(s)}catch{const e=s.match(/[\[{][\s\S]*[\]}]/);if(e)return JSON.parse(e[0]);throw new Error(`Failed to parse JSON response: ${s.substring(0,100)}`)}}}class SchemaExtractor{constructor(e){this.llm=e}async extractToSchema(e,t,n={}){const s=this._describeSchema(t),r=`You are a data extraction expert. Extract structured information from the provided text according to this JSON schema:\n\n${JSON.stringify(t,null,2)}\n\nSchema field descriptions:\n${s}\n\nRules:\n1. Extract ONLY information present in the text\n2. Use null for fields where information is not available\n3. Follow the exact schema structure and field types\n4. For arrays, include all relevant items found\n5. Return ONLY valid JSON matching the schema`;return await this.llm.getJSON(r,e,{temperature:.2,maxTokens:n.maxTokens||2e3})}_describeSchema(e,t=""){const n=[];if(e.description&&n.push(`${t||"root"}: ${e.description}`),e.properties)for(const[s,r]of Object.entries(e.properties)){const i=t?`${t}.${s}`:s,a=r.type||"any",o=e.required?.includes(s)?" (required)":"",l=r.description||"";n.push(`- ${i} [${a}]${o}: ${l}`),"object"===r.type&&r.properties&&n.push(this._describeSchema(r,i)),"array"===r.type&&r.items&&r.items.properties&&n.push(this._describeSchema(r.items,`${i}[]`))}return n.join("\n")}async extractMultiple(e,t,n={}){const s=`You are a data extraction expert. Extract ALL items matching this schema from the text:\n\n${JSON.stringify(t,null,2)}\n\nReturn a JSON array of all items found. If no items found, return [].\nReturn ONLY valid JSON array.`,r=await this.llm.getJSON(s,e,{temperature:.2,maxTokens:n.maxTokens||3e3});return Array.isArray(r)?r:[r]}async fillMissing(e,t,n){const s=this._findMissingFields(e,n);if(0===s.length)return e;const r=`You have existing data:\n${JSON.stringify(e,null,2)}\n\nExtract ONLY the following missing fields from the text:\n${s.join(", ")}\n\nBased on this schema:\n${JSON.stringify(n,null,2)}\n\nReturn JSON with ONLY the missing fields that you can extract. Do not modify existing fields.`,i=await this.llm.getJSON(r,t,{temperature:.2});return{...e,...i}}_findMissingFields(e,t,n=""){const s=[];if(t.properties)for(const[r,i]of Object.entries(t.properties)){const t=n?`${n}.${r}`:r,a=e[r];null==a?s.push(t):"object"===i.type&&i.properties&&s.push(...this._findMissingFields(a,i,t))}return s}validateExtraction(e,t){const n=[];if(t.required)for(const s of t.required)void 0!==e[s]&&null!==e[s]||n.push(`Missing required field: ${s}`);if(t.properties)for(const[s,r]of Object.entries(t.properties)){const t=e[s];if(null!=t){this._validateType(t,r.type)||n.push(`Invalid type for ${s}: expected ${r.type}, got ${typeof t}`)}}return{valid:0===n.length,errors:n}}_validateType(e,t){switch(t){case"string":return"string"==typeof e;case"number":case"integer":return"number"==typeof e;case"boolean":return"boolean"==typeof e;case"array":return Array.isArray(e);case"object":return"object"==typeof e&&!Array.isArray(e);default:return!0}}}class JSONOps{constructor(e){this.llm=e}async add(e,t,n={}){const s=`You are a JSON merge expert. Semantically merge these two JSON objects.\n\nRules:\n1. Combine information from both objects intelligently\n2. For conflicting values, prefer the more complete/detailed one${n.preferSecond?", or prefer the second object":""}\n3. Merge arrays by combining items, removing duplicates by semantic similarity\n4. Preserve all unique information from both objects\n5. Return ONLY valid JSON`,r=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON(s,r,{temperature:.2})}async subtract(e,t){const n=`Base object (to modify):\n${JSON.stringify(e,null,2)}\n\nConcepts to remove:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON manipulation expert. Remove concepts from the first object that are semantically present in the second object.\n\nRules:\n1. Remove fields from obj1 that have semantic equivalents in obj2\n2. For arrays, remove items that are semantically similar to items in obj2\n3. Preserve fields/items in obj1 that have no semantic match in obj2\n4. Remove nested content that matches semantically\n5. Return ONLY valid JSON",n,{temperature:.2})}async union(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON merge expert. Create a semantic union of these two JSON objects.\n\nRules:\n1. Include all unique information from both objects\n2. For duplicate concepts, keep only one (the more complete version)\n3. Deduplicate array items by semantic similarity, not just exact match\n4. Merge nested objects recursively with the same rules\n5. Return ONLY valid JSON",n,{temperature:.2})}async difference(e,t){const n=`Object 1 (original):\n${JSON.stringify(e,null,2)}\n\nObject 2 (new):\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON('You are a JSON comparison expert. Find the semantic differences between these two JSON objects.\n\nReturn a JSON object with:\n- "added": fields/values present in obj2 but not in obj1\n- "removed": fields/values present in obj1 but not in obj2\n- "changed": fields where the value changed (show both old and new)\n\nConsider semantic similarity - fields with different names but same meaning should be considered the same.\nReturn ONLY valid JSON with the structure: {"added": {}, "removed": {}, "changed": {}}',n,{temperature:.2})}async concatenate(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON concatenation expert. Concatenate these two JSON objects.\n\nRules:\n1. For string fields: append obj2 values to obj1 values with appropriate separators\n2. For array fields: append obj2 arrays to obj1 arrays\n3. For number fields: sum the values\n4. For object fields: recursively concatenate\n5. For boolean fields: use logical OR\n6. Preserve the structure of obj1\n7. Return ONLY valid JSON",n,{temperature:.2})}async intersection(e,t){const n=`Object 1:\n${JSON.stringify(e,null,2)}\n\nObject 2:\n${JSON.stringify(t,null,2)}`;return this.llm.getJSON("You are a JSON comparison expert. Find the semantic intersection of these two JSON objects.\n\nRules:\n1. Return only fields/values that are semantically present in BOTH objects\n2. For arrays, return only items that have semantic matches in both\n3. Consider semantic similarity, not just exact matches\n4. Return ONLY valid JSON",n,{temperature:.2})}async transform(e,t){const n=`You are a JSON transformation expert. Transform this JSON object according to the target structure description.\n\nTarget structure: ${t}\n\nRules:\n1. Map existing fields to the new structure\n2. Preserve all information, reorganizing as needed\n3. Use appropriate type conversions\n4. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async simplify(e,t={}){const n=`You are a JSON simplification expert. Simplify this nested JSON object.\n\nRules:\n1. Flatten deeply nested structures where appropriate\n2. Combine redundant fields\n3. Remove null/empty values${t.keepEmpty?" (unless specified to keep)":""}\n4. Use clear, concise field names\n5. Return ONLY valid JSON`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}async apply(e,t){const n=`You are a JSON manipulation expert. Apply the following operation to the JSON object:\n\nOperation: ${t}\n\nReturn ONLY valid JSON with the operation applied.`;return this.llm.getJSON(n,JSON.stringify(e,null,2),{temperature:.3})}}class Embeddings{constructor(e,t=null){this.openai=e,this.holosphere=t,this.model="text-embedding-3-small",this.dimensions=1536}setHoloSphere(e){this.holosphere=e}async embed(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data[0].embedding}catch(t){throw new Error(`Embedding generation failed: ${t.message}`)}}async embedBatch(e){try{return(await this.openai.embeddings.create({model:this.model,input:e})).data.map(e=>e.embedding)}catch(t){throw new Error(`Batch embedding failed: ${t.message}`)}}cosineSimilarity(e,t){if(e.length!==t.length)throw new Error("Vectors must have same length");let n=0,s=0,r=0;for(let i=0;i<e.length;i++)n+=e[i]*t[i],s+=e[i]*e[i],r+=t[i]*t[i];return n/(Math.sqrt(s)*Math.sqrt(r))}async storeWithEmbedding(e,t,n,s=null){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const r=s?n[s]:n.content||n.text||n.description||JSON.stringify(n);if(!r)throw new Error("No text found to embed");const i=await this.embed(r),a={...n,_embedding:i,_embeddedField:s||"auto",_embeddedAt:Date.now()};return await this.holosphere.put(e,t,a),a}async semanticSearch(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required for search");const{limit:r=10,threshold:i=.5}=s,a=await this.embed(e),o=await this.holosphere.getAll(t,n),l=[];for(const c of o)if(c._embedding){const e=this.cosineSimilarity(a,c._embedding);e>=i&&l.push({item:{...c,_embedding:void 0},similarity:e})}return l.sort((e,t)=>t.similarity-e.similarity),l.slice(0,r)}async findSimilar(e,t,n,s={}){const r=e.content||e.text||e.description||JSON.stringify(e);return this.semanticSearch(r,t,n,s)}async cluster(e,t=5){const n=await Promise.all(e.map(async e=>{if(e._embedding)return e;const t=e.content||e.text||e.description||JSON.stringify(e),n=await this.embed(t);return{...e,_embedding:n}}));return this._kMeans(n,t).map(e=>e.map(e=>({...e,_embedding:void 0})))}_kMeans(e,t,n=100){if(e.length<=t)return e.map(e=>[e]);let s=[...e].sort(()=>Math.random()-.5).slice(0,t).map(e=>[...e._embedding]),r=new Array(e.length);for(let a=0;a<n;a++){const n=e.map(e=>{let t=1/0,n=0;for(let r=0;r<s.length;r++){const i=1-this.cosineSimilarity(e._embedding,s[r]);i<t&&(t=i,n=r)}return n});if(JSON.stringify(n)===JSON.stringify(r))break;r=n;for(let i=0;i<t;i++){const t=e.filter((e,t)=>r[t]===i);if(t.length>0){s[i]=new Array(this.dimensions).fill(0);for(const e of t)for(let t=0;t<this.dimensions;t++)s[i][t]+=e._embedding[t];for(let e=0;e<this.dimensions;e++)s[i][e]/=t.length}}}const i=Array.from({length:t},()=>[]);return e.forEach((e,t)=>{i[r[t]].push(e)}),i.filter(e=>e.length>0)}}const DEFAULT_PERSPECTIVES=[{name:"Values & Worldview",prompt:"Answer from the embodied perspective of Values and Worldview - considering ethics, beliefs, culture, and meaning."},{name:"Health & Wellbeing",prompt:"Answer from the embodied perspective of Health & Wellbeing - considering physical, mental, and social health."},{name:"Food & Agriculture",prompt:"Answer from the embodied perspective of Food & Agriculture - considering food systems, nutrition, and farming."},{name:"Business & Trade",prompt:"Answer from the embodied perspective of Business & Trade - considering commerce, markets, and economic exchange."},{name:"Energy & Resources",prompt:"Answer from the embodied perspective of Energy & Resources - considering power, materials, and sustainability."},{name:"Climate & Environment",prompt:"Answer from the embodied perspective of Climate Change - considering environmental impact and adaptation."},{name:"Ecosystems & Biosphere",prompt:"Answer from the embodied perspective of Ecosystems & Biosphere - considering biodiversity and natural systems."},{name:"Water Availability",prompt:"Answer from the embodied perspective of Water Availability - considering water access, quality, and management."},{name:"Habitat & Infrastructure",prompt:"Answer from the embodied perspective of Habitat & Infrastructure - considering built environment and housing."},{name:"Economy & Wealth",prompt:"Answer from the embodied perspective of Economy & Wealth - considering prosperity, inequality, and resources."},{name:"Governance & Institutions",prompt:"Answer from the embodied perspective of Governance & Institutions - considering power, policy, and organization."},{name:"Community & Resilience",prompt:"Answer from the embodied perspective of Community & Resilience - considering social bonds and adaptability."}];class Council{constructor(e,t=null){this.llm=e,this.perspectives=t||DEFAULT_PERSPECTIVES}setPerspectives(e){this.perspectives=e}static getDefaultPerspectives(){return DEFAULT_PERSPECTIVES}async ask(e,t={}){const{parallel:n=!0,includeSummary:s=!0}=t,r=t.perspectives||this.perspectives;let i;if(n)i=await Promise.all(r.map(async t=>{const n=await this._askPerspective(e,t);return{perspective:t.name,answer:n}}));else{i=[];for(const t of r){const n=await this._askPerspective(e,t);i.push({perspective:t.name,answer:n})}}let a=null;return s&&(a=await this._summarize(e,i)),{question:e,perspectives:i,summary:a,timestamp:Date.now()}}async _askPerspective(e,t){const n=`You are a wise council member representing a specific perspective.\n\n${t.prompt}\n\nProvide thoughtful, nuanced answers that honor your unique perspective while being constructive and helpful. Be concise but insightful.`;return this.llm.sendMessage(n,e,{temperature:.7})}async _summarize(e,t){const n=`Question: ${e}\n\nPerspectives:\n${t.map(e=>`**${e.perspective}**: ${e.answer}`).join("\n\n")}`;return this.llm.sendMessage("You are a wise facilitator. Synthesize the following perspectives into a balanced summary that:\n1. Identifies common themes and agreements\n2. Notes important tensions or tradeoffs\n3. Provides actionable wisdom\n4. Remains neutral and balanced\n\nBe concise but comprehensive.",n,{temperature:.5})}static createPerspectives(e){return e.map(e=>({name:e,prompt:`Answer from the embodied perspective of ${e} - considering all aspects related to ${e.toLowerCase()}.`}))}async askCustom(e,t,n={}){const s=Council.createPerspectives(t);return this.ask(e,{...n,perspectives:s})}async askSingle(e,t){const n=this.perspectives.find(e=>e.name===t)||{name:t,prompt:`Answer from the perspective of ${t}.`};return this._askPerspective(e,n)}async debate(e,t,n=3){if(2!==t.length)throw new Error("Debate requires exactly 2 perspectives");const s=t.map(e=>this.perspectives.find(t=>t.name===e)||{name:e,prompt:`Argue from the perspective of ${e}.`}),r=[];let i=`Topic: ${e}`;for(let a=0;a<n;a++)for(const e of s){const t=`You are debating from the perspective of ${e.name}.\n${e.prompt}\nRespond to the previous arguments constructively, acknowledging good points but advocating for your perspective.`,n=await this.llm.sendMessage(t,i,{temperature:.7});r.push({perspective:e.name,round:a+1,response:n}),i+=`\n\n${e.name}: ${n}`}return{topic:e,perspectives:t,exchanges:r,conclusion:await this.llm.sendMessage("As a neutral moderator, summarize the key insights from this debate and identify areas of agreement and disagreement.",i,{temperature:.5})}}}const VOICES={ALLOY:"alloy",ECHO:"echo",FABLE:"fable",ONYX:"onyx",NOVA:"nova",SHIMMER:"shimmer"},MODELS={TTS_1:"tts-1",TTS_1_HD:"tts-1-hd"};class TTS{constructor(e){this.openai=e,this.defaultVoice=VOICES.ECHO,this.defaultModel=MODELS.TTS_1}async speak(e,t={}){const{voice:n=this.defaultVoice,model:s=this.defaultModel,speed:r=1,responseFormat:i="mp3"}=t;try{const t=await this.openai.audio.speech.create({model:s,voice:n,input:e,speed:r,response_format:i}),a=await t.arrayBuffer();return Buffer.from(a)}catch(a){throw new Error(`TTS failed: ${a.message}`)}}async speakBase64(e,t={}){return(await this.speak(e,t)).toString("base64")}async speakDataUrl(e,t={}){const n=t.responseFormat||"mp3";return`data:${"mp3"===n?"audio/mpeg":`audio/${n}`};base64,${await this.speakBase64(e,t)}`}setDefaultVoice(e){if(!Object.values(VOICES).includes(e))throw new Error(`Invalid voice: ${e}. Use one of: ${Object.values(VOICES).join(", ")}`);this.defaultVoice=e}setDefaultModel(e){if(!Object.values(MODELS).includes(e))throw new Error(`Invalid model: ${e}. Use one of: ${Object.values(MODELS).join(", ")}`);this.defaultModel=e}static getVoices(){return Object.values(VOICES)}static getModels(){return Object.values(MODELS)}static estimateDuration(e,t=1){return 60*(e.split(/\s+/).length/150)/t}static splitText(e,t=4e3){if(e.length<=t)return[e];const n=[],s=e.split(/(?<=[.!?])\s+/);let r="";for(const i of s)(r+i).length>t?(r&&n.push(r.trim()),r=i):r+=(r?" ":"")+i;return r&&n.push(r.trim()),n}async speakLong(e,t={}){const n=TTS.splitText(e,t.maxChars||4e3);return await Promise.all(n.map(e=>this.speak(e,t)))}}class NLQuery{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async parse(e,t={}){const n=`You are a query parser. Convert natural language queries into structured JSON filters for a geospatial database.\n\nAvailable holons: ${t.holons?.join(", ")||"any"}\nAvailable lenses: ${t.lenses?.join(", ")||"any"}\n\nReturn a JSON object with:\n{\n "holon": "holon_id or null",\n "lens": "lens_name or null",\n "filters": {\n "field_name": { "op": "eq|ne|gt|gte|lt|lte|contains|in", "value": value }\n },\n "sort": { "field": "field_name", "order": "asc|desc" } or null,\n "limit": number or null,\n "spatial": { "near": "location_name", "radius": "distance" } or null,\n "temporal": { "after": "date", "before": "date" } or null\n}\n\nExamples:\n- "show projects near Rome" -> { "lens": "projects", "spatial": { "near": "Rome" } }\n- "find quests with more than 10 participants" -> { "lens": "quests", "filters": { "participants": { "op": "gt", "value": 10 } } }`;return await this.llm.getJSON(n,e,{temperature:.2})}async execute(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required for query execution");const n=await this.parse(e,t.context);let s=[];if(n.holon&&n.lens)s=await this.holosphere.getAll(n.holon,n.lens);else if(n.lens&&t.holons)for(const r of t.holons){const e=await this.holosphere.getAll(r,n.lens);s.push(...e.map(e=>({...e,_holon:r})))}return n.filters&&(s=this._applyFilters(s,n.filters)),n.sort&&(s=this._applySort(s,n.sort)),n.limit&&(s=s.slice(0,n.limit)),{query:e,parsed:n,results:s,count:s.length}}_applyFilters(e,t){return e.filter(e=>{for(const[n,s]of Object.entries(t)){const t=this._getNestedValue(e,n);if(!this._matchCondition(t,s))return!1}return!0})}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_matchCondition(e,t){const{op:n,value:s}=t;switch(n){case"eq":return e===s;case"ne":return e!==s;case"gt":return e>s;case"gte":return e>=s;case"lt":return e<s;case"lte":return e<=s;case"contains":return String(e).toLowerCase().includes(String(s).toLowerCase());case"in":return Array.isArray(s)&&s.includes(e);default:return!0}}_applySort(e,t){const{field:n,order:s}=t,r="desc"===s?-1:1;return[...e].sort((e,t)=>{const s=this._getNestedValue(e,n),i=this._getNestedValue(t,n);return s<i?-1*r:s>i?1*r:0})}async suggest(e={}){const t=`Suggest 5 useful natural language queries for exploring geospatial data.\n\nAvailable holons: ${e.holons?.join(", ")||"geographic areas"}\nAvailable lenses: ${e.lenses?.join(", ")||"projects, quests, events, resources"}\n\nReturn ONLY a JSON array of query strings.`;return this.llm.getJSON(t,"Generate query suggestions",{temperature:.7})}async explain(e,t){const n=`You are a helpful data analyst. Explain the results of a query in natural language.\n\nOriginal query: ${e}\nNumber of results: ${t.length}\n\nProvide a brief, helpful summary of what was found.`,s=t.slice(0,5);return this.llm.sendMessage(n,`Results sample: ${JSON.stringify(s,null,2)}`,{temperature:.5})}}class Classifier{constructor(e,t=null){this.llm=e,this.holosphere=t,this.lensDescriptions=new Map}setHoloSphere(e){this.holosphere=e}registerLens(e,t,n=null){this.lensDescriptions.set(e,{description:t,schema:n})}registerLenses(e){for(const[t,n]of Object.entries(e))this.registerLens(t,n.description,n.schema)}async classifyToLens(e){const t=Array.from(this.lensDescriptions.entries());if(0===t.length)throw new Error("No lenses registered. Use registerLens() first.");const n=t.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),s="string"==typeof e?e:JSON.stringify(e,null,2),r=`You are a content classifier. Classify the following content into the most appropriate lens.\n\nAvailable lenses:\n${n}\n\nReturn JSON: {"lens": "lens_name", "confidence": 0.0-1.0, "reasoning": "brief explanation"}`;return this.llm.getJSON(r,s,{temperature:.2})}async classifyMultiple(e,t=3){const n=Array.from(this.lensDescriptions.entries());if(0===n.length)throw new Error("No lenses registered");const s=n.map(([e,t])=>`- ${e}: ${t.description}`).join("\n"),r="string"==typeof e?e:JSON.stringify(e,null,2),i=`You are a content classifier. Classify the content into up to ${t} appropriate lenses, ranked by fit.\n\nAvailable lenses:\n${s}\n\nReturn JSON array: [{"lens": "name", "confidence": 0.0-1.0}, ...]\nOrder by confidence descending.`;return this.llm.getJSON(i,r,{temperature:.2})}async autoStore(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required for storage");const n=await this.classifyToLens(t),s=await this.holosphere.put(e,n.lens,t);return{lens:n.lens,confidence:n.confidence,reasoning:n.reasoning,stored:!0,result:s}}async suggestNewLens(e){const t=`You are helping design a data organization system. Suggest a new lens (category) for this type of content.\n\nExisting lenses: ${Array.from(this.lensDescriptions.keys()).join(", ")}\n\nReturn JSON: {"name": "lens_name", "description": "what this lens contains"}\nUse lowercase_snake_case for names.`;return this.llm.getJSON(t,e,{temperature:.5})}async suggestSchema(e){const t=JSON.stringify(e,null,2);return this.llm.getJSON("You are a data modeling expert. Analyze this content and suggest a JSON schema for validating similar content.\n\nReturn a valid JSON schema with:\n- Type definitions\n- Required fields\n- Field descriptions\n- Reasonable constraints",t,{temperature:.3})}async validateForLens(e,t){const n=this.lensDescriptions.get(t);if(!n)throw new Error(`Lens not found: ${t}`);if(!n.schema){const s=`Validate if this content is appropriate for the "${t}" lens.\nLens description: ${n.description}\n\nReturn JSON: {"valid": true/false, "issues": ["issue1", "issue2"] or []}`;return this.llm.getJSON(s,JSON.stringify(e,null,2),{temperature:.2})}return{valid:!0,issues:[]}}async analyzeCollection(e){const t=await Promise.all(e.map(e=>this.classifyToLens(e))),n={};for(const s of t)n[s.lens]=(n[s.lens]||0)+1;return{total:e.length,byLens:n,classifications:t}}}class SpatialAnalysis{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async analyzeRegion(e,t=null,n="general"){if(!this.holosphere)throw new Error("HoloSphere instance required");let s=[];s=t?await this.holosphere.getAll(e,t):await this.holosphere.getAll(e,"default");const r=JSON.stringify(s.slice(0,50),null,2),i=`You are a geospatial data analyst. Analyze the following data from a geographic region.\n\nRegion (holon): ${e}\nLens: ${t||"all"}\nAnalysis aspect: ${n}\nTotal items: ${s.length}\n\nProvide insights about:\n1. Key patterns and trends\n2. Notable clusters or concentrations\n3. Anomalies or outliers\n4. Recommendations for the region\n\nReturn JSON:\n{\n "summary": "brief overview",\n "patterns": ["pattern1", "pattern2"],\n "insights": ["insight1", "insight2"],\n "metrics": {"metric1": value},\n "recommendations": ["rec1", "rec2"],\n "confidence": 0.0-1.0\n}`,a=await this.llm.getJSON(i,r,{temperature:.3});return{holon:e,lens:t,aspect:n,dataCount:s.length,analysis:a,timestamp:Date.now()}}async compareRegions(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,n),r=await this.holosphere.getAll(t,n),i=`You are a comparative analyst. Compare data between two geographic regions.\n\nRegion 1 (${e}): ${s.length} items\nRegion 2 (${t}): ${r.length} items\nLens: ${n}\n\nAnalyze and compare:\n1. Similarities between regions\n2. Key differences\n3. Relative strengths of each region\n4. Opportunities for collaboration\n\nReturn JSON:\n{\n "summary": "brief comparison",\n "similarities": ["sim1", "sim2"],\n "differences": ["diff1", "diff2"],\n "region1_strengths": ["strength1"],\n "region2_strengths": ["strength1"],\n "collaboration_opportunities": ["opp1"],\n "metrics_comparison": {"metric": {"region1": val, "region2": val}}\n}`,a=`Region 1 data sample:\n${JSON.stringify(s.slice(0,25),null,2)}\n\nRegion 2 data sample:\n${JSON.stringify(r.slice(0,25),null,2)}`,o=await this.llm.getJSON(i,a,{temperature:.3});return{regions:[e,t],lens:n,dataCounts:{[e]:s.length,[t]:r.length},comparison:o,timestamp:Date.now()}}async spatialTrends(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t);let r=s;(n.start||n.end)&&(r=s.filter(e=>{const t=e.timestamp||e.created_at||e.date;if(!t)return!0;const s=new Date(t).getTime();return!(n.start&&s<new Date(n.start).getTime())&&!(n.end&&s>new Date(n.end).getTime())}));const i=`You are a trend analyst. Analyze temporal patterns in geographic data.\n\nRegion: ${e}\nLens: ${t}\nTime range: ${JSON.stringify(n)}\nItems analyzed: ${r.length}\n\nIdentify:\n1. Growth/decline trends\n2. Seasonal patterns\n3. Emerging themes\n4. Predictions\n\nReturn JSON:\n{\n "trends": [{"trend": "description", "direction": "up|down|stable", "strength": 0.0-1.0}],\n "patterns": ["pattern1"],\n "emerging_themes": ["theme1"],\n "predictions": ["pred1"],\n "summary": "overview"\n}`,a=await this.llm.getJSON(i,JSON.stringify(r.slice(0,50),null,2),{temperature:.3});return{holon:e,lens:t,timeRange:n,dataCount:r.length,trends:a,timestamp:Date.now()}}async findHotspots(e,t,n="count"){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=`You are a spatial analyst. Identify hotspots (areas of high concentration/activity) in geographic data.\n\nRegion: ${e}\nLens: ${t}\nMetric: ${n}\nData points: ${s.length}\n\nIdentify:\n1. High-activity areas\n2. Emerging areas\n3. Underserved areas\n4. Recommended focus areas\n\nReturn JSON:\n{\n "hotspots": [{"location": "desc", "intensity": 0.0-1.0, "type": "high_activity|emerging|underserved"}],\n "concentration_patterns": ["pattern1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(r,JSON.stringify(s.slice(0,50),null,2),{temperature:.3})}async generateReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=t.lenses||["default"],s={};for(const a of n)s[a]=await this.holosphere.getAll(e,a);const r=`You are a regional analyst. Generate a comprehensive report for this geographic region.\n\nRegion: ${e}\nData by lens: ${Object.entries(s).map(([e,t])=>`${e}: ${t.length} items`).join(", ")}\n\nGenerate a professional report including:\n1. Executive Summary\n2. Key Statistics\n3. Notable Patterns\n4. Opportunities\n5. Recommendations\n\nFormat as markdown.`,i={};for(const[a,o]of Object.entries(s))i[a]=o.slice(0,20);return this.llm.sendMessage(r,JSON.stringify(i,null,2),{temperature:.5,maxTokens:2e3})}}class SmartAggregation{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async smartUpcast(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{maxLevels:s=5,storeResults:r=!0}=n,i=await this.holosphere.getAll(e,t),a=await this._generateSummary(i,e,t),o=h3__namespace.getResolution(e);if(o<=0||s<=0)return{holon:e,lens:t,summary:a,level:o};const l=h3__namespace.cellToParent(e,o-1);r&&await this.holosphere.put(l,`${t}_summaries`,{id:e,childHolon:e,summary:a,dataCount:i.length,timestamp:Date.now()});const c=await this.smartUpcast(l,t,{...n,maxLevels:s-1});return{holon:e,lens:t,summary:a,dataCount:i.length,parent:c}}async _generateSummary(e,t,n){if(0===e.length)return{text:"No data in this region",stats:{count:0}};const s=`You are a data summarization expert. Create a concise summary of this geographic data.\n\nRegion: ${t}\nCategory: ${n}\nItems: ${e.length}\n\nGenerate:\n1. A brief text summary (2-3 sentences)\n2. Key statistics\n3. Notable items\n4. Themes/patterns\n\nReturn JSON:\n{\n "text": "summary text",\n "stats": {"count": n, "key_metric": value},\n "notable": ["item1", "item2"],\n "themes": ["theme1", "theme2"]\n}`;return this.llm.getJSON(s,JSON.stringify(e.slice(0,30),null,2),{temperature:.3})}async generateHolonSummary(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=["projects","quests","events","resources","default"],n={};for(const i of t)try{const t=await this.holosphere.getAll(e,i);t.length>0&&(n[i]=t)}catch{}const s=`You are a regional analyst. Generate a comprehensive summary of this geographic area.\n\nRegion: ${e}\nData available: ${Object.entries(n).map(([e,t])=>`${e}: ${t.length}`).join(", ")}\n\nGenerate a complete overview including:\n1. Executive summary\n2. Key activities and projects\n3. Community engagement\n4. Resources and assets\n5. Challenges and opportunities\n6. Overall health assessment\n\nReturn JSON:\n{\n "title": "Region Title",\n "executive_summary": "brief overview",\n "highlights": ["highlight1", "highlight2"],\n "activities": {"count": n, "summary": "text"},\n "community": {"engagement_level": "high|medium|low", "notes": "text"},\n "resources": ["resource1"],\n "challenges": ["challenge1"],\n "opportunities": ["opp1"],\n "health_score": 0.0-1.0,\n "recommendations": ["rec1"]\n}`,r={};for(const[i,a]of Object.entries(n))r[i]=a.slice(0,15);return{holon:e,summary:await this.llm.getJSON(s,JSON.stringify(r,null,2),{temperature:.4,maxTokens:2e3}),lensesAnalyzed:Object.keys(n),totalItems:Object.values(n).reduce((e,t)=>e+t.length,0),timestamp:Date.now()}}async aggregateChildren(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n=h3__namespace.getResolution(e),s=h3__namespace.cellToChildren(e,n+1),r=[];for(const o of s.slice(0,7))try{const e=await this.holosphere.getAll(o,t);if(e.length>0){const n=await this._generateSummary(e,o,t);r.push({holon:o,summary:n})}}catch{}if(0===r.length)return{holon:e,summary:null,message:"No child data found"};const i=`You are aggregating summaries from child regions into a parent region summary.\n\nParent region: ${e}\nChild summaries: ${r.length}\n\nCreate an aggregated summary that:\n1. Synthesizes common themes\n2. Highlights regional diversity\n3. Identifies cross-cutting patterns\n4. Notes outliers\n\nReturn JSON:\n{\n "aggregated_summary": "text",\n "common_themes": ["theme1"],\n "regional_diversity": ["diff1"],\n "patterns": ["pattern1"],\n "total_activity": {"count": n, "trend": "growing|stable|declining"}\n}`,a=await this.llm.getJSON(i,JSON.stringify(r,null,2),{temperature:.3});return{holon:e,lens:t,childCount:r.length,summary:a,timestamp:Date.now()}}async comparePeriods(e,t,n,s){if(!this.holosphere)throw new Error("HoloSphere instance required");const r=await this.holosphere.getAll(e,t),i=(e,t)=>e.filter(e=>{const n=e.timestamp||e.created_at;if(!n)return!1;const s=new Date(n).getTime();return s>=new Date(t.start).getTime()&&s<=new Date(t.end).getTime()}),a=i(r,n),o=i(r,s),l=`Compare data between two time periods for a geographic region.\n\nRegion: ${e}\nPeriod 1: ${JSON.stringify(n)} - ${a.length} items\nPeriod 2: ${JSON.stringify(s)} - ${o.length} items\n\nAnalyze:\n1. Growth/decline\n2. New themes in period 2\n3. Themes that disappeared\n4. Key changes\n\nReturn JSON:\n{\n "growth_rate": percentage,\n "direction": "growth|decline|stable",\n "new_themes": ["theme1"],\n "disappeared": ["theme1"],\n "key_changes": ["change1"],\n "summary": "text"\n}`,c=`Period 1 data:\n${JSON.stringify(a.slice(0,20),null,2)}\n\nPeriod 2 data:\n${JSON.stringify(o.slice(0,20),null,2)}`;return this.llm.getJSON(l,c,{temperature:.3})}}class FederationAdvisor{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async suggestFederations(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{candidateHolons:n=[],lens:s="default",maxSuggestions:r=5}=t,i=await this.holosphere.getAll(e,s);if(0===i.length)return{holon:e,suggestions:[],message:"No data in source holon"};const a=[];for(const c of n.slice(0,10))if(c!==e)try{const e=await this.holosphere.getAll(c,s);e.length>0&&a.push({holon:c,dataCount:e.length,dataSample:e.slice(0,10)})}catch{}if(0===a.length)return{holon:e,suggestions:[],message:"No candidate holons with data"};const o=`You are a federation advisor. Analyze which regions would benefit from federating (sharing data) with the source region.\n\nSource region: ${e}\nSource data count: ${i.length}\n\nConsider:\n1. Content similarity - similar topics benefit from shared visibility\n2. Complementary content - different but related content enables collaboration\n3. Geographic proximity relevance\n4. Potential for knowledge sharing\n\nReturn JSON array:\n[\n {\n "holon": "id",\n "score": 0.0-1.0,\n "reasoning": "why federate",\n "benefits": ["benefit1"],\n "type": "similarity|complementary|geographic"\n }\n]\n\nOrder by score descending, max ${r} suggestions.`,l=`Source data sample:\n${JSON.stringify(i.slice(0,15),null,2)}\n\nCandidate regions:\n${JSON.stringify(a,null,2)}`;return{holon:e,lens:s,suggestions:(await this.llm.getJSON(o,l,{temperature:.3})).slice(0,r),timestamp:Date.now()}}async analyzeFederationHealth(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t||!t.federation||0===t.federation.length)return{holon:e,health:"none",message:"No federations configured",score:0};const n=[];for(const i of t.federation.slice(0,5))try{const e=await this.holosphere.getAll(i,"default");n.push({holon:i,active:e.length>0,dataCount:e.length})}catch{n.push({holon:i,active:!1,error:!0})}const s=`You are a federation health analyst. Assess the health of this holon's federation relationships.\n\nSource holon: ${e}\nFederation partners: ${t.federation.length}\nActive federations: ${n.filter(e=>e.active).length}\n\nFederation details:\n${JSON.stringify(n,null,2)}\n\nAnalyze:\n1. Overall federation health\n2. Active vs inactive relationships\n3. Balance of the federation network\n4. Recommendations\n\nReturn JSON:\n{\n "health_score": 0.0-1.0,\n "status": "healthy|degraded|unhealthy",\n "active_count": n,\n "inactive_count": n,\n "issues": ["issue1"],\n "recommendations": ["rec1"],\n "summary": "text"\n}`,r=await this.llm.getJSON(s,"",{temperature:.3});return{holon:e,federation:t.federation,analysis:r,timestamp:Date.now()}}async optimizeFederation(e){const t=await this.analyzeFederationHealth(e);if("none"===t.health)return{holon:e,suggestions:["Consider establishing initial federations"]};const n=`Based on federation health analysis, suggest optimizations.\n\nHealth analysis:\n${JSON.stringify(t.analysis,null,2)}\n\nSuggest:\n1. Federations to strengthen\n2. Federations to reconsider\n3. New potential federations\n4. Data flow improvements\n\nReturn JSON:\n{\n "strengthen": ["holon_id"],\n "reconsider": ["holon_id"],\n "new_potential": ["description"],\n "improvements": ["improvement1"],\n "priority": "high|medium|low"\n}`;return this.llm.getJSON(n,"",{temperature:.4})}async analyzeDataFlow(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=await this.holosphere.getFederation(e);if(!t)return{holon:e,message:"No federation configured"};const n=`Analyze the data flow patterns in a federation network.\n\nSource holon: ${e}\nFederated with: ${t.federation?.join(", ")||"none"}\nNotifies: ${t.notify?.join(", ")||"none"}\n\nConsider:\n1. Bidirectional vs unidirectional relationships\n2. Hub patterns (many connections)\n3. Data propagation paths\n4. Potential bottlenecks\n\nReturn JSON:\n{\n "flow_type": "bidirectional|unidirectional|mixed",\n "topology": "hub|mesh|chain|star",\n "propagation_depth": n,\n "bottlenecks": ["desc"],\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(n,JSON.stringify(t,null,2),{temperature:.3})}async findBridges(e){if(!this.holosphere)throw new Error("HoloSphere instance required");const t=[];for(const s of e.slice(0,20))try{const e=await this.holosphere.getFederation(s);e&&t.push({holon:s,federations:e.federation||[],notifies:e.notify||[]})}catch{}const n=`Analyze a federation network to identify bridge holons (connectors between clusters).\n\nNetwork:\n${JSON.stringify(t,null,2)}\n\nIdentify:\n1. Bridge holons that connect clusters\n2. Isolated holons\n3. Central hubs\n4. Network clusters\n\nReturn JSON:\n{\n "bridges": [{"holon": "id", "connects": ["cluster1", "cluster2"]}],\n "isolated": ["holon_id"],\n "hubs": [{"holon": "id", "connections": n}],\n "clusters": [["holon1", "holon2"]],\n "network_health": 0.0-1.0\n}`;return this.llm.getJSON(n,"",{temperature:.3})}}class RelationshipDiscovery{constructor(e,t=null,n=null){this.llm=e,this.holosphere=t,this.embeddings=n}setHoloSphere(e){this.holosphere=e}setEmbeddings(e){this.embeddings=e}async discoverRelationships(e,t=null){if(!this.holosphere)throw new Error("HoloSphere instance required");let n=[];const s=t?[t]:["projects","quests","events","resources","default"];for(const a of s)try{const t=await this.holosphere.getAll(e,a);n.push(...t.map(e=>({...e,_lens:a})))}catch{}if(n.length<2)return{holon:e,relationships:[],message:"Not enough data for relationship discovery"};const r=`You are a relationship discovery expert. Find hidden connections between items in this dataset.\n\nRegion: ${e}\nItems: ${n.length}\n\nLook for:\n1. Thematic connections (shared topics, goals)\n2. Entity connections (shared people, organizations)\n3. Temporal connections (same timeframes)\n4. Causal connections (one enables/requires another)\n5. Geographic connections (same sub-regions)\n\nReturn JSON:\n{\n "relationships": [\n {\n "item1": {"id": "id1", "title": "title"},\n "item2": {"id": "id2", "title": "title"},\n "type": "thematic|entity|temporal|causal|geographic",\n "strength": 0.0-1.0,\n "description": "relationship description"\n }\n ],\n "clusters": [\n {\n "theme": "cluster theme",\n "items": ["id1", "id2"]\n }\n ],\n "key_entities": ["entity1", "entity2"],\n "summary": "overview of relationship network"\n}`,i=await this.llm.getJSON(r,JSON.stringify(n.slice(0,40),null,2),{temperature:.3});return{holon:e,lens:t,itemCount:n.length,relationships:i,timestamp:Date.now()}}async findSimilar(e,t=null,n=null,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{limit:r=10,threshold:i=.5,useEmbeddings:a=!0}=s;if(a&&this.embeddings&&t&&n)return this.embeddings.findSimilar(e,t,n,{limit:r,threshold:i});if(!t)throw new Error("Holon required for LLM-based similarity");const o=n?[n]:["projects","quests","events","resources","default"];let l=[];for(const u of o)try{const e=await this.holosphere.getAll(t,u);l.push(...e.map(e=>({...e,_lens:u})))}catch{}if(0===l.length)return[];const c=`Find items most similar to the reference item.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nConsider:\n1. Topic/theme similarity\n2. Goal alignment\n3. Participant overlap\n4. Resource requirements\n5. Timeline compatibility\n\nReturn JSON array of similar items with similarity scores:\n[\n {\n "item": {item object},\n "similarity": 0.0-1.0,\n "reasons": ["reason1"]\n }\n]\n\nOrder by similarity descending. Max ${r} items with similarity >= ${i}.`;return(await this.llm.getJSON(c,JSON.stringify(l.slice(0,50),null,2),{temperature:.2})).slice(0,r).filter(e=>e.similarity>=i)}async buildGraph(e,t){const n=await this.discoverRelationships(e,t),s=new Map,r=[];for(const i of n.relationships?.relationships||[])s.has(i.item1.id)||s.set(i.item1.id,{id:i.item1.id,label:i.item1.title}),s.has(i.item2.id)||s.set(i.item2.id,{id:i.item2.id,label:i.item2.title}),r.push({source:i.item1.id,target:i.item2.id,type:i.type,weight:i.strength});return{nodes:Array.from(s.values()),edges:r,clusters:n.relationships?.clusters||[]}}async findCrossHolonRelationships(e,t){if(!this.holosphere)throw new Error("HoloSphere instance required");const n={};for(const r of e.slice(0,5))try{const e=await this.holosphere.getAll(r,t);e.length>0&&(n[r]=e.slice(0,15))}catch{}if(Object.keys(n).length<2)return{message:"Need at least 2 holons with data"};const s=`Find relationships between items across different geographic regions.\n\nRegions and their data:\n${JSON.stringify(n,null,2)}\n\nIdentify:\n1. Cross-region collaborations\n2. Shared themes across regions\n3. Potential synergies\n4. Knowledge transfer opportunities\n\nReturn JSON:\n{\n "cross_relationships": [\n {\n "holon1": "id",\n "item1": "item_id",\n "holon2": "id",\n "item2": "item_id",\n "type": "type",\n "potential": "collaboration|knowledge_share|synergy"\n }\n ],\n "shared_themes": [{"theme": "theme", "holons": ["id1", "id2"]}],\n "opportunities": ["opp1"]\n}`;return this.llm.getJSON(s,"",{temperature:.4})}async suggestConnections(e,t,n){const s=await this.findSimilar(e,t,n,{limit:10}),r=`Based on similar items found, suggest specific actions to create connections.\n\nReference item:\n${JSON.stringify(e,null,2)}\n\nSimilar items found:\n${JSON.stringify(s,null,2)}\n\nSuggest:\n1. Collaboration opportunities\n2. Resource sharing possibilities\n3. Joint initiatives\n4. Knowledge exchange\n\nReturn JSON:\n{\n "collaborations": [{"with": "item_id", "action": "suggested action"}],\n "resource_sharing": [{"items": ["id1", "id2"], "resource": "what to share"}],\n "initiatives": [{"description": "joint initiative", "participants": ["id1"]}],\n "knowledge_exchange": [{"from": "id", "to": "id", "topic": "topic"}]\n}`;return this.llm.getJSON(r,"",{temperature:.5})}async detectPatterns(e,t){const n=await this.discoverRelationships(e,t),s=`Analyze relationships and detect higher-level patterns.\n\nRelationships:\n${JSON.stringify(n.relationships,null,2)}\n\nDetect:\n1. Hub-spoke patterns (central connectors)\n2. Cluster patterns (tight groups)\n3. Bridge patterns (connecting different groups)\n4. Chain patterns (sequential relationships)\n5. Cyclical patterns (mutual dependencies)\n\nReturn JSON:\n{\n "patterns": [\n {\n "type": "hub|cluster|bridge|chain|cycle",\n "description": "pattern description",\n "items": ["id1", "id2"],\n "significance": "why this matters"\n }\n ],\n "network_structure": "description of overall structure",\n "recommendations": ["rec1"]\n}`;return this.llm.getJSON(s,"",{temperature:.3})}}class TaskBreakdown{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async breakdown(e,t,n,s={}){if(!e||!e.id)throw new Error("Item must have an id property");const{depth:r=2,stepsPerLevel:i={min:3,max:5},useContext:a=!0,storeResults:o=!0,dependencyField:l="dependencies",parentField:c="parent"}=s,u="number"==typeof i?{min:i,max:i}:i;let d=[];if(a&&this.holosphere)try{d=(await this.holosphere.getAll(t,n)).filter(t=>t.id!==e.id).slice(0,10)}catch{}let f=null;if(this.holosphere)try{f=await this.holosphere.getSchema(n)}catch{}const h=await this._breakdownRecursive(e,t,n,r,u,d,f,l,c,o,0);return{original:e,holonId:t,lensName:n,breakdown:h,totalSubtasks:this._countSubtasks(h),maxDepth:r,timestamp:Date.now()}}async _breakdownRecursive(e,t,n,s,r,i,a,o,l,c,u){if(u>=s)return{item:e,children:[],depth:u};const d=await this._generateSubtasks(e,i,a,r,o,l);if(c&&this.holosphere&&d.length>0){for(const e of d)try{await this.holosphere.write(t,n,e)}catch(h){console.warn(`Failed to store subtask ${e.id}:`,h.message)}if(e._meta?.childTasks!==d.map(e=>e.id))try{await this.holosphere.update(t,n,e.id,{_meta:{...e._meta,childTasks:d.map(e=>e.id),breakdownTimestamp:Date.now()}})}catch{}}const f=[];for(const p of d){const e=await this._breakdownRecursive(p,t,n,s,r,i,a,o,l,c,u+1);f.push(e)}return{item:e,children:f,depth:u}}async _generateSubtasks(e,t,n,s,r,i){const{min:a,max:o}=s,l=`You are a task decomposition expert. Break down the given task/quest into ${a}-${o} concrete, actionable subtasks.\n\nEach subtask should:\n1. Be a clear, specific action\n2. Be smaller and more manageable than the parent\n3. Together with siblings, fully accomplish the parent task\n4. Have a unique ID (format: parentId-1, parentId-2, etc.)\n5. Reference the parent task in the "${i}" field\n6. List any dependencies on sibling tasks in "${r}" array\n\n${n?`Follow this schema structure:\n${JSON.stringify(n,null,2)}`:""}\n\n${t.length>0?`Consider these existing items for context and avoid duplication:\n${JSON.stringify(t.slice(0,5),null,2)}`:""}\n\nReturn a JSON array of subtasks. Each subtask must have:\n- id: unique identifier (parentId-1, parentId-2, etc.)\n- title/name: clear action title\n- description: what needs to be done\n- ${i}: reference to parent id\n- ${r}: array of sibling task ids this depends on (empty if first task)\n- status: "pending"\n- Any other relevant fields from the parent schema\n\nExample output format:\n[\n {\n "id": "parent-1",\n "title": "First subtask",\n "description": "Details...",\n "${i}": "parentId",\n "${r}": [],\n "status": "pending"\n },\n {\n "id": "parent-2",\n "title": "Second subtask (depends on first)",\n "description": "Details...",\n "${i}": "parentId",\n "${r}": ["parent-1"],\n "status": "pending"\n }\n]`,c=`Break down this task into ${a}-${o} subtasks:\n\n${JSON.stringify(e,null,2)}`;try{return(await this.llm.getJSON(l,c,{temperature:.4,maxTokens:2e3})).map((t,n)=>({...t,id:t.id||`${e.id}-${n+1}`,[i]:e.id,[r]:t[r]||[],status:t.status||"pending",_meta:{...t._meta,generatedFrom:e.id,generatedAt:Date.now(),depth:(e._meta?.depth||0)+1}}))}catch(u){return console.error("Failed to generate subtasks:",u),[]}}_countSubtasks(e){return e.children&&0!==e.children.length?e.children.length+e.children.reduce((e,t)=>e+this._countSubtasks(t),0):0}flatten(e){const t=[],n=e=>{if(e.item&&t.push(e.item),e.children)for(const t of e.children)n(t)};return e.breakdown&&n(e.breakdown),t}getDependencyOrder(e){return this.flatten(e).sort((e,t)=>{const n=e._meta?.depth||0,s=t._meta?.depth||0;if(n!==s)return n-s;if((t.dependencies||[]).includes(e.id))return-1;return(e.dependencies||[]).includes(t.id)?1:0})}async suggestStrategy(e){return this.llm.getJSON('You are a task decomposition expert. Analyze this task and suggest the best breakdown strategy.\n\nConsider:\n1. Task complexity\n2. Recommended depth (1-4 levels)\n3. Recommended subtasks per level (2-7)\n4. Key areas to focus on\n5. Potential dependencies between subtasks\n\nReturn JSON:\n{\n "complexity": "simple|moderate|complex|very_complex",\n "recommendedDepth": n,\n "recommendedStepsPerLevel": {"min": n, "max": n},\n "focusAreas": ["area1", "area2"],\n "potentialChallenges": ["challenge1"],\n "estimatedTotalSubtasks": n,\n "reasoning": "explanation"\n}',JSON.stringify(e,null,2),{temperature:.3})}async rebalance(e,t={}){const{targetStepsPerLevel:n={min:3,max:5}}=t,s=this.flatten(e),r=`You are a task organization expert. Rebalance these tasks to have ${n.min}-${n.max} items per level.\n\nCurrent tasks:\n${JSON.stringify(s,null,2)}\n\nReorganize by:\n1. Merging tasks that are too granular\n2. Splitting tasks that are too large\n3. Maintaining proper dependency chains\n4. Keeping the same overall scope\n\nReturn JSON with the rebalanced structure:\n{\n "tasks": [...],\n "changes": [{"type": "merge|split|move", "description": "..."}],\n "summary": "what changed"\n}`;return this.llm.getJSON(r,"",{temperature:.3})}async getProgress(e,t,n){if(!this.holosphere)throw new Error("HoloSphere instance required");const s=await this.holosphere.getAll(e,t),r=s.find(e=>e.id===n);if(!r)throw new Error(`Item ${n} not found`);const i=this._findDescendants(n,s),a=i.length,o=i.filter(e=>"completed"===e.status||"done"===e.status).length,l=i.filter(e=>"in_progress"===e.status||"active"===e.status).length,c=a-o-l;return{itemId:n,title:r.title||r.name,total:a,completed:o,inProgress:l,pending:c,percentComplete:a>0?Math.round(o/a*100):0,blockers:this._findBlockers(i),nextUp:this._findNextTasks(i)}}_findDescendants(e,t,n="parent"){const s=[],r=t.filter(t=>t[n]===e);for(const i of r)s.push(i),s.push(...this._findDescendants(i.id,t,n));return s}_findBlockers(e,t="dependencies"){return e.filter(n=>{const s=n[t]||[];return 0!==s.length&&s.some(t=>{const n=e.find(e=>e.id===t);return n&&"completed"!==n.status&&"done"!==n.status})}).map(e=>({id:e.id,title:e.title||e.name,blockedBy:e[t]}))}_findNextTasks(e,t="dependencies"){return e.filter(n=>{if("completed"===n.status||"done"===n.status)return!1;if("in_progress"===n.status||"active"===n.status)return!1;const s=n[t]||[];return 0===s.length||s.every(t=>{const n=e.find(e=>e.id===t);return!n||"completed"===n.status||"done"===n.status})}).slice(0,5).map(e=>({id:e.id,title:e.title||e.name,description:e.description}))}}class H3AI{constructor(e,t=null){this.llm=e,this.holosphere=t}setHoloSphere(e){this.holosphere=e}async suggestResolution(e,t={}){const{currentResolution:n=null,context:s=null}=t,r=`You are a geospatial planning expert. Analyze this item and suggest the optimal H3 hexagonal resolution (0-15) for organizing it.\n\nH3 Resolution Guide:\n- Resolution 0-2: Continental/country scale (thousands of km)\n- Resolution 3-4: Regional/state scale (hundreds of km)\n- Resolution 5-6: Metropolitan/city scale (tens of km)\n- Resolution 7-8: District/neighborhood scale (km)\n- Resolution 9-10: Block/street scale (hundreds of meters)\n- Resolution 11-12: Building/lot scale (tens of meters)\n- Resolution 13-15: Room/precise scale (meters)\n\nConsider:\n1. Geographic scope mentioned in the item\n2. Number of potential participants/stakeholders\n3. Type of activity (local vs regional)\n4. Resource requirements and logistics\n5. Similar projects' typical scale\n\n${null!==n?`Current resolution: ${n}`:""}\n${s?`Context:\n${JSON.stringify(s,null,2)}`:""}\n\nReturn JSON:\n{\n "recommendedResolution": n,\n "reasoning": "why this resolution",\n "alternativeResolutions": [{"resolution": n, "useCase": "when to use"}],\n "geographicScope": "description of area covered",\n "scaleSuggestions": {\n "expansion": {"resolution": n, "reason": "when to expand"},\n "contraction": {"resolution": n, "reason": "when to focus"}\n }\n}`;return this.llm.getJSON(r,JSON.stringify(e,null,2),{temperature:.3})}async analyzeDistribution(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{includeChildren:s=!0,maxChildren:r=20}=n,i=await this.holosphere.getAll(e,t),a={};if(s&&h3__namespace.isValidCell(e)){const n=h3__namespace.getResolution(e);if(n<15){const s=h3__namespace.cellToChildren(e,n+1);for(const e of s.slice(0,r))try{const n=await this.holosphere.getAll(e,t);n.length>0&&(a[e]={count:n.length,sample:n.slice(0,3)})}catch{}}}const o=`You are a geospatial analyst. Analyze the distribution of data across this H3 hexagonal region.\n\nParent holon: ${e}\nResolution: ${h3__namespace.isValidCell(e)?h3__namespace.getResolution(e):"N/A"}\nParent data count: ${i.length}\nChildren with data: ${Object.keys(a).length}\n\nAnalyze:\n1. Data density and distribution patterns\n2. Geographic hotspots and cold spots\n3. Coverage gaps\n4. Clustering patterns\n5. Recommendations for better coverage\n\nReturn JSON:\n{\n "distribution": {\n "pattern": "clustered|uniform|sparse|concentrated",\n "density": "high|medium|low",\n "coverage": 0.0-1.0\n },\n "hotspots": [{"holonId": "id", "reason": "why"}],\n "gaps": [{"description": "gap description", "suggestedAction": "what to do"}],\n "clusters": [{"theme": "cluster theme", "holons": ["id1"]}],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`,l=`Parent data sample:\n${JSON.stringify(i.slice(0,10),null,2)}\n\nChildren distribution:\n${JSON.stringify(a,null,2)}`,c=await this.llm.getJSON(o,l,{temperature:.3});return{holonId:e,lensName:t,resolution:h3__namespace.isValidCell(e)?h3__namespace.getResolution(e):null,parentDataCount:i.length,childrenAnalyzed:Object.keys(a).length,analysis:c,timestamp:Date.now()}}async findNeighborRelevance(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(e))throw new Error("Invalid H3 cell");const{ringSize:s=1,relevanceThreshold:r=.5}=n,i=await this.holosphere.getAll(e,t),a=h3__namespace.gridDisk(e,s).filter(t=>t!==e),o={};for(const d of a)try{const e=await this.holosphere.getAll(d,t);e.length>0&&(o[d]=e.slice(0,5))}catch{}if(0===Object.keys(o).length)return{holonId:e,neighbors:[],message:"No data found in neighboring cells"};const l=`You are a geospatial relevance analyst. Find items in neighboring H3 cells that are relevant to the center cell's data.\n\nCenter cell: ${e}\nRing size: ${s} (immediate neighbors)\n\nConsider:\n1. Thematic overlap\n2. Potential collaborations\n3. Shared resources\n4. Cross-boundary projects\n5. Geographic continuity of activities\n\nReturn JSON:\n{\n "relevantNeighbors": [\n {\n "holonId": "neighbor_id",\n "relevanceScore": 0.0-1.0,\n "relevantItems": [{"id": "item_id", "reason": "why relevant"}],\n "collaborationPotential": "description"\n }\n ],\n "crossBoundaryOpportunities": [\n {\n "description": "opportunity",\n "involvedHolons": ["id1", "id2"],\n "suggestedAction": "what to do"\n }\n ],\n "geographicPatterns": ["pattern1"],\n "summary": "overview"\n}`,c=`Center cell data:\n${JSON.stringify(i.slice(0,10),null,2)}\n\nNeighbor data:\n${JSON.stringify(o,null,2)}`,u=await this.llm.getJSON(l,c,{temperature:.4});return u.relevantNeighbors&&(u.relevantNeighbors=u.relevantNeighbors.filter(e=>e.relevanceScore>=r)),{holonId:e,lensName:t,ringSize:s,neighborsAnalyzed:Object.keys(o).length,analysis:u,timestamp:Date.now()}}async suggestGeographicScope(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(t))throw new Error("Invalid H3 cell");const r=h3__namespace.getResolution(t);let i=[];if(r>0){const e=h3__namespace.cellToParent(t,r-1);try{i=await this.holosphere.getAll(e,n)}catch{}}let a=[];if(r<15){const e=h3__namespace.cellToChildren(t,r+1);for(const t of e.slice(0,7))try{const e=await this.holosphere.getAll(t,n);a.push(...e.slice(0,2))}catch{}}const o=`You are a geographic scope advisor. Analyze whether this item should expand to a larger region (parent holon) or focus on smaller sub-regions (children holons).\n\nCurrent holon: ${t}\nCurrent resolution: ${r}\n\nFactors to consider:\n1. Item's stated scope and goals\n2. Current participation/activity level\n3. Resource requirements\n4. Similar activities in parent/children\n5. Natural geographic boundaries\n\nReturn JSON:\n{\n "currentScopeAssessment": {\n "appropriate": true/false,\n "reasoning": "why"\n },\n "expansionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why expand",\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "contractionRecommendation": {\n "recommended": true/false,\n "targetResolution": n,\n "reasoning": "why contract",\n "suggestedFocusAreas": ["description"],\n "benefits": ["benefit1"],\n "risks": ["risk1"]\n },\n "optimalAction": "expand|contract|maintain",\n "summary": "recommendation summary"\n}`,l=`Item to analyze:\n${JSON.stringify(e,null,2)}\n\nParent region data (${i.length} items):\n${JSON.stringify(i.slice(0,5),null,2)}\n\nChildren regions data (${a.length} items):\n${JSON.stringify(a.slice(0,5),null,2)}`;return this.llm.getJSON(o,l,{temperature:.3})}async analyzeCoverage(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(e))throw new Error("Invalid H3 cell");const{targetResolution:s=null}=n,r=h3__namespace.getResolution(e),i=s||Math.min(r+1,15),a=h3__namespace.cellToChildren(e,i),o={total:a.length,withData:0,withoutData:0,dataDistribution:{}},l=[],c=[];for(const f of a)try{const e=await this.holosphere.getAll(f,t);e.length>0?(o.withData++,o.dataDistribution[f]=e.length,l.push({holon:f,count:e.length})):(o.withoutData++,c.push(f))}catch{o.withoutData++,c.push(f)}const u=`You are a geographic coverage analyst. Analyze the data coverage in this H3 region.\n\nRegion: ${e}\nResolution: ${r}\nChild resolution analyzed: ${i}\nTotal children: ${o.total}\nChildren with data: ${o.withData}\nChildren without data: ${o.withoutData}\nCoverage ratio: ${(o.withData/o.total*100).toFixed(1)}%\n\nAnalyze:\n1. Coverage patterns\n2. Potential reasons for gaps\n3. Priority areas for expansion\n4. Whether gaps are concerning or expected\n\nReturn JSON:\n{\n "coverageScore": 0.0-1.0,\n "coverageQuality": "excellent|good|moderate|poor|minimal",\n "patterns": {\n "type": "clustered|scattered|peripheral|central|uniform",\n "description": "pattern description"\n },\n "gaps": {\n "count": n,\n "significance": "high|medium|low",\n "likelyReasons": ["reason1"],\n "priorityAreas": ["description of areas to focus"]\n },\n "recommendations": [\n {\n "action": "what to do",\n "priority": "high|medium|low",\n "targetArea": "description"\n }\n ],\n "summary": "overview"\n}`,d=await this.llm.getJSON(u,"",{temperature:.3});return{holonId:e,lensName:t,resolution:r,childResolution:i,coverage:{...o,ratio:o.withData/o.total},childrenWithData:l.slice(0,10),gapCount:c.length,analysis:d,timestamp:Date.now()}}async crossResolutionInsights(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(e))throw new Error("Invalid H3 cell");const{levels:s=3}=n,r=h3__namespace.getResolution(e),i={},a=await this.holosphere.getAll(e,t);i[r]={holon:e,count:a.length,sample:a.slice(0,5)};let o=e;for(let c=0;c<s&&h3__namespace.getResolution(o)>0;c++){const e=h3__namespace.getResolution(o)-1;o=h3__namespace.cellToParent(o,e);try{const n=await this.holosphere.getAll(o,t);i[e]={holon:o,count:n.length,sample:n.slice(0,5)}}catch{}}if(r<15){const n=r+1,s=h3__namespace.cellToChildren(e,n);let a=0;const o=[];for(const e of s.slice(0,7))try{const n=await this.holosphere.getAll(e,t);a+=n.length,n.length>0&&o.push(...n.slice(0,2))}catch{}i[n]={holon:`${s.length} children`,count:a,sample:o.slice(0,5)}}const l=`You are a multi-scale geographic analyst. Find patterns that emerge across different H3 resolutions.\n\nStarting holon: ${e}\nResolutions analyzed: ${Object.keys(i).sort().join(", ")}\n\nData at each resolution:\n${JSON.stringify(i,null,2)}\n\nAnalyze:\n1. How themes evolve across scales\n2. What appears only at certain resolutions\n3. Aggregation patterns (local vs regional)\n4. Scale-dependent opportunities\n5. Optimal resolution for different activities\n\nReturn JSON:\n{\n "scalePatterns": [\n {\n "pattern": "description",\n "visibleAt": [resolution_numbers],\n "significance": "why this matters"\n }\n ],\n "themeEvolution": {\n "localThemes": ["themes at fine resolution"],\n "regionalThemes": ["themes at coarse resolution"],\n "consistentThemes": ["themes across all scales"]\n },\n "optimalResolutions": {\n "forCollaboration": n,\n "forResources": n,\n "forCommunity": n,\n "reasoning": "why"\n },\n "insights": ["insight1"],\n "recommendations": ["rec1"],\n "summary": "overview"\n}`;return this.llm.getJSON(l,"",{temperature:.4})}async suggestMigration(e,t,n,s={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(t))throw new Error("Invalid H3 cell");const{searchRadius:r=2}=s,i=h3__namespace.gridDisk(t,r),a={};for(const d of i)if(d!==t)try{const e=await this.holosphere.getAll(d,n);e.length>0&&(a[d]={count:e.length,sample:e.slice(0,3)})}catch{}const o=h3__namespace.getResolution(t);let l=null;if(o>0){const e=h3__namespace.cellToParent(t,o-1);try{const t=await this.holosphere.getAll(e,n);l={holon:e,count:t.length,sample:t.slice(0,3)}}catch{}}const c=`You are a geographic placement advisor. Determine if this item would be better suited in a different H3 cell.\n\nCurrent location: ${t}\nCurrent resolution: ${o}\n\nConsider:\n1. Thematic fit with existing data in each cell\n2. Geographic scope of the item\n3. Collaboration opportunities\n4. Resource proximity\n5. Community alignment\n\nReturn JSON:\n{\n "currentFit": {\n "score": 0.0-1.0,\n "reasoning": "why current location is/isn't appropriate"\n },\n "migrationRecommended": true/false,\n "suggestedDestinations": [\n {\n "holonId": "cell_id",\n "fitScore": 0.0-1.0,\n "reasoning": "why this location",\n "benefits": ["benefit1"],\n "drawbacks": ["drawback1"]\n }\n ],\n "stayReasons": ["reason to stay if applicable"],\n "moveReasons": ["reason to move if applicable"],\n "recommendation": "stay|move|duplicate",\n "summary": "final recommendation"\n}`,u=`Item to place:\n${JSON.stringify(e,null,2)}\n\nNearby cells with data:\n${JSON.stringify(a,null,2)}\n\n${l?`Parent cell data:\n${JSON.stringify(l,null,2)}`:""}`;return this.llm.getJSON(c,u,{temperature:.3})}async generateGeographicReport(e,t={}){if(!this.holosphere)throw new Error("HoloSphere instance required");const{lenses:n=["projects","quests","events","resources","default"]}=t,s={};for(const o of n)try{const t=await this.holosphere.getAll(e,o);t.length>0&&(s[o]={count:t.length,sample:t.slice(0,5)})}catch{}let r={};if(h3__namespace.isValidCell(e)){const t=h3__namespace.getResolution(e),[n,s]=h3__namespace.cellToLatLng(e),i=h3__namespace.cellToBoundary(e);r={resolution:t,center:{lat:n,lng:s},areaKm2:h3__namespace.cellArea(e,"km2"),vertexCount:i.length}}const i=`You are a regional activity reporter. Generate a comprehensive report on geographic activity in this H3 region.\n\nRegion: ${e}\nGeographic context: ${JSON.stringify(r,null,2)}\nData available in ${Object.keys(s).length} categories\n\nGenerate a report covering:\n1. Executive summary\n2. Activity overview by category\n3. Key highlights and achievements\n4. Geographic patterns\n5. Opportunities and challenges\n6. Recommendations\n\nReturn JSON:\n{\n "title": "Region Report Title",\n "executiveSummary": "2-3 sentence overview",\n "activityOverview": {\n "totalItems": n,\n "categorySummaries": {"lens": "summary"}\n },\n "highlights": [\n {"title": "highlight", "description": "details", "category": "lens"}\n ],\n "geographicPatterns": ["pattern1"],\n "strengths": ["strength1"],\n "challenges": ["challenge1"],\n "opportunities": ["opportunity1"],\n "recommendations": [\n {"priority": "high|medium|low", "action": "what to do", "rationale": "why"}\n ],\n "metrics": {\n "activityLevel": "high|medium|low",\n "diversity": "high|medium|low",\n "growth": "growing|stable|declining"\n }\n}`,a=await this.llm.getJSON(i,JSON.stringify(s,null,2),{temperature:.4,maxTokens:2e3});return{holonId:e,geoContext:r,lensesAnalyzed:Object.keys(s),totalItems:Object.values(s).reduce((e,t)=>e+t.count,0),report:a,timestamp:Date.now()}}async findGeographicClusters(e,t,n={}){if(!this.holosphere)throw new Error("HoloSphere instance required");if(!h3__namespace.isValidCell(e))throw new Error("Invalid H3 cell");const{clusterResolution:s=null}=n,r=h3__namespace.getResolution(e),i=s||Math.min(r+1,15),a=h3__namespace.cellToChildren(e,i),o={};for(const u of a)try{const e=await this.holosphere.getAll(u,t);e.length>0&&(o[u]=e)}catch{}if(Object.keys(o).length<2)return{holonId:e,clusters:[],message:"Not enough data for clustering"};const l=`You are a geographic clustering expert. Find thematic clusters in this spatial data.\n\nRegion: ${e}\nResolution analyzed: ${i}\nCells with data: ${Object.keys(o).length}\n\nIdentify:\n1. Thematic clusters (cells with similar content)\n2. Activity clusters (cells with related activities)\n3. Isolated cells (unique content)\n4. Potential connections between clusters\n\nReturn JSON:\n{\n "clusters": [\n {\n "name": "cluster name",\n "theme": "what unifies this cluster",\n "cells": ["cell_id1", "cell_id2"],\n "strength": 0.0-1.0,\n "characteristics": ["char1"]\n }\n ],\n "isolatedCells": [\n {"cellId": "id", "uniqueAspect": "what makes it unique"}\n ],\n "interClusterConnections": [\n {"cluster1": "name", "cluster2": "name", "connection": "how related"}\n ],\n "spatialPatterns": ["pattern1"],\n "recommendations": ["rec1"]\n}`,c=await this.llm.getJSON(l,JSON.stringify(o,null,2),{temperature:.4});return{holonId:e,lensName:t,clusterResolution:i,cellsAnalyzed:Object.keys(o).length,analysis:c,timestamp:Date.now()}}async analyzeGeographicImpact(e,t,n,s={}){if(!h3__namespace.isValidCell(t))throw new Error("Invalid H3 cell");const r=h3__namespace.getResolution(t),[i,a]=h3__namespace.cellToLatLng(t),o=h3__namespace.cellArea(t,"km2");let l=null;if(r>0){const e=h3__namespace.cellToParent(t,Math.max(0,r-2));l={holon:e,resolution:r-2,areaKm2:h3__namespace.cellArea(e,"km2")}}const c=`You are a geographic impact analyst. Analyze the geographic reach and impact of this item.\n\nItem location: ${t}\nResolution: ${r}\nCenter: ${i.toFixed(4)}, ${a.toFixed(4)}\nArea: ${o.toFixed(2)} km²\n\n${l?`Broader region: ${l.areaKm2.toFixed(2)} km²`:""}\n\nAnalyze:\n1. Direct impact area (immediate cell)\n2. Indirect impact area (spillover effects)\n3. Potential reach (if expanded)\n4. Geographic barriers/enablers\n5. Network effects\n\nReturn JSON:\n{\n "directImpact": {\n "areaKm2": n,\n "description": "direct impact area",\n "affectedPopulation": "estimate or N/A"\n },\n "indirectImpact": {\n "estimatedReach": n,\n "mechanisms": ["how impact spreads"],\n "neighboringAreas": ["affected areas"]\n },\n "potentialReach": {\n "ifExpanded": {\n "maxAreaKm2": n,\n "optimalResolution": n,\n "limitingFactors": ["factor1"]\n }\n },\n "geographicFactors": {\n "enablers": ["what helps geographic spread"],\n "barriers": ["what limits spread"]\n },\n "impactScore": {\n "local": 0.0-1.0,\n "regional": 0.0-1.0,\n "network": 0.0-1.0\n },\n "recommendations": ["how to increase impact"],\n "summary": "impact overview"\n}`;return this.llm.getJSON(c,JSON.stringify(e,null,2),{temperature:.3})}}const NETWORKS={ethereum:{name:"Ethereum Mainnet",chainId:1,rpc:"https://eth.llamarpc.com",explorer:"https://etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},polygon:{name:"Polygon Mainnet",chainId:137,rpc:"https://polygon-rpc.com",explorer:"https://polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"mainnet"},arbitrum:{name:"Arbitrum One",chainId:42161,rpc:"https://arb1.arbitrum.io/rpc",explorer:"https://arbiscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},base:{name:"Base",chainId:8453,rpc:"https://mainnet.base.org",explorer:"https://basescan.org",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},optimism:{name:"Optimism",chainId:10,rpc:"https://mainnet.optimism.io",explorer:"https://optimistic.etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"mainnet"},avalanche:{name:"Avalanche C-Chain",chainId:43114,rpc:"https://api.avax.network/ext/bc/C/rpc",explorer:"https://snowtrace.io",currency:{name:"AVAX",symbol:"AVAX",decimals:18},type:"mainnet"},bsc:{name:"BNB Smart Chain",chainId:56,rpc:"https://bsc-dataseed.binance.org",explorer:"https://bscscan.com",currency:{name:"BNB",symbol:"BNB",decimals:18},type:"mainnet"},sepolia:{name:"Sepolia",chainId:11155111,rpc:"https://rpc.sepolia.org",explorer:"https://sepolia.etherscan.io",currency:{name:"Sepolia ETH",symbol:"ETH",decimals:18},type:"testnet",faucet:"https://sepoliafaucet.com"},goerli:{name:"Goerli",chainId:5,rpc:"https://rpc.goerli.eth.gateway.fm",explorer:"https://goerli.etherscan.io",currency:{name:"Goerli ETH",symbol:"ETH",decimals:18},type:"testnet",faucet:"https://goerlifaucet.com"},mumbai:{name:"Polygon Mumbai",chainId:80001,rpc:"https://rpc-mumbai.maticvigil.com",explorer:"https://mumbai.polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"testnet",faucet:"https://faucet.polygon.technology"},amoy:{name:"Polygon Amoy",chainId:80002,rpc:"https://rpc-amoy.polygon.technology",explorer:"https://amoy.polygonscan.com",currency:{name:"MATIC",symbol:"MATIC",decimals:18},type:"testnet",faucet:"https://faucet.polygon.technology"},arbitrumSepolia:{name:"Arbitrum Sepolia",chainId:421614,rpc:"https://sepolia-rollup.arbitrum.io/rpc",explorer:"https://sepolia.arbiscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},baseSepolia:{name:"Base Sepolia",chainId:84532,rpc:"https://sepolia.base.org",explorer:"https://sepolia.basescan.org",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},optimismSepolia:{name:"Optimism Sepolia",chainId:11155420,rpc:"https://sepolia.optimism.io",explorer:"https://sepolia-optimism.etherscan.io",currency:{name:"Ether",symbol:"ETH",decimals:18},type:"testnet"},hardhat:{name:"Hardhat Local",chainId:31337,rpc:"http://127.0.0.1:8545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"},anvil:{name:"Anvil Local",chainId:31337,rpc:"http://127.0.0.1:8545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"},ganache:{name:"Ganache Local",chainId:1337,rpc:"http://127.0.0.1:7545",explorer:null,currency:{name:"Ether",symbol:"ETH",decimals:18},type:"local"}};function getNetwork(e){if("string"==typeof e)return NETWORKS[e]||null;for(const[t,n]of Object.entries(NETWORKS))if(n.chainId===e)return{...n,key:t};return null}function getNetworksByType(e){return Object.fromEntries(Object.entries(NETWORKS).filter(([t,n])=>n.type===e))}function listNetworks(){return Object.keys(NETWORKS)}function isNetworkSupported(e){return e in NETWORKS}function getTxUrl(e,t){const n=NETWORKS[e];return n?.explorer?`${n.explorer}/tx/${t}`:null}function getAddressUrl(e,t){const n=NETWORKS[e];return n?.explorer?`${n.explorer}/address/${t}`:null}const networks=Object.freeze(Object.defineProperty({__proto__:null,NETWORKS:NETWORKS,default:NETWORKS,getAddressUrl:getAddressUrl,getNetwork:getNetwork,getNetworksByType:getNetworksByType,getTxUrl:getTxUrl,isNetworkSupported:isNetworkSupported,listNetworks:listNetworks},Symbol.toStringTag,{value:"Module"}));class ChainManager{constructor(e={}){this.config=e,this.provider=null,this.signer=null,this.network=null,this.networkName=null,this.ethers=null,this._initialized=!1}async _loadEthers(){if(!this.ethers){const e=await Promise.resolve().then(()=>require("./index-COpLk9gL.cjs"));this.ethers=e}return this.ethers}async connect(e,t,n){const s=await this._loadEthers();if(!isNetworkSupported(e)&&!n)throw new Error(`Unsupported network: ${e}. Use a custom rpcUrl or choose from: ${Object.keys(NETWORKS).join(", ")}`);const r=getNetwork(e)||{chainId:0,name:e},i=n||r.rpc;if(this.provider=new s.JsonRpcProvider(i,{chainId:r.chainId,name:r.name}),await this.provider.ready,this.network=await this.provider.getNetwork(),this.networkName=e,t){const e=t.startsWith("0x")?t:`0x${t}`;this.signer=new s.Wallet(e,this.provider)}return this._initialized=!0,{provider:this.provider,signer:this.signer,network:this.network,networkName:this.networkName,config:r}}async connectBrowser(e){const t=await this._loadEthers();if("undefined"==typeof window||!window.ethereum)throw new Error("No browser wallet detected. Please install MetaMask or another Web3 wallet.");if(await window.ethereum.request({method:"eth_requestAccounts"}),this.provider=new t.BrowserProvider(window.ethereum),this.signer=await this.provider.getSigner(),this.network=await this.provider.getNetwork(),e&&isNetworkSupported(e)){const t=getNetwork(e);this.network.chainId!==BigInt(t.chainId)&&await this.switchNetwork(e)}const n=await this.signer.getAddress();return this._initialized=!0,{provider:this.provider,signer:this.signer,network:this.network,address:n}}async switchNetwork(e){if("undefined"==typeof window||!window.ethereum)throw new Error("Network switching requires a browser wallet");const t=getNetwork(e);if(!t)throw new Error(`Unknown network: ${e}`);const n="0x"+t.chainId.toString(16);try{await window.ethereum.request({method:"wallet_switchEthereumChain",params:[{chainId:n}]})}catch(r){if(4902!==r.code)throw r;await window.ethereum.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:t.name,nativeCurrency:t.currency,rpcUrls:[t.rpc],blockExplorerUrls:t.explorer?[t.explorer]:[]}]})}const s=await this._loadEthers();this.provider=new s.BrowserProvider(window.ethereum),this.signer=await this.provider.getSigner(),this.network=await this.provider.getNetwork(),this.networkName=e}getProvider(){return this._requireInitialized(),this.provider}getSigner(){if(this._requireInitialized(),!this.signer)throw new Error("No signer available. Connect with a private key or use connectBrowser().");return this.signer}async getAddress(){return this.getSigner().getAddress()}async getBalance(e){this._requireInitialized();const t=await this._loadEthers(),n=e||(this.signer?await this.signer.getAddress():null);if(!n)throw new Error("No address provided and no signer available");const s=await this.provider.getBalance(n);return t.formatEther(s)}getNetworkConfig(){return this._requireInitialized(),getNetwork(this.networkName)}getChainId(){return this._requireInitialized(),Number(this.network.chainId)}isOnNetwork(e){if(!this._initialized)return!1;const t=getNetwork(e);return!!t&&this.getChainId()===t.chainId}async getContract(e,t,n=!0){this._requireInitialized();const s=await this._loadEthers(),r=n&&this.signer?this.signer:this.provider;return new s.Contract(e,t,r)}async deployContract(e,t,n=[]){if(this._requireInitialized(),!this.signer)throw new Error("Signer required for contract deployment");const s=new((await this._loadEthers()).ContractFactory)(e,t,this.signer),r=await s.deploy(...n);await r.waitForDeployment();const i=await r.getAddress(),a=r.deploymentTransaction();return{contract:r,address:i,deployTx:a,txHash:a?.hash}}async waitForTransaction(e,t=1){return this._requireInitialized(),this.provider.waitForTransaction(e,t)}async estimateGas(e){return this._requireInitialized(),this.provider.estimateGas(e)}async getGasPrice(){this._requireInitialized();const e=await this._loadEthers(),t=await this.provider.getFeeData();return{gasPrice:t.gasPrice?e.formatUnits(t.gasPrice,"gwei"):null,maxFeePerGas:t.maxFeePerGas?e.formatUnits(t.maxFeePerGas,"gwei"):null,maxPriorityFeePerGas:t.maxPriorityFeePerGas?e.formatUnits(t.maxPriorityFeePerGas,"gwei"):null}}async parseUnits(e,t="ether"){return(await this._loadEthers()).parseUnits(e.toString(),t)}async formatUnits(e,t="ether"){return(await this._loadEthers()).formatUnits(e,t)}_requireInitialized(){if(!this._initialized)throw new Error("ChainManager not initialized. Call connect() or connectBrowser() first.")}isConnected(){return this._initialized&&null!==this.provider}disconnect(){this.provider=null,this.signer=null,this.network=null,this.networkName=null,this._initialized=!1}}const SplitterABI=[{type:"constructor",inputs:[{name:"_owner",type:"address",internalType:"address"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"contractsByType",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createManagedContract",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createZonedContract",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"creatorUserId",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"debugGetContractAddress",inputs:[{name:"contractKey",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"externalContractSplitPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getContractAddresses",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"},{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"getContractInfo",inputs:[{name:"key",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getContractKeys",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"internalContractSplitPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isSplitterMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"percentages",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"routeCommand",inputs:[{name:"contractName",type:"string",internalType:"string"},{name:"data",type:"bytes",internalType:"bytes"}],outputs:[{name:"",type:"bool",internalType:"bool"},{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"nonpayable"},{type:"function",name:"setContractSplit",inputs:[{name:"_internalPercentage",type:"uint256",internalType:"uint256"},{name:"_externalPercentage",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setSplit",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"percentage",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ChildContractCreated",inputs:[{name:"parentContract",type:"address",indexed:!0,internalType:"address"},{name:"childContract",type:"address",indexed:!0,internalType:"address"},{name:"parentHolonId",type:"string",indexed:!1,internalType:"string"},{name:"childHolonId",type:"string",indexed:!1,internalType:"string"},{name:"childType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ChildRewardTriggered",inputs:[{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ContractSplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"internalPercentage",type:"uint256",indexed:!1,internalType:"uint256"},{name:"externalPercentage",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsForwarded",inputs:[{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"address",indexed:!1,internalType:"address"},{name:"",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],ManagedABI=[{type:"constructor",inputs:[{name:"_creator",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"appreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getTokensOf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isManagedMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"maxAppreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setAppreciation",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_appreciationAmounts",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setUserAppreciation",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_appreciationAmount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalappreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],ZonedABI=[{type:"constructor",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_creator",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"},{name:"_nzones",type:"uint256",internalType:"uint256"},{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"a",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"addFederationMember",inputs:[{name:"federationId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addToZone",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"},{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addressToUserId",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"b",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"c",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"calculateRewards",inputs:[],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"factory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getZoneMembers",inputs:[{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isZonedMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"nzones",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"percentages",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeFromZone",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"rewards",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setRewardFunction",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_a",type:"uint256",internalType:"uint256"},{name:"_b",type:"uint256",internalType:"uint256"},{name:"_c",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"zone",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zonemembers",inputs:[{name:"",type:"uint256",internalType:"uint256"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],AppreciativeABI=[{type:"constructor",inputs:[{name:"_name",type:"string",internalType:"string"},{name:"creatorUserId",type:"string",internalType:"string"},{name:"_creator",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"},{name:"_membername",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addParent",inputs:[{name:"_parentaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addressToUserId",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"appreciate",inputs:[{name:"senderUserId",type:"string",internalType:"string"},{name:"_userId",type:"string",internalType:"string"},{name:"_percentage",type:"uint8",internalType:"uint8"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"appreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"changeName",inputs:[{name:"_address",type:"address",internalType:"address"},{name:"_name",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"changeOwner",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"depositEtherForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"depositTokenForUser",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_tokenAddress",type:"address",internalType:"address"},{name:"_amount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isAppreciativeMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isMember",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"listMembers",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address payable[]"}],stateMutability:"view"},{type:"function",name:"listParents",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"manifest",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"remainingappreciation",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"removeMember",inputs:[{name:"_memberaddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"resetAppreciation",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setAppreciation",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_percentages",type:"uint8[]",internalType:"uint8[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManifest",inputs:[{name:"_IPFSHash",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"toName",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalappreciation",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"version",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"AddedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"AppreciationGiven",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"fromUserId",type:"string",indexed:!1,internalType:"string"},{name:"toUserId",type:"string",indexed:!1,internalType:"string"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ChangedName",inputs:[{name:"namefrom",type:"string",indexed:!1,internalType:"string"},{name:"nameto",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsCascaded",inputs:[{name:"fromContract",type:"address",indexed:!0,internalType:"address"},{name:"toContract",type:"address",indexed:!0,internalType:"address"},{name:"fromHolonId",type:"string",indexed:!1,internalType:"string"},{name:"toHolonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"splitType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberRemoved",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RemovedMember",inputs:[{name:"member",type:"address",indexed:!1,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SplitConfigured",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"splitType",type:"string",indexed:!1,internalType:"string"},{name:"values",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"WeightChanged",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldWeight",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newWeight",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1}],abi=[{type:"constructor",inputs:[{name:"_owner",type:"address",internalType:"address"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_steepness",type:"uint256",internalType:"uint256"},{name:"_nzones",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"fallback",stateMutability:"payable"},{type:"receive",stateMutability:"payable"},{type:"function",name:"BASIS_POINTS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"WAD",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"addMember",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"addMembers",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"assignToZone",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"cancelElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"candidates",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"claim",inputs:[{name:"_userId",type:"string",internalType:"string"},{name:"_beneficiary",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"creator",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"electionActive",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"etherBalance",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"exteriorPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"factory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"finalizeElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"flavor",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"getCandidates",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getInteriorMembers",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getSize",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getTokensOf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"getZoneMembers",inputs:[{name:"_zone",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"getZoneWeights",inputs:[],outputs:[{name:"",type:"uint256[]",internalType:"uint256[]"}],stateMutability:"view"},{type:"function",name:"hasClaimed",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"hasVoted",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"interiorMembers",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"interiorPercentage",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"interiorShare",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"isBundleMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isCandidate",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isExteriorMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"isInteriorMember",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"nominateSelf",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"nzones",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"removeFromExterior",inputs:[{name:"_userId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"reward",inputs:[{name:"_tokenaddress",type:"address",internalType:"address"},{name:"_tokenamount",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"payable"},{type:"function",name:"setContractSplit",inputs:[{name:"_interior",type:"uint256",internalType:"uint256"},{name:"_exterior",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setInteriorSplit",inputs:[{name:"_userIds",type:"string[]",internalType:"string[]"},{name:"_percentages",type:"uint256[]",internalType:"uint256[]"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setNzones",inputs:[{name:"_nzones",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setSteepness",inputs:[{name:"_steepness",type:"uint256",internalType:"uint256"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"startElection",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"steepness",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokenBalance",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"tokensOf",inputs:[{name:"",type:"string",internalType:"string"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"totalDeposited",inputs:[{name:"",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"totalWeightedMembers",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"userIdToAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"userIds",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"vote",inputs:[{name:"_voterId",type:"string",internalType:"string"},{name:"_candidateId",type:"string",internalType:"string"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"votedFor",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"votes",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zone",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zoneWeights",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"zonemembers",inputs:[{name:"",type:"uint256",internalType:"uint256"},{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"event",name:"CandidateNominated",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ContractSplitSet",inputs:[{name:"interior",type:"uint256",indexed:!1,internalType:"uint256"},{name:"exterior",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"DistributionCompleted",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"totalAmount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"recipientCount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"cascadeCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ElectionCancelled",inputs:[],anonymous:!1},{type:"event",name:"ElectionFinalized",inputs:[{name:"winner",type:"string",indexed:!1,internalType:"string"},{name:"voteCount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"ElectionStarted",inputs:[],anonymous:!1},{type:"event",name:"FundsAllocated",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"distributionType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"FundsClaimed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"beneficiary",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsReceived",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"sender",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"FundsTransferred",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"recipient",type:"address",indexed:!0,internalType:"address"},{name:"tokenAddress",type:"address",indexed:!1,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"InteriorSplitSet",inputs:[{name:"userIds",type:"string[]",indexed:!1,internalType:"string[]"},{name:"percentages",type:"uint256[]",indexed:!1,internalType:"uint256[]"}],anonymous:!1},{type:"event",name:"MemberAdded",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberAddedStd",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"addedBy",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"MemberAssignedToZone",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"zoneNumber",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"MemberRemovedFromZone",inputs:[{name:"userId",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"MemberRewarded",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"isContract",type:"bool",indexed:!1,internalType:"bool"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"RewardDistributed",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"amount",type:"uint256",indexed:!1,internalType:"uint256"},{name:"totalMembers",type:"uint256",indexed:!1,internalType:"uint256"},{name:"rewardType",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"SteepnessSet",inputs:[{name:"steepness",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"VoteCast",inputs:[{name:"voter",type:"string",indexed:!1,internalType:"string"},{name:"candidate",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"ZoneAssigned",inputs:[{name:"contractAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonId",type:"string",indexed:!1,internalType:"string"},{name:"userId",type:"string",indexed:!1,internalType:"string"},{name:"oldZone",type:"uint256",indexed:!1,internalType:"uint256"},{name:"newZone",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}],bytecode="0x60806040526040518060400160405280600681526020017f42756e646c650000000000000000000000000000000000000000000000000000815250600290816200004a9190620006da565b5034801562000057575f80fd5b5060405162007e0338038062007e0383398181016040528101906200007d9190620009a6565b60015f819055505f821180156200009b5750670de0b6b3a764000082105b620000dd576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620000d49062000ac6565b60405180910390fd5b8460035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508460045f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055503360055f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508260019081620001ae9190620006da565b5081601381905550806014819055506001600985604051620001d1919062000b26565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600684908060018154018082558091505060019003905f5260205f20015f909190919091509081620002289190620006da565b50620002396200024460201b60201c565b505050505062000d3a565b60185f620002539190620003e9565b600160145462000264919062000b6b565b67ffffffffffffffff81111562000280576200027f62000480565b5b604051908082528060200260200182016040528015620002af5781602001602082028036833780820191505090505b5060189080519060200190620002c792919062000409565b505f6019819055505f670de0b6b3a764000090505f5b60145481116200037b578160188281548110620002ff57620002fe62000ba5565b5b905f5260205f2001819055508160155f8381526020019081526020015f20805490506200032d919062000bd2565b60195f8282546200033f919062000b6b565b925050819055506200036382601354670de0b6b3a76400006200037f60201b60201c565b91508080620003729062000c1c565b915050620002dd565b5050565b5f808211620003c5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401620003bc9062000cb6565b60405180910390fd5b818385620003d4919062000bd2565b620003e0919062000d03565b90509392505050565b5080545f8255905f5260205f209081019062000406919062000459565b50565b828054828255905f5260205f2090810192821562000446579160200282015b828111156200044557825182559160200191906001019062000428565b5b50905062000455919062000459565b5090565b5b8082111562000472575f815f9055506001016200045a565b5090565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680620004f257607f821691505b602082108103620005085762000507620004ad565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026200056c7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff826200052f565b6200057886836200052f565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f620005c2620005bc620005b68462000590565b62000599565b62000590565b9050919050565b5f819050919050565b620005dd83620005a2565b620005f5620005ec82620005c9565b8484546200053b565b825550505050565b5f90565b6200060b620005fd565b62000618818484620005d2565b505050565b5b818110156200063f57620006335f8262000601565b6001810190506200061e565b5050565b601f8211156200068e5762000658816200050e565b620006638462000520565b8101602085101562000673578190505b6200068b620006828562000520565b8301826200061d565b50505b505050565b5f82821c905092915050565b5f620006b05f198460080262000693565b1980831691505092915050565b5f620006ca83836200069f565b9150826002028217905092915050565b620006e58262000476565b67ffffffffffffffff81111562000701576200070062000480565b5b6200070d8254620004da565b6200071a82828562000643565b5f60209050601f83116001811462000750575f84156200073b578287015190505b620007478582620006bd565b865550620007b6565b601f19841662000760866200050e565b5f5b82811015620007895784890151825560018201915060208501945060208101905062000762565b86831015620007a95784890151620007a5601f8916826200069f565b8355505b6001600288020188555050505b505050505050565b5f604051905090565b5f80fd5b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f620007fa82620007cf565b9050919050565b6200080c81620007ee565b811462000817575f80fd5b50565b5f815190506200082a8162000801565b92915050565b5f80fd5b5f80fd5b5f601f19601f8301169050919050565b620008538262000838565b810181811067ffffffffffffffff8211171562000875576200087462000480565b5b80604052505050565b5f62000889620007be565b905062000897828262000848565b919050565b5f67ffffffffffffffff821115620008b957620008b862000480565b5b620008c48262000838565b9050602081019050919050565b5f5b83811015620008f0578082015181840152602081019050620008d3565b5f8484015250505050565b5f620009116200090b846200089c565b6200087e565b90508281526020810184848401111562000930576200092f62000834565b5b6200093d848285620008d1565b509392505050565b5f82601f8301126200095c576200095b62000830565b5b81516200096e848260208601620008fb565b91505092915050565b620009828162000590565b81146200098d575f80fd5b50565b5f81519050620009a08162000977565b92915050565b5f805f805f60a08688031215620009c257620009c1620007c7565b5b5f620009d1888289016200081a565b955050602086015167ffffffffffffffff811115620009f557620009f4620007cb565b5b62000a038882890162000945565b945050604086015167ffffffffffffffff81111562000a275762000a26620007cb565b5b62000a358882890162000945565b935050606062000a488882890162000990565b925050608062000a5b8882890162000990565b9150509295509295909350565b5f82825260208201905092915050565b7f53746565706e657373206d7573742062652030203c2073203c203165313800005f82015250565b5f62000aae601e8362000a68565b915062000abb8262000a78565b602082019050919050565b5f6020820190508181035f83015262000adf8162000aa0565b9050919050565b5f81905092915050565b5f62000afc8262000476565b62000b08818562000ae6565b935062000b1a818560208601620008d1565b80840191505092915050565b5f62000b33828462000af0565b915081905092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f62000b778262000590565b915062000b848362000590565b925082820190508082111562000b9f5762000b9e62000b3e565b5b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f62000bde8262000590565b915062000beb8362000590565b925082820262000bfb8162000590565b9150828204841483151762000c155762000c1462000b3e565b5b5092915050565b5f62000c288262000590565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820362000c5d5762000c5c62000b3e565b5b600182019050919050565b7f4469766973696f6e206279207a65726f000000000000000000000000000000005f82015250565b5f62000c9e60108362000a68565b915062000cab8262000c68565b602082019050919050565b5f6020820190508181035f83015262000ccf8162000c90565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f62000d0f8262000590565b915062000d1c8362000590565b92508262000d2f5762000d2e62000cd6565b5b828204905092915050565b6170bb8062000d485f395ff3fe608060405260043610610338575f3560e01c806377e7fca2116101aa578063c21be6ae116100f6578063dad4ae3711610094578063e1f1c4a71161006e578063e1f1c4a714610ca5578063e8d5940d14610ccf578063ead6252014610cf7578063f59e4f6514610d3357610349565b8063dad4ae3714610c03578063de8fa43114610c3f578063e15b3f5f14610c6957610349565b8063cafa4ffa116100d0578063cafa4ffa14610b4b578063cc18494814610b75578063d118a53f14610bb1578063d7841a1c14610bdb57610349565b8063c21be6ae14610aa9578063c45a015514610ae5578063ca22431314610b0f57610349565b8063873010d911610163578063918f96871161013d578063918f9687146109e1578063981a63dc14610a09578063b801603514610a45578063b99ef1fa14610a6d57610349565b8063873010d91461095157806387563ec11461098d5780638da5cb5b146109b757610349565b806377e7fca2146108355780637a3c22eb1461085f5780637b0a7e33146108875780637c59dd5f146108c35780637ed628bb146108ff578063804d74701461092957610349565b806339bfeae31161028457806357a32534116102225780636a146024116101fc5780636a1460241461078f5780636bd39c52146107b95780636cc6837e146107e35780636d2687c0146107f957610349565b806357a325341461071557806360a1da831461075157806362d73eb81461077957610349565b80634635fd681161025e5780634635fd681461064b57806351599b151461068757806353055481146106c35780635744426e146106ff57610349565b806339bfeae3146105ab578063404880d9146105e7578063441179e51461062357610349565b806321670f22116102f15780633477ee2e116102cb5780633477ee2e146104e3578063363454ee1461051f578063372c3e7c1461055b57806338eccabd1461058357610349565b806321670f221461046157806328c317d71461047d57806333d6e65f146104b957610349565b806302d05d3f1461035557806306a49fce1461037f57806306fdde03146103a957806312feb905146103d35780631821fcab146103fd5780631a2f4ee51461043957610349565b36610349576103475f34610d5d565b005b6103535f34610d5d565b005b348015610360575f80fd5b50610369611149565b604051610376919061509c565b60405180910390f35b34801561038a575f80fd5b5061039361116e565b6040516103a091906151fa565b60405180910390f35b3480156103b4575f80fd5b506103bd611242565b6040516103ca9190615262565b60405180910390f35b3480156103de575f80fd5b506103e76112ce565b6040516103f491906151fa565b60405180910390f35b348015610408575f80fd5b50610423600480360381019061041e91906153bf565b6113a2565b604051610430919061541e565b60405180910390f35b348015610444575f80fd5b5061045f600480360381019061045a9190615461565b6113cf565b005b61047b600480360381019061047691906154c9565b610d5d565b005b348015610488575f80fd5b506104a3600480360381019061049e91906153bf565b6114f8565b6040516104b091906155be565b60405180910390f35b3480156104c4575f80fd5b506104cd6115a1565b6040516104da919061541e565b60405180910390f35b3480156104ee575f80fd5b50610509600480360381019061050491906155de565b6115a7565b6040516105169190615262565b60405180910390f35b34801561052a575f80fd5b50610545600480360381019061054091906153bf565b61164d565b6040516105529190615623565b60405180910390f35b348015610566575f80fd5b50610581600480360381019061057c91906155de565b611682565b005b34801561058e575f80fd5b506105a960048036038101906105a491906153bf565b611723565b005b3480156105b6575f80fd5b506105d160048036038101906105cc91906153bf565b61189c565b6040516105de9190615623565b60405180910390f35b3480156105f2575f80fd5b5061060d600480360381019061060891906153bf565b6118d1565b60405161061a9190615623565b60405180910390f35b34801561062e575f80fd5b506106496004803603810190610644919061563c565b611906565b005b348015610656575f80fd5b50610671600480360381019061066c91906155de565b611c2b565b60405161067e9190615262565b60405180910390f35b348015610692575f80fd5b506106ad60048036038101906106a891906153bf565b611cd1565b6040516106ba9190615623565b60405180910390f35b3480156106ce575f80fd5b506106e960048036038101906106e49190615696565b611d06565b6040516106f6919061541e565b60405180910390f35b34801561070a575f80fd5b50610713611d1b565b005b348015610720575f80fd5b5061073b600480360381019061073691906153bf565b611e3f565b604051610748919061541e565b60405180910390f35b34801561075c575f80fd5b50610777600480360381019061077291906156c1565b611e6c565b005b348015610784575f80fd5b5061078d612201565b005b34801561079a575f80fd5b506107a361245e565b6040516107b0919061541e565b60405180910390f35b3480156107c4575f80fd5b506107cd61246a565b6040516107da919061541e565b60405180910390f35b3480156107ee575f80fd5b506107f7612470565b005b348015610804575f80fd5b5061081f600480360381019061081a91906155de565b612987565b60405161082c9190615262565b60405180910390f35b348015610840575f80fd5b50610849612a2d565b604051610856919061541e565b60405180910390f35b34801561086a575f80fd5b50610885600480360381019061088091906153bf565b612a33565b005b348015610892575f80fd5b506108ad60048036038101906108a891906155de565b612c87565b6040516108ba91906151fa565b60405180910390f35b3480156108ce575f80fd5b506108e960048036038101906108e491906153bf565b612d6c565b6040516108f69190615623565b60405180910390f35b34801561090a575f80fd5b50610913612da1565b6040516109209190615623565b60405180910390f35b348015610934575f80fd5b5061094f600480360381019061094a91906157fd565b612db3565b005b34801561095c575f80fd5b50610977600480360381019061097291906155de565b612fac565b604051610984919061541e565b60405180910390f35b348015610998575f80fd5b506109a1612fcc565b6040516109ae919061541e565b60405180910390f35b3480156109c2575f80fd5b506109cb612fd2565b6040516109d8919061509c565b60405180910390f35b3480156109ec575f80fd5b50610a076004803603810190610a0291906153bf565b612ff7565b005b348015610a14575f80fd5b50610a2f6004803603810190610a2a91906153bf565b6131ab565b604051610a3c9190615262565b60405180910390f35b348015610a50575f80fd5b50610a6b6004803603810190610a669190615904565b61325e565b005b348015610a78575f80fd5b50610a936004803603810190610a8e91906153bf565b61368c565b604051610aa0919061541e565b60405180910390f35b348015610ab4575f80fd5b50610acf6004803603810190610aca91906153bf565b6136b9565b604051610adc919061509c565b60405180910390f35b348015610af0575f80fd5b50610af9613701565b604051610b06919061509c565b60405180910390f35b348015610b1a575f80fd5b50610b356004803603810190610b3091906156c1565b613726565b604051610b42919061541e565b60405180910390f35b348015610b56575f80fd5b50610b5f61375e565b604051610b6c919061541e565b60405180910390f35b348015610b80575f80fd5b50610b9b6004803603810190610b96919061563c565b613764565b604051610ba8919061509c565b60405180910390f35b348015610bbc575f80fd5b50610bc56137c4565b604051610bd29190615a31565b60405180910390f35b348015610be6575f80fd5b50610c016004803603810190610bfc91906155de565b61381a565b005b348015610c0e575f80fd5b50610c296004803603810190610c2491906153bf565b613947565b604051610c369190615623565b60405180910390f35b348015610c4a575f80fd5b50610c5361397c565b604051610c60919061541e565b60405180910390f35b348015610c74575f80fd5b50610c8f6004803603810190610c8a91906153bf565b613988565b604051610c9c919061541e565b60405180910390f35b348015610cb0575f80fd5b50610cb96139b5565b604051610cc6919061541e565b60405180910390f35b348015610cda575f80fd5b50610cf56004803603810190610cf09190615a51565b6139bb565b005b348015610d02575f80fd5b50610d1d6004803603810190610d189190615461565b613ca9565b604051610d2a9190615262565b60405180910390f35b348015610d3e575f80fd5b50610d47613d5a565b604051610d549190615262565b60405180910390f35b610d65613de6565b5f8034118015610da057505f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b90505f8115610e18573492503373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f37de26b9f29dba736fb8291dad9ace7d2f6dc76e3e5faaeca097145b5298f94b5f86604051610e0b929190615ac7565b60405180910390a3610f8a565b8390505f600d5f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20548273ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401610e93919061509c565b602060405180830381865afa158015610eae573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610ed29190615b02565b610edc9190615b5a565b905083811015610f21576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610f1890615bd7565b60405180910390fd5b3373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f37de26b9f29dba736fb8291dad9ace7d2f6dc76e3e5faaeca097145b5298f94b8787604051610f80929190615ac7565b60405180910390a3505b5f610f9a84600e54612710613e2a565b90505f8185610fa99190615b5a565b90505f8083118015610fbf57505f601080549050115b15610fde57610fd087848787613e8d565b81610fdb9190615bf5565b90505b5f82118015610fee57505f601954115b1561100d57610fff87838787613fb6565b8161100a9190615bf5565b90505b3073ffffffffffffffffffffffffffffffffffffffff167fd83308e9158842b2115ec5e6f6395db42fff24e4b5506ef42fe33854fafad655878388611087576040518060400160405280600581526020017f45524332300000000000000000000000000000000000000000000000000000008152506110be565b6040518060400160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152505b6040516110cd93929190615c28565b60405180910390a23073ffffffffffffffffffffffffffffffffffffffff167fc2d2b959adca67349f750fed9ef9eaefbec59f24fa563c7fa410157130395c4060018761111a578961111c565b5f5b89855f604051611130959493929190615d96565b60405180910390a25050505050611145614184565b5050565b60045f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6060601b805480602002602001604051908101604052809291908181526020015f905b82821015611239578382905f5260205f200180546111ae90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546111da90615c91565b80156112255780601f106111fc57610100808354040283529160200191611225565b820191905f5260205f20905b81548152906001019060200180831161120857829003601f168201915b505050505081526020019060010190611191565b50505050905090565b6001805461124f90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461127b90615c91565b80156112c65780601f1061129d576101008083540402835291602001916112c6565b820191905f5260205f20905b8154815290600101906020018083116112a957829003601f168201915b505050505081565b60606010805480602002602001604051908101604052809291908181526020015f905b82821015611399578382905f5260205f2001805461130e90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461133a90615c91565b80156113855780601f1061135c57610100808354040283529160200191611385565b820191905f5260205f20905b81548152906001019060200180831161136857829003601f168201915b5050505050815260200190600101906112f1565b50505050905090565b6016818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461145e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161145590615e38565b60405180910390fd5b612710818361146d9190615bf5565b146114ad576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016114a490615ea0565b60405180910390fd5b81600e8190555080600f819055507f29dd4a83e71eab2a472a8bb7a7bb9467395098acb48b07c8d9ea7294de0ba0ae82826040516114ec929190615ebe565b60405180910390a15050565b6060600c8260405161150a9190615f1f565b908152602001604051809103902080548060200260200160405190810160405280929190818152602001828054801561159557602002820191905f5260205f20905b815f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001906001019080831161154c575b50505050509050919050565b60145481565b601b81815481106115b6575f80fd5b905f5260205f20015f9150905080546115ce90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546115fa90615c91565b80156116455780601f1061161c57610100808354040283529160200191611645565b820191905f5260205f20905b81548152906001019060200180831161162857829003601f168201915b505050505081565b6008818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611711576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161170890615e38565b60405180910390fd5b8060148190555061172061418d565b50565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146117b2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016117a990615e38565b60405180910390fd5b6017816040516117c29190615f1f565b90815260200160405180910390205f9054906101000a900460ff1661181c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161181390615f7f565b60405180910390fd5b611825816142ab565b5f6017826040516118369190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555061186261418d565b7fe6db474363a3116f4cf525fc0d78d9dd53e214383db31efef8368f08c4bf7991816040516118919190615262565b60405180910390a150565b601e818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b6009818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611995576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161198c90615e38565b60405180910390fd5b6009826040516119a59190615f1f565b90815260200160405180910390205f9054906101000a900460ff166119ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016119f690615fe7565b60405180910390fd5b601454811115611a44576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611a3b9061604f565b60405180910390fd5b5f601783604051611a559190615f1f565b90815260200160405180910390205f9054906101000a900460ff16611a9a577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff611aba565b601683604051611aaa9190615f1f565b9081526020016040518091039020545b9050601783604051611acc9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615611af657611af5836142ab565b5b81601684604051611b079190615f1f565b90815260200160405180910390208190555060155f8381526020019081526020015f2083908060018154018082558091505060019003905f5260205f20015f909190919091509081611b5991906161ef565b506001601784604051611b6c9190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550611b9861418d565b7f9bca84993827a6bd2bc824f45db9e0ae931cf1f7b1706b7c735ba0102300b4ca8383604051611bc99291906162be565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f7d482c93a88a92e4d27ba697265785162f607bc0ac6c55b868232b3ba3fbb63d6001858486604051611c1e94939291906162ec565b60405180910390a2505050565b60068181548110611c3a575f80fd5b905f5260205f20015f915090508054611c5290615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054611c7e90615c91565b8015611cc95780601f10611ca057610100808354040283529160200191611cc9565b820191905f5260205f20905b815481529060010190602001808311611cac57829003601f168201915b505050505081565b601c818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b600d602052805f5260405f205f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611daa576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611da190615e38565b60405180910390fd5b601a5f9054906101000a900460ff16611df8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611def90616387565b60405180910390fd5b5f601a5f6101000a81548160ff0219169083151502179055507f990bb31515adefe5ecd88a4dca3e9772b32d484c81e22cae38d5482e0d9f35e460405160405180910390a1565b600a818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611efb576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611ef290615e38565b60405180910390fd5b611f03613de6565b600882604051611f139190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615611f6e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611f65906163ef565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603611fdc576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611fd390616457565b60405180910390fd5b600982604051611fec9190615f1f565b90815260200160405180910390205f9054906101000a900460ff16612046576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161203d906164bf565b60405180910390fd5b5f600a836040516120579190615f1f565b9081526020016040518091039020549050600160088460405161207a9190615f1f565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055505f73ffffffffffffffffffffffffffffffffffffffff166007846040516120c59190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff160361216b578160078460405161211f9190615f1f565b90815260200160405180910390205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b61217583836143c9565b61217f83836144c5565b5f8111156121f4578173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f605614956ef211f270ab0b08a13dd69698dc38d70e20899e1051ae2e1ae6cd5b6001865f866040516121eb94939291906164dd565b60405180910390a35b506121fd614184565b5050565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612290576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161228790615e38565b60405180910390fd5b5f5b601b80549050811015612340575f601d601b83815481106122b6576122b561652e565b5b905f5260205f20016040516122cb91906165db565b9081526020016040518091039020819055505f601c601b83815481106122f4576122f361652e565b5b905f5260205f200160405161230991906165db565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055508080612338906165f1565b915050612292565b50601b5f61234e9190614f5b565b5f5b600680549050811015612415575f601e600683815481106123745761237361652e565b5b905f5260205f200160405161238991906165db565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555060405180602001604052805f815250601f600683815481106123d2576123d161652e565b5b905f5260205f20016040516123e791906165db565b9081526020016040518091039020908161240191906161ef565b50808061240d906165f1565b915050612350565b506001601a5f6101000a81548160ff0219169083151502179055507fc475c26aa25ed8e85a7faa790e5f63b5d7ee1025f12821f4c9bfddd36ab4d11260405160405180910390a1565b670de0b6b3a764000081565b600e5481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146124ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016124f690615e38565b60405180910390fd5b601a5f9054906101000a900460ff1661254d576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161254490616387565b60405180910390fd5b5f601b8054905011612594576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161258b90616682565b60405180910390fd5b5f601b5f815481106125a9576125a861652e565b5b905f5260205f200180546125bc90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546125e890615c91565b80156126335780601f1061260a57610100808354040283529160200191612633565b820191905f5260205f20905b81548152906001019060200180831161261657829003601f168201915b505050505090505f601d601b5f815481106126515761265061652e565b5b905f5260205f200160405161266691906165db565b90815260200160405180910390205490505f600190505b601b805490508110156127c05781601d601b83815481106126a1576126a061652e565b5b905f5260205f20016040516126b691906165db565b90815260200160405180910390205411156127ad57601d601b82815481106126e1576126e061652e565b5b905f5260205f20016040516126f691906165db565b9081526020016040518091039020549150601b818154811061271b5761271a61652e565b5b905f5260205f2001805461272e90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461275a90615c91565b80156127a55780601f1061277c576101008083540402835291602001916127a5565b820191905f5260205f20905b81548152906001019060200180831161278857829003601f168201915b505050505092505b80806127b8906165f1565b91505061267d565b505f6007836040516127d29190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505f73ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1603612870576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161286790616710565b60405180910390fd5b5f60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690508160035f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505f601a5f6101000a81548160ff0219169083151502179055507f5e99cd5235d5c8c4f0f8dc2626c83130cf843047e4ecbe4c111076e2b31a0d52848460405161291f9291906162be565b60405180910390a18173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a350505050565b60108181548110612996575f80fd5b905f5260205f20015f9150905080546129ae90615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546129da90615c91565b8015612a255780601f106129fc57610100808354040283529160200191612a25565b820191905f5260205f20905b815481529060010190602001808311612a0857829003601f168201915b505050505081565b600f5481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612ac2576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612ab990615e38565b60405180910390fd5b601a5f9054906101000a900460ff16612b10576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612b0790616387565b60405180910390fd5b600981604051612b209190615f1f565b90815260200160405180910390205f9054906101000a900460ff16612b7a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612b7190616778565b60405180910390fd5b601c81604051612b8a9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615612be5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612bdc906167e0565b60405180910390fd5b601b81908060018154018082558091505060019003905f5260205f20015f909190919091509081612c1691906161ef565b506001601c82604051612c299190615f1f565b90815260200160405180910390205f6101000a81548160ff0219169083151502179055507f134c877b5bd4770ffc56867fc5d2c549dd813a5db276d378f8d855a04fc7aa1d81604051612c7c9190615262565b60405180910390a150565b606060155f8381526020019081526020015f20805480602002602001604051908101604052809291908181526020015f905b82821015612d61578382905f5260205f20018054612cd690615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054612d0290615c91565b8015612d4d5780601f10612d2457610100808354040283529160200191612d4d565b820191905f5260205f20905b815481529060010190602001808311612d3057829003601f168201915b505050505081526020019060010190612cb9565b505050509050919050565b6011818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b601a5f9054906101000a900460ff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614612e42576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401612e3990615e38565b60405180910390fd5b5f5b8151811015612fa8575f828281518110612e6157612e6061652e565b5b60200260200101519050600981604051612e7b9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615612ea15750612f95565b6001600982604051612eb39190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600681908060018154018082558091505060019003905f5260205f20015f909190919091509081612f0891906161ef565b507fdfaa3c24567cbffbf024ddfd8dfca7a224b307e94b0df5437facad0f2fea2f9b81604051612f389190615262565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f954917c11fc57299ff064c483b4113756221231fcea3a1a3aa54ebd605a9c1e860018333604051612f8b939291906167fe565b60405180910390a2505b8080612fa0906165f1565b915050612e44565b5050565b60188181548110612fbb575f80fd5b905f5260205f20015f915090505481565b60135481565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614613086576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161307d90615e38565b60405180910390fd5b6009816040516130969190615f1f565b90815260200160405180910390205f9054906101000a900460ff166131a85760016009826040516130c79190615f1f565b90815260200160405180910390205f6101000a81548160ff021916908315150217905550600681908060018154018082558091505060019003905f5260205f20015f90919091909150908161311c91906161ef565b507fdfaa3c24567cbffbf024ddfd8dfca7a224b307e94b0df5437facad0f2fea2f9b8160405161314c9190615262565b60405180910390a13073ffffffffffffffffffffffffffffffffffffffff167f954917c11fc57299ff064c483b4113756221231fcea3a1a3aa54ebd605a9c1e86001833360405161319f939291906167fe565b60405180910390a25b50565b601f818051602081018201805184825260208301602085012081835280955050505050505f9150905080546131df90615c91565b80601f016020809104026020016040519081016040528092919081815260200182805461320b90615c91565b80156132565780601f1061322d57610100808354040283529160200191613256565b820191905f5260205f20905b81548152906001019060200180831161323957829003601f168201915b505050505081565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146132ed576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016132e490615e38565b60405180910390fd5b8051825114613331576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016133289061688b565b60405180910390fd5b5f5b6010805490508110156133e1575f6012601083815481106133575761335661652e565b5b905f5260205f200160405161336c91906165db565b9081526020016040518091039020819055505f6011601083815481106133955761339461652e565b5b905f5260205f20016040516133aa91906165db565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555080806133d9906165f1565b915050613333565b5060105f6133ef9190614f5b565b5f805b83518110156136095760098482815181106134105761340f61652e565b5b60200260200101516040516134259190615f1f565b90815260200160405180910390205f9054906101000a900460ff1661347f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613476906168f3565b60405180910390fd5b5f8382815181106134935761349261652e565b5b6020026020010151116134db576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016134d29061695b565b60405180910390fd5b60108482815181106134f0576134ef61652e565b5b6020026020010151908060018154018082558091505060019003905f5260205f20015f90919091909150908161352691906161ef565b506001601185838151811061353e5761353d61652e565b5b60200260200101516040516135539190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555082818151811061358a5761358961652e565b5b602002602001015160128583815181106135a7576135a661652e565b5b60200260200101516040516135bc9190615f1f565b9081526020016040518091039020819055508281815181106135e1576135e061652e565b5b6020026020010151826135f49190615bf5565b91508080613601906165f1565b9150506133f2565b50612710811461364e576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613645906169c3565b60405180910390fd5b7f7749ddba77d660c1351ff548a0bf5b09743d6ad44914e3cb9a29a1f805fb09fe838360405161367f9291906169e1565b60405180910390a1505050565b601d818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b6007818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60055f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600b82805160208101820180518482526020830160208501208183528095505050505050602052805f5260405f205f91509150505481565b60195481565b600c828051602081018201805184825260208301602085012081835280955050505050508181548110613795575f80fd5b905f5260205f20015f915091509054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6060601880548060200260200160405190810160405280929190818152602001828054801561381057602002820191905f5260205f20905b8154815260200190600101908083116137fc575b5050505050905090565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16146138a9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016138a090615e38565b60405180910390fd5b5f811180156138bf5750670de0b6b3a764000081105b6138fe576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016138f590616a60565b60405180910390fd5b8060138190555061390d61418d565b7f5fad7fda6b8fb652ca59780d340772fed3852ba698b3a4cd40ebc117b8ec57508160405161393c919061541e565b60405180910390a150565b6017818051602081018201805184825260208301602085012081835280955050505050505f915054906101000a900460ff1681565b5f600680549050905090565b6012818051602081018201805184825260208301602085012081835280955050505050505f915090505481565b61271081565b60035f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614613a4a576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613a4190615e38565b60405180910390fd5b601a5f9054906101000a900460ff16613a98576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613a8f90616387565b60405180910390fd5b600982604051613aa89190615f1f565b90815260200160405180910390205f9054906101000a900460ff16613b02576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613af990616ac8565b60405180910390fd5b601c81604051613b129190615f1f565b90815260200160405180910390205f9054906101000a900460ff16613b6c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613b6390616b30565b60405180910390fd5b601e82604051613b7c9190615f1f565b90815260200160405180910390205f9054906101000a900460ff1615613bd7576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613bce90616b98565b60405180910390fd5b6001601e83604051613be99190615f1f565b90815260200160405180910390205f6101000a81548160ff02191690831515021790555080601f83604051613c1e9190615f1f565b90815260200160405180910390209081613c3891906161ef565b50601d81604051613c499190615f1f565b90815260200160405180910390205f815480929190613c67906165f1565b91905055507f137ad23732468494166ec34d1367743690ffa17f6ceac8429cba8fc35d088b6e8282604051613c9d929190616bb6565b60405180910390a15050565b6015602052815f5260405f208181548110613cc2575f80fd5b905f5260205f20015f91509150508054613cdb90615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613d0790615c91565b8015613d525780601f10613d2957610100808354040283529160200191613d52565b820191905f5260205f20905b815481529060010190602001808311613d3557829003601f168201915b505050505081565b60028054613d6790615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613d9390615c91565b8015613dde5780601f10613db557610100808354040283529160200191613dde565b820191905f5260205f20905b815481529060010190602001808311613dc157829003601f168201915b505050505081565b60025f5403613e21576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60025f81905550565b5f808211613e6d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401613e6490616c35565b60405180910390fd5b818385613e7a9190616c53565b613e849190616cc1565b90509392505050565b5f805f90505b601080549050811015613fad575f60108281548110613eb557613eb461652e565b5b905f5260205f20018054613ec890615c91565b80601f0160208091040260200160405190810160405280929190818152602001828054613ef490615c91565b8015613f3f5780601f10613f1657610100808354040283529160200191613f3f565b820191905f5260205f20905b815481529060010190602001808311613f2257829003601f168201915b505050505090505f613f7287601284604051613f5b9190615f1f565b908152602001604051809103902054612710613e2a565b90505f811115613f9857613f898289838989614737565b8380613f94906165f1565b9450505b50508080613fa5906165f1565b915050613e93565b50949350505050565b5f805f90505b601454811161417b575f60155f8381526020019081526020015f208054905090505f8103613fea5750614168565b5f60188381548110613fff57613ffe61652e565b5b905f5260205f200154826140139190616c53565b90505f6140238883601954613e2a565b90505f83826140329190616cc1565b90505f805b85811015614161575f60018761404d9190615b5a565b820361406657828561405f9190615b5a565b9050614078565b83905083836140759190615bf5565b92505b5f81111561414d5761413e60155f8a81526020019081526020015f2083815481106140a6576140a561652e565b5b905f5260205f200180546140b990615c91565b80601f01602080910402602001604051908101604052809291908181526020018280546140e590615c91565b80156141305780601f1061410757610100808354040283529160200191614130565b820191905f5260205f20905b81548152906001019060200180831161411357829003601f168201915b50505050508e838e8e614737565b8880614149906165f1565b9950505b508080614159906165f1565b915050614037565b5050505050505b8080614173906165f1565b915050613fbc565b50949350505050565b60015f81905550565b60185f61419a9190614f79565b60016014546141a99190615bf5565b67ffffffffffffffff8111156141c2576141c161529b565b5b6040519080825280602002602001820160405280156141f05781602001602082028036833780820191505090505b5060189080519060200190614206929190614f97565b505f6019819055505f670de0b6b3a764000090505f5b60145481116142a757816018828154811061423a5761423961652e565b5b905f5260205f2001819055508160155f8381526020019081526020015f20805490506142669190616c53565b60195f8282546142769190615bf5565b9250508190555061429282601354670de0b6b3a7640000613e2a565b9150808061429f906165f1565b91505061421c565b5050565b5f6016826040516142bc9190615f1f565b90815260200160405180910390205490505f60155f8381526020019081526020015f2090505f5b81805490508110156143c357838051906020012082828154811061430a5761430961652e565b5b905f5260205f200160405161431f9190616d8d565b6040518091039020036143b057816001838054905061433e9190615b5a565b8154811061434f5761434e61652e565b5b905f5260205f200182828154811061436a5761436961652e565b5b905f5260205f2001908161437e9190616dca565b50818054806143905761438f616eaf565b5b600190038181905f5260205f20015f6143a99190614fe2565b90556143c3565b80806143bb906165f1565b9150506142e3565b50505050565b5f600a836040516143da9190615f1f565b90815260200160405180910390205490505f8111156144c0575f600a846040516144049190615f1f565b9081526020016040518091039020819055505f8273ffffffffffffffffffffffffffffffffffffffff168260405161443b90616eff565b5f6040518083038185875af1925050503d805f8114614475576040519150601f19603f3d011682016040523d82523d5f602084013e61447a565b606091505b50509050806144be576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016144b590616f5d565b60405180910390fd5b505b505050565b5f600c836040516144d69190615f1f565b908152602001604051809103902080548060200260200160405190810160405280929190818152602001828054801561456157602002820191905f5260205f20905b815f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311614518575b505050505090505f5b8151811015614731575f600b856040516145849190615f1f565b90815260200160405180910390205f8484815181106145a6576145a561652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205490505f81111561471d575f600b866040516146039190615f1f565b90815260200160405180910390205f8585815181106146255761462461652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f208190555080600d5f8585815181106146815761468061652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8282546146d09190615b5a565b9250508190555061471c84828585815181106146ef576146ee61652e565b5b602002602001015173ffffffffffffffffffffffffffffffffffffffff16614e419092919063ffffffff16565b5b508080614729906165f1565b91505061456a565b50505050565b5f6007866040516147489190615f1f565b90815260200160405180910390205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690505f8073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141580156147cb57505f8273ffffffffffffffffffffffffffffffffffffffff163b115b90506008876040516147dd9190615f1f565b90815260200160405180910390205f9054906101000a900460ff16801561483057505f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614155b15614a715783156148e9575f8273ffffffffffffffffffffffffffffffffffffffff168660405161486090616eff565b5f6040518083038185875af1925050503d805f811461489a576040519150601f19603f3d011682016040523d82523d5f602084013e61489f565b606091505b50509050806148e3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016148da90616fc5565b60405180910390fd5b50614915565b61491482868573ffffffffffffffffffffffffffffffffffffffff16614e419092919063ffffffff16565b5b8173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f7d6a6b7452c2fec7981096e354fb3311f3f3b800ff27def1017b22cbff2751908784886149a6576040518060400160405280600581526020017f45524332300000000000000000000000000000000000000000000000000000008152506149dd565b6040518060400160405280600381526020017f45544800000000000000000000000000000000000000000000000000000000008152505b6040516149ec93929190616fe3565b60405180910390a38173ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f71e611184866cc19c5f49af6c856ce9bde5a13bcd197c7499b61ab410ac9439960018a88614a51578a614a53565b5f5b8a604051614a6494939291906164dd565b60405180910390a3614e38565b8315614ab05784600a88604051614a889190615f1f565b90815260200160405180910390205f828254614aa49190615bf5565b92505081905550614c50565b5f600b88604051614ac19190615f1f565b90815260200160405180910390205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205403614b8d57600c87604051614b209190615f1f565b908152602001604051809103902086908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505b84600b88604051614b9e9190615f1f565b90815260200160405180910390205f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f828254614bf59190615bf5565b9250508190555084600d5f8873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f828254614c489190615bf5565b925050819055505b5f73ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167f7d6a6b7452c2fec7981096e354fb3311f3f3b800ff27def1017b22cbff275190875f88614ce1576040518060400160405280600c81526020017f53544f5245445f45524332300000000000000000000000000000000000000000815250614d18565b6040518060400160405280600a81526020017f53544f5245445f455448000000000000000000000000000000000000000000008152505b604051614d2793929190616fe3565b60405180910390a35f601188604051614d409190615f1f565b90815260200160405180910390205f9054906101000a900460ff16614d9a576040518060400160405280600481526020017f7a6f6e6500000000000000000000000000000000000000000000000000000000815250614dd1565b6040518060400160405280600a81526020017f70657263656e74616765000000000000000000000000000000000000000000008152505b90503073ffffffffffffffffffffffffffffffffffffffff167ff9700e8ac41cc506d3f79229bad9981619140b63838136cdb10ac6ba5f6976ab60018a88614e19578a614e1b565b5f5b8a86604051614e2e95949392919061701f565b60405180910390a2505b50505050505050565b614ebb838473ffffffffffffffffffffffffffffffffffffffff1663a9059cbb8585604051602401614e74929190615ac7565b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050614ec0565b505050565b5f8060205f8451602086015f885af180614edf576040513d5f823e3d81fd5b3d92505f519150505f8214614ef8576001811415614f13565b5f8473ffffffffffffffffffffffffffffffffffffffff163b145b15614f5557836040517f5274afe7000000000000000000000000000000000000000000000000000000008152600401614f4c919061509c565b60405180910390fd5b50505050565b5080545f8255905f5260205f2090810190614f76919061501f565b50565b5080545f8255905f5260205f2090810190614f949190615042565b50565b828054828255905f5260205f20908101928215614fd1579160200282015b82811115614fd0578251825591602001919060010190614fb5565b5b509050614fde9190615042565b5090565b508054614fee90615c91565b5f825580601f10614fff575061501c565b601f0160209004905f5260205f209081019061501b9190615042565b5b50565b5b8082111561503e575f81816150359190614fe2565b50600101615020565b5090565b5b80821115615059575f815f905550600101615043565b5090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6150868261505d565b9050919050565b6150968161507c565b82525050565b5f6020820190506150af5f83018461508d565b92915050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f81519050919050565b5f82825260208201905092915050565b5f5b838110156151155780820151818401526020810190506150fa565b5f8484015250505050565b5f601f19601f8301169050919050565b5f61513a826150de565b61514481856150e8565b93506151548185602086016150f8565b61515d81615120565b840191505092915050565b5f6151738383615130565b905092915050565b5f602082019050919050565b5f615191826150b5565b61519b81856150bf565b9350836020820285016151ad856150cf565b805f5b858110156151e857848403895281516151c98582615168565b94506151d48361517b565b925060208a019950506001810190506151b0565b50829750879550505050505092915050565b5f6020820190508181035f8301526152128184615187565b905092915050565b5f82825260208201905092915050565b5f615234826150de565b61523e818561521a565b935061524e8185602086016150f8565b61525781615120565b840191505092915050565b5f6020820190508181035f83015261527a818461522a565b905092915050565b5f604051905090565b5f80fd5b5f80fd5b5f80fd5b5f80fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6152d182615120565b810181811067ffffffffffffffff821117156152f0576152ef61529b565b5b80604052505050565b5f615302615282565b905061530e82826152c8565b919050565b5f67ffffffffffffffff82111561532d5761532c61529b565b5b61533682615120565b9050602081019050919050565b828183375f83830152505050565b5f61536361535e84615313565b6152f9565b90508281526020810184848401111561537f5761537e615297565b5b61538a848285615343565b509392505050565b5f82601f8301126153a6576153a5615293565b5b81356153b6848260208601615351565b91505092915050565b5f602082840312156153d4576153d361528b565b5b5f82013567ffffffffffffffff8111156153f1576153f061528f565b5b6153fd84828501615392565b91505092915050565b5f819050919050565b61541881615406565b82525050565b5f6020820190506154315f83018461540f565b92915050565b61544081615406565b811461544a575f80fd5b50565b5f8135905061545b81615437565b92915050565b5f80604083850312156154775761547661528b565b5b5f6154848582860161544d565b92505060206154958582860161544d565b9150509250929050565b6154a88161507c565b81146154b2575f80fd5b50565b5f813590506154c38161549f565b92915050565b5f80604083850312156154df576154de61528b565b5b5f6154ec858286016154b5565b92505060206154fd8582860161544d565b9150509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6155398161507c565b82525050565b5f61554a8383615530565b60208301905092915050565b5f602082019050919050565b5f61556c82615507565b6155768185615511565b935061558183615521565b805f5b838110156155b1578151615598888261553f565b97506155a383615556565b925050600181019050615584565b5085935050505092915050565b5f6020820190508181035f8301526155d68184615562565b905092915050565b5f602082840312156155f3576155f261528b565b5b5f6156008482850161544d565b91505092915050565b5f8115159050919050565b61561d81615609565b82525050565b5f6020820190506156365f830184615614565b92915050565b5f80604083850312156156525761565161528b565b5b5f83013567ffffffffffffffff81111561566f5761566e61528f565b5b61567b85828601615392565b925050602061568c8582860161544d565b9150509250929050565b5f602082840312156156ab576156aa61528b565b5b5f6156b8848285016154b5565b91505092915050565b5f80604083850312156156d7576156d661528b565b5b5f83013567ffffffffffffffff8111156156f4576156f361528f565b5b61570085828601615392565b9250506020615711858286016154b5565b9150509250929050565b5f67ffffffffffffffff8211156157355761573461529b565b5b602082029050602081019050919050565b5f80fd5b5f61575c6157578461571b565b6152f9565b9050808382526020820190506020840283018581111561577f5761577e615746565b5b835b818110156157c657803567ffffffffffffffff8111156157a4576157a3615293565b5b8086016157b18982615392565b85526020850194505050602081019050615781565b5050509392505050565b5f82601f8301126157e4576157e3615293565b5b81356157f484826020860161574a565b91505092915050565b5f602082840312156158125761581161528b565b5b5f82013567ffffffffffffffff81111561582f5761582e61528f565b5b61583b848285016157d0565b91505092915050565b5f67ffffffffffffffff82111561585e5761585d61529b565b5b602082029050602081019050919050565b5f61588161587c84615844565b6152f9565b905080838252602082019050602084028301858111156158a4576158a3615746565b5b835b818110156158cd57806158b9888261544d565b8452602084019350506020810190506158a6565b5050509392505050565b5f82601f8301126158eb576158ea615293565b5b81356158fb84826020860161586f565b91505092915050565b5f806040838503121561591a5761591961528b565b5b5f83013567ffffffffffffffff8111156159375761593661528f565b5b615943858286016157d0565b925050602083013567ffffffffffffffff8111156159645761596361528f565b5b615970858286016158d7565b9150509250929050565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b6159ac81615406565b82525050565b5f6159bd83836159a3565b60208301905092915050565b5f602082019050919050565b5f6159df8261597a565b6159e98185615984565b93506159f483615994565b805f5b83811015615a24578151615a0b88826159b2565b9750615a16836159c9565b9250506001810190506159f7565b5085935050505092915050565b5f6020820190508181035f830152615a4981846159d5565b905092915050565b5f8060408385031215615a6757615a6661528b565b5b5f83013567ffffffffffffffff811115615a8457615a8361528f565b5b615a9085828601615392565b925050602083013567ffffffffffffffff811115615ab157615ab061528f565b5b615abd85828601615392565b9150509250929050565b5f604082019050615ada5f83018561508d565b615ae7602083018461540f565b9392505050565b5f81519050615afc81615437565b92915050565b5f60208284031215615b1757615b1661528b565b5b5f615b2484828501615aee565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f615b6482615406565b9150615b6f83615406565b9250828203905081811115615b8757615b86615b2d565b5b92915050565b7f496e73756666696369656e7420746f6b656e2062616c616e63650000000000005f82015250565b5f615bc1601a8361521a565b9150615bcc82615b8d565b602082019050919050565b5f6020820190508181035f830152615bee81615bb5565b9050919050565b5f615bff82615406565b9150615c0a83615406565b9250828201905080821115615c2257615c21615b2d565b5b92915050565b5f606082019050615c3b5f83018661540f565b615c48602083018561540f565b8181036040830152615c5a818461522a565b9050949350505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680615ca857607f821691505b602082108103615cbb57615cba615c64565b5b50919050565b5f819050815f5260205f209050919050565b5f8154615cdf81615c91565b615ce9818661521a565b9450600182165f8114615d035760018114615d1957615d4b565b60ff198316865281151560200286019350615d4b565b615d2285615cc1565b5f5b83811015615d4357815481890152600182019150602081019050615d24565b808801955050505b50505092915050565b5f819050919050565b5f819050919050565b5f615d80615d7b615d7684615d54565b615d5d565b615406565b9050919050565b615d9081615d66565b82525050565b5f60a0820190508181035f830152615dae8188615cd3565b9050615dbd602083018761508d565b615dca604083018661540f565b615dd7606083018561540f565b615de46080830184615d87565b9695505050505050565b7f4f6e6c79206f776e6572000000000000000000000000000000000000000000005f82015250565b5f615e22600a8361521a565b9150615e2d82615dee565b602082019050919050565b5f6020820190508181035f830152615e4f81615e16565b9050919050565b7f4d7573742073756d20746f2031303030300000000000000000000000000000005f82015250565b5f615e8a60118361521a565b9150615e9582615e56565b602082019050919050565b5f6020820190508181035f830152615eb781615e7e565b9050919050565b5f604082019050615ed15f83018561540f565b615ede602083018461540f565b9392505050565b5f81905092915050565b5f615ef9826150de565b615f038185615ee5565b9350615f138185602086016150f8565b80840191505092915050565b5f615f2a8284615eef565b915081905092915050565b7f4e6f7420616e206578746572696f72206d656d626572000000000000000000005f82015250565b5f615f6960168361521a565b9150615f7482615f35565b602082019050919050565b5f6020820190508181035f830152615f9681615f5d565b9050919050565b7f4d75737420626520612062756e646c65206d656d6265720000000000000000005f82015250565b5f615fd160178361521a565b9150615fdc82615f9d565b602082019050919050565b5f6020820190508181035f830152615ffe81615fc5565b9050919050565b7f5a6f6e65206f7574206f662072616e67650000000000000000000000000000005f82015250565b5f61603960118361521a565b915061604482616005565b602082019050919050565b5f6020820190508181035f8301526160668161602d565b9050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026160b77fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8261607c565b6160c1868361607c565b95508019841693508086168417925050509392505050565b5f6160f36160ee6160e984615406565b615d5d565b615406565b9050919050565b5f819050919050565b61610c836160d9565b616120616118826160fa565b848454616088565b825550505050565b5f90565b616134616128565b61613f818484616103565b505050565b5b81811015616162576161575f8261612c565b600181019050616145565b5050565b601f8211156161a75761617881615cc1565b6161818461606d565b81016020851015616190578190505b6161a461619c8561606d565b830182616144565b50505b505050565b5f82821c905092915050565b5f6161c75f19846008026161ac565b1980831691505092915050565b5f6161df83836161b8565b9150826002028217905092915050565b6161f8826150de565b67ffffffffffffffff8111156162115761621061529b565b5b61621b8254615c91565b616226828285616166565b5f60209050601f831160018114616257575f8415616245578287015190505b61624f85826161d4565b8655506162b6565b601f19841661626586615cc1565b5f5b8281101561628c57848901518255600182019150602085019450602081019050616267565b868310156162a957848901516162a5601f8916826161b8565b8355505b6001600288020188555050505b505050505050565b5f6040820190508181035f8301526162d6818561522a565b90506162e5602083018461540f565b9392505050565b5f6080820190508181035f8301526163048187615cd3565b90508181036020830152616318818661522a565b9050616327604083018561540f565b616334606083018461540f565b95945050505050565b7f4e6f2061637469766520656c656374696f6e00000000000000000000000000005f82015250565b5f61637160128361521a565b915061637c8261633d565b602082019050919050565b5f6020820190508181035f83015261639e81616365565b9050919050565b7f416c726561647920636c61696d656400000000000000000000000000000000005f82015250565b5f6163d9600f8361521a565b91506163e4826163a5565b602082019050919050565b5f6020820190508181035f830152616406816163cd565b9050919050565b7f496e76616c69642062656e6566696369617279000000000000000000000000005f82015250565b5f61644160138361521a565b915061644c8261640d565b602082019050919050565b5f6020820190508181035f83015261646e81616435565b9050919050565b7f4e6f742061206d656d62657200000000000000000000000000000000000000005f82015250565b5f6164a9600c8361521a565b91506164b482616475565b602082019050919050565b5f6020820190508181035f8301526164d68161649d565b9050919050565b5f6080820190508181035f8301526164f58187615cd3565b90508181036020830152616509818661522a565b9050616518604083018561508d565b616525606083018461540f565b95945050505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b5f815461656781615c91565b6165718186615ee5565b9450600182165f811461658b57600181146165a0576165d2565b60ff19831686528115158202860193506165d2565b6165a985615cc1565b5f5b838110156165ca578154818901526001820191506020810190506165ab565b838801955050505b50505092915050565b5f6165e6828461655b565b915081905092915050565b5f6165fb82615406565b91507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820361662d5761662c615b2d565b5b600182019050919050565b7f4e6f2063616e64696461746573000000000000000000000000000000000000005f82015250565b5f61666c600d8361521a565b915061667782616638565b602082019050919050565b5f6020820190508181035f83015261669981616660565b9050919050565b7f57696e6e6572206d757374206861766520636c61696d656420746f20726563655f8201527f697665206f776e65727368697000000000000000000000000000000000000000602082015250565b5f6166fa602d8361521a565b9150616705826166a0565b604082019050919050565b5f6020820190508181035f830152616727816166ee565b9050919050565b7f4d7573742062652061206d656d626572000000000000000000000000000000005f82015250565b5f61676260108361521a565b915061676d8261672e565b602082019050919050565b5f6020820190508181035f83015261678f81616756565b9050919050565b7f416c726561647920612063616e646964617465000000000000000000000000005f82015250565b5f6167ca60138361521a565b91506167d582616796565b602082019050919050565b5f6020820190508181035f8301526167f7816167be565b9050919050565b5f6060820190508181035f8301526168168186615cd3565b9050818103602083015261682a818561522a565b9050616839604083018461508d565b949350505050565b7f4172726179206c656e677468206d69736d6174636800000000000000000000005f82015250565b5f61687560158361521a565b915061688082616841565b602082019050919050565b5f6020820190508181035f8301526168a281616869565b9050919050565b7f55736572206d75737420626520612062756e646c65206d656d626572000000005f82015250565b5f6168dd601c8361521a565b91506168e8826168a9565b602082019050919050565b5f6020820190508181035f83015261690a816168d1565b9050919050565b7f50657263656e74616765206d75737420626520706f73697469766500000000005f82015250565b5f616945601b8361521a565b915061695082616911565b602082019050919050565b5f6020820190508181035f83015261697281616939565b9050919050565b7f50657263656e7461676573206d7573742073756d20746f2031303030300000005f82015250565b5f6169ad601d8361521a565b91506169b882616979565b602082019050919050565b5f6020820190508181035f8301526169da816169a1565b9050919050565b5f6040820190508181035f8301526169f98185615187565b90508181036020830152616a0d81846159d5565b90509392505050565b7f53746565706e657373206d7573742062652030203c2073203c203165313800005f82015250565b5f616a4a601e8361521a565b9150616a5582616a16565b602082019050919050565b5f6020820190508181035f830152616a7781616a3e565b9050919050565b7f566f746572206d7573742062652061206d656d626572000000000000000000005f82015250565b5f616ab260168361521a565b9150616abd82616a7e565b602082019050919050565b5f6020820190508181035f830152616adf81616aa6565b9050919050565b7f4e6f7420612076616c69642063616e64696461746500000000000000000000005f82015250565b5f616b1a60158361521a565b9150616b2582616ae6565b602082019050919050565b5f6020820190508181035f830152616b4781616b0e565b9050919050565b7f416c726561647920766f746564000000000000000000000000000000000000005f82015250565b5f616b82600d8361521a565b9150616b8d82616b4e565b602082019050919050565b5f6020820190508181035f830152616baf81616b76565b9050919050565b5f6040820190508181035f830152616bce818561522a565b90508181036020830152616be2818461522a565b90509392505050565b7f4469766973696f6e206279207a65726f000000000000000000000000000000005f82015250565b5f616c1f60108361521a565b9150616c2a82616beb565b602082019050919050565b5f6020820190508181035f830152616c4c81616c13565b9050919050565b5f616c5d82615406565b9150616c6883615406565b9250828202616c7681615406565b91508282048414831517616c8d57616c8c615b2d565b5b5092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f616ccb82615406565b9150616cd683615406565b925082616ce657616ce5616c94565b5b828204905092915050565b5f81905092915050565b5f819050815f5260205f209050919050565b5f8154616d1981615c91565b616d238186616cf1565b9450600182165f8114616d3d5760018114616d5257616d84565b60ff1983168652811515820286019350616d84565b616d5b85616cfb565b5f5b83811015616d7c57815481890152600182019150602081019050616d5d565b838801955050505b50505092915050565b5f616d988284616d0d565b915081905092915050565b5f81549050616db181615c91565b9050919050565b5f819050815f5260205f209050919050565b818103616dd8575050616ead565b616de182616da3565b67ffffffffffffffff811115616dfa57616df961529b565b5b616e048254615c91565b616e0f828285616166565b5f601f831160018114616e3c575f8415616e2a578287015490505b616e3485826161d4565b865550616ea6565b601f198416616e4a87616db8565b9650616e5586615cc1565b5f5b82811015616e7c57848901548255600182019150600185019450602081019050616e57565b86831015616e995784890154616e95601f8916826161b8565b8355505b6001600288020188555050505b5050505050505b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603160045260245ffd5b50565b5f616eea5f83616cf1565b9150616ef582616edc565b5f82019050919050565b5f616f0982616edf565b9150819050919050565b7f45544820636c61696d206661696c6564000000000000000000000000000000005f82015250565b5f616f4760108361521a565b9150616f5282616f13565b602082019050919050565b5f6020820190508181035f830152616f7481616f3b565b9050919050565b7f455448207472616e73666572206661696c6564000000000000000000000000005f82015250565b5f616faf60138361521a565b9150616fba82616f7b565b602082019050919050565b5f6020820190508181035f830152616fdc81616fa3565b9050919050565b5f606082019050616ff65f83018661540f565b6170036020830185615614565b8181036040830152617015818461522a565b9050949350505050565b5f60a0820190508181035f8301526170378188615cd3565b9050818103602083015261704b818761522a565b905061705a604083018661508d565b617067606083018561540f565b8181036080830152617079818461522a565b9050969550505050505056fea2646970667358221220e61ca743da8bf74312a4d4f6b348b3282428098da8234b281a8987056df9bb6364736f6c63430008140033",BundleABI={abi:abi,bytecode:bytecode},HolonsABI=[{type:"function",name:"getFlavorAddress",inputs:[{name:"_name",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"knownflavors",inputs:[{name:"",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"listFlavors",inputs:[],outputs:[{name:"",type:"string[]",internalType:"string[]"}],stateMutability:"view"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"newFlavor",inputs:[{name:"_flavorname",type:"string",internalType:"string"},{name:"_flavoraddress",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"newHolon",inputs:[{name:"_flavor",type:"string",internalType:"string"},{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"newHolonBundle",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManagedFactory",inputs:[{name:"_managedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setZonedFactory",inputs:[{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"HolonCreated",inputs:[{name:"holonAddress",type:"address",indexed:!0,internalType:"address"},{name:"holonName",type:"string",indexed:!1,internalType:"string"},{name:"flavor",type:"string",indexed:!1,internalType:"string"},{name:"creator",type:"address",indexed:!0,internalType:"address"},{name:"timestamp",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"NewFlavor",inputs:[{name:"flavor",type:"address",indexed:!0,internalType:"address"},{name:"name",type:"string",indexed:!1,internalType:"string"}],anonymous:!1},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],SplitterFactoryABI=[{type:"function",name:"createSplitter",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"managedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"},{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"setFactories",inputs:[{name:"_managedFactory",type:"address",internalType:"address"},{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setManagedFactory",inputs:[{name:"_managedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"setZonedFactory",inputs:[{name:"_zonedFactory",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"zonedFactory",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],ManagedFactoryABI=[{type:"constructor",inputs:[{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createManaged",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],ZonedFactoryABI=[{type:"constructor",inputs:[{name:"_botAddress",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"botAddress",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"createZoned",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],AppreciativeFactoryABI=[{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"newHolon",inputs:[{name:"creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_parameter",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],BundleFactoryABI=[{type:"function",name:"createBundle",inputs:[{name:"_creatorUserId",type:"string",internalType:"string"},{name:"_name",type:"string",internalType:"string"},{name:"_steepness",type:"uint256",internalType:"uint256"},{name:"_nzones",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"listHolons",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"listHolonsOf",inputs:[{name:"_address",type:"address",internalType:"address"}],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"toAddress",inputs:[{name:"",type:"string",internalType:"string"}],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"event",name:"NewHolon",inputs:[{name:"name",type:"string",indexed:!1,internalType:"string"},{name:"addr",type:"address",indexed:!1,internalType:"address"}],anonymous:!1}],TestTokenABI=[{type:"constructor",inputs:[{name:"initialSupply",type:"uint256",internalType:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"allowance",inputs:[{name:"owner",type:"address",internalType:"address"},{name:"spender",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"approve",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"balanceOf",inputs:[{name:"account",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"decimals",inputs:[],outputs:[{name:"",type:"uint8",internalType:"uint8"}],stateMutability:"view"},{type:"function",name:"name",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"symbol",inputs:[],outputs:[{name:"",type:"string",internalType:"string"}],stateMutability:"view"},{type:"function",name:"totalSupply",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"transfer",inputs:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"function",name:"transferFrom",inputs:[{name:"from",type:"address",internalType:"address"},{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"}],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"nonpayable"},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0,internalType:"address"},{name:"spender",type:"address",indexed:!0,internalType:"address"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0,internalType:"address"},{name:"to",type:"address",indexed:!0,internalType:"address"},{name:"value",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"error",name:"ERC20InsufficientAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"allowance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC20InsufficientBalance",inputs:[{name:"sender",type:"address",internalType:"address"},{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"ERC20InvalidApprover",inputs:[{name:"approver",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidReceiver",inputs:[{name:"receiver",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidSender",inputs:[{name:"sender",type:"address",internalType:"address"}]},{type:"error",name:"ERC20InvalidSpender",inputs:[{name:"spender",type:"address",internalType:"address"}]}],ABIs={Splitter:SplitterABI,Managed:ManagedABI,Zoned:ZonedABI,Appreciative:AppreciativeABI,Bundle:BundleABI,Holons:HolonsABI,SplitterFactory:SplitterFactoryABI,ManagedFactory:ManagedFactoryABI,ZonedFactory:ZonedFactoryABI,AppreciativeFactory:AppreciativeFactoryABI,BundleFactory:BundleFactoryABI,TestToken:TestTokenABI};class ContractDeployer{constructor(e){this.chainManager=e,this.deployedContracts={},this.ethers=null}async _loadEthers(){return this.ethers||(this.ethers=await Promise.resolve().then(()=>require("./index-COpLk9gL.cjs"))),this.ethers}async deployAll(e={}){const t=await this._loadEthers(),n=this.chainManager.getSigner(),s=await n.getAddress(),r=e.botAddress||s,i=e.testTokenSupply||"1000000",a=!1!==e.deployTestToken,o=e.onProgress||(()=>{}),l={network:this.chainManager.networkName,chainId:this.chainManager.getChainId(),deployer:s,botAddress:r,timestamp:(new Date).toISOString(),contracts:{}};try{o({step:1,total:a?8:7,message:"Deploying ManagedFactory..."});const e=await this._deployContract(ManagedFactoryABI.abi,ManagedFactoryABI.bytecode,[r]);l.contracts.managedFactory=e.address,o({step:1,done:!0,address:e.address}),o({step:2,total:a?8:7,message:"Deploying ZonedFactory..."});const n=await this._deployContract(ZonedFactoryABI.abi,ZonedFactoryABI.bytecode,[r]);l.contracts.zonedFactory=n.address,o({step:2,done:!0,address:n.address}),o({step:3,total:a?8:7,message:"Deploying SplitterFactory..."});const s=await this._deployContract(SplitterFactoryABI.abi,SplitterFactoryABI.bytecode,[]);l.contracts.splitterFactory=s.address,o({step:3,done:!0,address:s.address}),o({step:4,total:a?8:7,message:"Deploying AppreciativeFactory..."});const c=await this._deployContract(AppreciativeFactoryABI.abi,AppreciativeFactoryABI.bytecode,[]);l.contracts.appreciativeFactory=c.address,o({step:4,done:!0,address:c.address}),o({step:5,total:a?8:7,message:"Deploying BundleFactory..."});const u=await this._deployContract(BundleFactoryABI.abi,BundleFactoryABI.bytecode,[]);l.contracts.bundleFactory=u.address,o({step:5,done:!0,address:u.address}),o({step:6,total:a?8:7,message:"Deploying Holons Registry..."});const d=await this._deployContract(HolonsABI.abi,HolonsABI.bytecode,[]);if(l.contracts.holons=d.address,o({step:6,done:!0,address:d.address}),o({step:7,total:a?8:7,message:"Configuring Holons Registry..."}),await d.contract.setFactories(e.address,n.address),await d.contract.newFlavor("Splitter",s.address),await d.contract.newFlavor("Managed",e.address),await d.contract.newFlavor("Zoned",n.address),await d.contract.newFlavor("Appreciative",c.address),await d.contract.newFlavor("Bundle",u.address),o({step:7,done:!0,message:"Registry configured"}),a){o({step:8,total:8,message:"Deploying TestToken..."});const e=t.parseEther(i),n=await this._deployContract(TestTokenABI.abi,TestTokenABI.bytecode,[e]);l.contracts.testToken=n.address,o({step:8,done:!0,address:n.address})}this.deployedContracts=l.contracts,l.explorerUrls={};for(const[t,r]of Object.entries(l.contracts)){const e=getAddressUrl(l.network,r);e&&(l.explorerUrls[t]=e)}return l}catch(c){throw new Error(`Deployment failed: ${c.message}`)}}async deploySplitter(e,t,n=70,s={}){const r=this.chainManager.getSigner(),i=await r.getAddress(),a=s.creatorUserId||e,o=s.managedFactory||this.deployedContracts.managedFactory,l=s.zonedFactory||this.deployedContracts.zonedFactory;if(!o||!l)throw new Error("Factories not deployed. Run deployAll() first or provide factory addresses.");const c=await this._deployContract(SplitterABI.abi,SplitterABI.bytecode,[i,a,t,n,o,l]);return await c.contract.setContractSplit(n,100-n),await c.contract.createManagedContract(a,t,0),await c.contract.createZonedContract(a,t,6),{...c,holonId:e,type:"Splitter",splitPercentage:n}}async deployManaged(e,t={}){const n=this.chainManager.getSigner(),s=await n.getAddress(),r=t.botAddress||s;return{...await this._deployContract(ManagedABI.abi,ManagedABI.bytecode,[s,e,r]),type:"Managed"}}async deployZoned(e,t=6,n={}){const s=this.chainManager.getSigner(),r=await s.getAddress(),i=n.botAddress||r,a=n.creatorUserId||"creator";return{...await this._deployContract(ZonedABI.abi,ZonedABI.bytecode,[a,r,e,t,i]),type:"Zoned",nZones:t}}async deployAppreciative(e,t,n={}){const s=this.chainManager.getSigner(),r=await s.getAddress();return{...await this._deployContract(AppreciativeABI.abi,AppreciativeABI.bytecode,[e,t,r]),type:"Appreciative"}}async deployBundle(e,t,n=6,s={}){const r=await this._loadEthers(),i=this.chainManager.getSigner(),a=await i.getAddress(),o=s.creatorUserId||"creator",l=t||r.parseEther("0.5"),c=BundleABI.abi||BundleABI,u=BundleABI.bytecode;if(!u)throw new Error("Bundle bytecode not available. Please rebuild contracts.");return{...await this._deployContract(c,u,[a,o,e,l,n]),type:"Bundle",steepness:l,nZones:n,creatorUserId:o,name:e}}async deployBundleDirect(e,t,n={}){const s=n.steepness,r=n.nZones||6;return this.deployBundle(t,s,r,{creatorUserId:e,...n})}async deployTestToken(e="1000000"){const t=(await this._loadEthers()).parseEther(e);return{...await this._deployContract(TestTokenABI.abi,TestTokenABI.bytecode,[t]),type:"TestToken",initialSupply:e}}async createHolonBundle(e,t,n=70){if(!this.deployedContracts.holons)throw new Error("Holons registry not deployed. Run deployAll() first.");const s=await this.chainManager.getContract(this.deployedContracts.holons,HolonsABI.abi),r=await s.newHolonBundle(e,t,n),i=await r.wait(),a=i.logs.find(e=>{try{const t=s.interface.parseLog(e);return"NewHolon"===t?.name}catch{return!1}});return{address:a?s.interface.parseLog(a).args.addr:await s.toAddress(t),txHash:i.hash,name:t,creatorUserId:e}}async getContract(e,t){const n=ABIs[t];if(!n)throw new Error(`Unknown contract type: ${t}`);return this.chainManager.getContract(e,n.abi)}getDeployedAddresses(){return{...this.deployedContracts}}loadDeployedAddresses(e){this.deployedContracts={...e}}async _deployContract(e,t,n){const s=await this.chainManager.deployContract(e,t,n);return{contract:s.contract,address:s.address,txHash:s.txHash,explorerUrl:getAddressUrl(this.chainManager.networkName,s.address)}}}class ContractOperations{constructor(e,t,n){this.contract=e,this.type=t,this.chainManager=n,this.ethers=null}async _loadEthers(){return this.ethers||(this.ethers=await Promise.resolve().then(()=>require("./index-COpLk9gL.cjs"))),this.ethers}async addMember(e){const t=await this.contract.addMember(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async addMembers(e){const t=await this.contract.addMembers(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async getMembers(){await this.contract.userIds();try{const e=[];let t=0;for(;;)try{const n=await this.contract.userIds(t);e.push(n),t++}catch{break}return e}catch{return[]}}async isMember(e){try{return"Splitter"===this.type?await this.contract.isSplitterMember(e):await this.contract.isMember(e)}catch{return!1}}async getUserAddress(e){return this.contract.userIdToAddress(e)}async reward(e,t){const n=await this._loadEthers(),s="string"==typeof t?n.parseUnits(t,18):t,r=await this.contract.reward(e,s),i=await r.wait();return{txHash:i.hash,receipt:i}}async rewardEth(e){const t=(await this._loadEthers()).parseEther(e),n=await this.contract.reward("0x0000000000000000000000000000000000000000",t,{value:t}),s=await n.wait();return{txHash:s.hash,receipt:s}}async sendEth(e){const t=await this._loadEthers(),n=this.chainManager.getSigner(),s=t.parseEther(e),r=await n.sendTransaction({to:await this.contract.getAddress(),value:s}),i=await r.wait();return{txHash:i.hash,receipt:i}}async claim(e,t){const n=await this.contract.claim(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getEthBalance(e){const t=await this._loadEthers(),n=await this.contract.etherBalance(e);return t.formatEther(n)}async getTokenBalance(e,t){const n=await this._loadEthers(),s=await this.contract.tokenBalance(e,t);return n.formatUnits(s,18)}async hasClaimed(e){return this.contract.hasClaimed(e)}async getTotalDeposited(e){const t=await this._loadEthers(),n=await this.contract.totalDeposited(e);return t.formatUnits(n,18)}async setContractSplit(e,t){if(this._requireType(["Splitter"]),e+t!==100)throw new Error("Percentages must sum to 100");const n=await this.contract.setContractSplit(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getContractSplit(){this._requireType(["Splitter"]);const e=await this.contract.internalContractSplitPercentage(),t=await this.contract.externalContractSplitPercentage();return{internal:Number(e),external:Number(t)}}async createManagedContract(e,t,n=0){this._requireType(["Splitter"]);const s=await this.contract.createManagedContract(e,t,n),r=await s.wait();return{address:await this.contract.contractsByType(`${t}_managed`),txHash:r.hash,receipt:r}}async createZonedContract(e,t,n=6){this._requireType(["Splitter"]);const s=await this.contract.createZonedContract(e,t,n),r=await s.wait();return{address:await this.contract.contractsByType(`${t}_zoned`),txHash:r.hash,receipt:r}}async getChildContractKeys(){return this._requireType(["Splitter"]),this.contract.getContractKeys()}async getChildContracts(){this._requireType(["Splitter"]);const[e,t]=await this.contract.getContractAddresses();return{keys:e,addresses:t}}async getChildContract(e){return this._requireType(["Splitter"]),this.contract.contractsByType(e)}async setAppreciation(e,t){if(this._requireType(["Managed"]),e.length!==t.length)throw new Error("userIds and amounts arrays must have same length");const n=await this.contract.setAppreciation(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getAppreciation(e){this._requireType(["Managed"]);const t=await this.contract.appreciation(e);return Number(t)}async getTotalAppreciation(){this._requireType(["Managed"]);const e=await this.contract.totalappreciation();return Number(e)}async addToZone(e,t,n){this._requireType(["Zoned"]);const s=await this.contract.addToZone(e,t,n),r=await s.wait();return{txHash:r.hash,receipt:r}}async removeFromZone(e,t){this._requireType(["Zoned"]);const n=await this.contract.removeFromZone(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async getZone(e){this._requireType(["Zoned"]);const t=await this.contract.zones(e);return Number(t)}async getNumZones(){this._requireType(["Zoned"]);const e=await this.contract.nzones();return Number(e)}async setZoneParameters(e,t,n,s){this._requireType(["Zoned"]);const r=await this.contract.setRewardFunction(e,t,n,s),i=await r.wait();return{txHash:i.hash,receipt:i}}async appreciate(e,t,n){this._requireType(["Appreciative"]);const s=await this.contract.appreciate(e,t,n),r=await s.wait();return{txHash:r.hash,receipt:r}}async getAppreciationGiven(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationGiven(e);return Number(t)}async getAppreciationReceived(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationReceived(e);return Number(t)}async getAppreciationRemaining(e){this._requireType(["Appreciative"]);const t=await this.contract.appreciationRemaining(e);return Number(t)}async setSteepness(e){this._requireType(["Bundle"]);const t=await this._loadEthers(),n="string"==typeof e?t.parseEther(e):e,s=await this.contract.setSteepness(n),r=await s.wait();return{txHash:r.hash,receipt:r}}async getSteepness(){this._requireType(["Bundle"]);const e=await this._loadEthers(),t=await this.contract.steepness();return e.formatEther(t)}async setInteriorSplit(e,t){this._requireType(["Bundle"]);if(100!==t.reduce((e,t)=>e+t,0))throw new Error("Percentages must sum to 100");const n=await this.contract.setInteriorSplit(e,t),s=await n.wait();return{txHash:s.hash,receipt:s}}async startElection(){this._requireType(["Bundle"]);const e=await this.contract.startElection(),t=await e.wait();return{txHash:t.hash,receipt:t}}async nominateSelf(){this._requireType(["Bundle"]);const e=await this.contract.nominateSelf(),t=await e.wait();return{txHash:t.hash,receipt:t}}async vote(e){this._requireType(["Bundle"]);const t=await this.contract.vote(e),n=await t.wait();return{txHash:n.hash,receipt:n}}async finalizeElection(){this._requireType(["Bundle"]);const e=await this.contract.finalizeElection(),t=await e.wait();return{txHash:t.hash,receipt:t}}async getName(){return this.contract.name()}async getOwner(){return this.contract.owner()}async getBotAddress(){try{return await this.contract.botAddress()}catch{return null}}async getCreatorUserId(){try{return await this.contract.creatorUserId()}catch{return null}}async getAddress(){return this.contract.getAddress()}getType(){return this.type}_requireType(e){if(!e.includes(this.type))throw new Error(`Operation only available for ${e.join("/")} contracts. This is a ${this.type} contract.`)}getRawContract(){return this.contract}async call(e,...t){return this.contract[e](...t)}async send(e,...t){const n=await this.contract[e](...t),s=await n.wait();return{txHash:s.hash,receipt:s}}}class HolonContracts{constructor(e,t){this.chainManager=e,this.deployer=t||new ContractDeployer(e),this.holonContracts=new Map,this.storage=null}setStorage(e){this.storage=e}async deploy(e,t="Splitter",n={}){if(this.holonContracts.has(e))throw new Error(`Holon ${e} already has a contract. Use unlink() first to remove it.`);const s=n.name||e,r=n.creatorUserId||e;let i;switch(t){case"Splitter":i=await this.deployer.deploySplitter(e,s,n.splitPercentage||70,{creatorUserId:r,...n});break;case"Managed":i=await this.deployer.deployManaged(s,n);break;case"Zoned":i=await this.deployer.deployZoned(s,n.nZones||6,n);break;case"Appreciative":i=await this.deployer.deployAppreciative(s,r,n);break;case"Bundle":i=await this.deployer.deployBundle(s,n.steepness,n.nZones||6,{creatorUserId:r,...n});break;default:throw new Error(`Unknown contract type: ${t}`)}const a=new ContractOperations(i.contract,t,this.chainManager),o={holonId:e,address:i.address,type:t,contract:i.contract,operations:a,deployedAt:(new Date).toISOString(),txHash:i.txHash};return this.holonContracts.set(e,o),await this._saveMapping(e,o),{contract:i.contract,address:i.address,operations:a,txHash:i.txHash,type:t}}async link(e,t,n="Splitter"){if(this.holonContracts.has(e))throw new Error(`Holon ${e} already has a contract. Use unlink() first.`);const s=ABIs[n];if(!s)throw new Error(`Unknown contract type: ${n}`);const r=await this.chainManager.getContract(t,s.abi);try{await r.name()}catch(o){throw new Error(`Invalid contract at ${t}: ${o.message}`)}const i=new ContractOperations(r,n,this.chainManager),a={holonId:e,address:t,type:n,contract:r,operations:i,linkedAt:(new Date).toISOString()};return this.holonContracts.set(e,a),await this._saveMapping(e,a),{contract:r,address:t,operations:i,type:n}}async unlink(e){return!!this.holonContracts.has(e)&&(this.holonContracts.delete(e),this.storage&&await(this.storage.delete?.(`holon_contract:${e}`)),!0)}getContract(e){const t=this.holonContracts.get(e);return t?.contract||null}getAddress(e){const t=this.holonContracts.get(e);return t?.address||null}getOperations(e){const t=this.holonContracts.get(e);return t?.operations||null}getType(e){const t=this.holonContracts.get(e);return t?.type||null}hasContract(e){return this.holonContracts.has(e)}listAll(){const e=[];for(const[t,n]of this.holonContracts)e.push({holonId:t,address:n.address,type:n.type,deployedAt:n.deployedAt,linkedAt:n.linkedAt});return e}getByType(e){const t=[];for(const[n,s]of this.holonContracts)s.type===e&&t.push({holonId:n,address:s.address});return t}async loadFromStorage(){if(!this.storage)return 0;const e=await(this.storage.get?.("holon_contracts_index"))||[];let t=0;for(const s of e)try{const e=await(this.storage.get?.(`holon_contract:${s}`));if(e&&e.address&&e.type){const n=ABIs[e.type];if(n){const r=await this.chainManager.getContract(e.address,n.abi),i=new ContractOperations(r,e.type,this.chainManager);this.holonContracts.set(s,{...e,contract:r,operations:i}),t++}}}catch(n){console.warn(`Failed to load contract for holon ${s}: ${n.message}`)}return t}async _saveMapping(e,t){if(!this.storage)return;await(this.storage.set?.(`holon_contract:${e}`,{holonId:t.holonId,address:t.address,type:t.type,deployedAt:t.deployedAt,linkedAt:t.linkedAt,txHash:t.txHash}));const n=await(this.storage.get?.("holon_contracts_index"))||[];n.includes(e)||(n.push(e),await(this.storage.set?.("holon_contracts_index",n)))}requireOperations(e){const t=this.getOperations(e);if(!t)throw new Error(`Holon ${e} has no linked contract. Deploy or link one first.`);return t}}const SANKEY_EVENTS={FundsReceived:"FundsReceived",FundsCascaded:"FundsCascaded",FundsAllocated:"FundsAllocated",FundsClaimed:"FundsClaimed",FundsTransferred:"FundsTransferred",DistributionCompleted:"DistributionCompleted",ChildContractCreated:"ChildContractCreated",HolonCreated:"HolonCreated",MemberAdded:"MemberAdded",MemberRemoved:"MemberRemoved",WeightChanged:"WeightChanged",ZoneAssigned:"ZoneAssigned",AppreciationGiven:"AppreciationGiven",SplitConfigured:"SplitConfigured",ContractSplitConfigured:"ContractSplitConfigured"};class EventListener{constructor(e){this.chainManager=e,this.listeners=new Map,this.eventHistory=[],this.sankeyNodes=new Map,this.sankeyLinks=[]}async listenToContract(e,t,n){const s=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","DistributionCompleted","MemberAdded","WeightChanged","ZoneAssigned","AppreciationGiven"];for(const i of s)try{const s=n.filters[i]?.();s&&n.on(i,(...n)=>{this._handleEvent(i,n,e,t)})}catch(r){}this.listeners.set(e,{contract:n,holonId:t})}stopListening(e){const t=this.listeners.get(e);t&&(t.contract.removeAllListeners(),this.listeners.delete(e))}stopAll(){for(const[e,t]of this.listeners)t.contract.removeAllListeners();this.listeners.clear()}_handleEvent(e,t,n,s){const r=t[t.length-1],i={type:e,contractAddress:n,holonId:s,timestamp:Date.now(),blockNumber:r?.blockNumber,transactionHash:r?.transactionHash,data:this._parseEventData(e,t)};this.eventHistory.push(i),this._updateSankeyData(i),"undefined"!=typeof window&&window.dispatchEvent(new CustomEvent("sankey-event",{detail:i}))}_parseEventData(e,t){switch(e){case"FundsReceived":return{contractAddress:t[0],sender:t[1],tokenAddress:t[2],amount:t[3]?.toString()};case"FundsCascaded":return{fromContract:t[0],toContract:t[1],fromHolonId:t[2],toHolonId:t[3],tokenAddress:t[4],amount:t[5]?.toString(),splitType:t[6]};case"FundsAllocated":return{contractAddress:t[0],holonId:t[1],userId:t[2],tokenAddress:t[3],amount:t[4]?.toString(),distributionType:t[5]};case"FundsClaimed":return{contractAddress:t[0],holonId:t[1],userId:t[2],beneficiary:t[3],tokenAddress:t[4],amount:t[5]?.toString()};case"FundsTransferred":return{contractAddress:t[0],holonId:t[1],userId:t[2],recipient:t[3],tokenAddress:t[4],amount:t[5]?.toString()};case"DistributionCompleted":return{contractAddress:t[0],holonId:t[1],tokenAddress:t[2],totalAmount:t[3]?.toString(),recipientCount:Number(t[4]),cascadeCount:Number(t[5])};case"MemberAdded":return{contractAddress:t[0],holonId:t[1],userId:t[2],addedBy:t[3]};case"WeightChanged":return{contractAddress:t[0],holonId:t[1],userId:t[2],oldWeight:t[3]?.toString(),newWeight:t[4]?.toString()};case"ZoneAssigned":return{contractAddress:t[0],holonId:t[1],userId:t[2],oldZone:t[3]?.toString(),newZone:t[4]?.toString()};case"AppreciationGiven":return{contractAddress:t[0],holonId:t[1],fromUserId:t[2],toUserId:t[3],amount:t[4]?.toString()};default:return{raw:t.slice(0,-1)}}}_updateSankeyData(e){const{type:t,data:n}=e;switch(t){case"FundsReceived":this._ensureNode(n.sender,"external","External"),this._ensureNode(n.contractAddress,"contract",e.holonId),this.sankeyLinks.push({source:n.sender,target:n.contractAddress,value:BigInt(n.amount),token:n.tokenAddress,type:"external_inflow"});break;case"FundsCascaded":this._ensureNode(n.fromContract,"contract",n.fromHolonId),this._ensureNode(n.toContract,"contract",n.toHolonId),this.sankeyLinks.push({source:n.fromContract,target:n.toContract,value:BigInt(n.amount),token:n.tokenAddress,type:"cascade",splitType:n.splitType});break;case"FundsAllocated":this._ensureNode(n.contractAddress,"contract",n.holonId),this._ensureNode(n.userId,"user",n.userId),this.sankeyLinks.push({source:n.contractAddress,target:n.userId,value:BigInt(n.amount),token:n.tokenAddress,type:"allocation",distributionType:n.distributionType});break;case"FundsClaimed":case"FundsTransferred":this._ensureNode(n.userId,"user",n.userId),this._ensureNode(n.beneficiary||n.recipient,"wallet",(n.beneficiary||n.recipient).slice(0,8)+"..."),this.sankeyLinks.push({source:n.userId,target:n.beneficiary||n.recipient,value:BigInt(n.amount),token:n.tokenAddress,type:"FundsClaimed"===t?"claim":"transfer"});break;case"MemberAdded":this._ensureNode(n.userId,"user",n.userId)}}_ensureNode(e,t,n){this.sankeyNodes.has(e)||this.sankeyNodes.set(e,{id:e,type:t,label:n})}getSankeyData(e={}){const{tokenAddress:t,fromBlock:n,toBlock:s,minValue:r}=e;let i=[...this.sankeyLinks];if(t&&(i=i.filter(e=>e.token===t)),r){const e=BigInt(r);i=i.filter(t=>t.value>=e)}const a=new Set;i.forEach(e=>{a.add(e.source),a.add(e.target)});const o=[...a].map(e=>{const t=this.sankeyNodes.get(e)||{id:e,type:"unknown",label:e};return{id:t.id,name:t.label,type:t.type}}),l=new Map;o.forEach((e,t)=>l.set(e.id,t));return{nodes:o,links:i.map(e=>({source:l.get(e.source),target:l.get(e.target),value:Number(e.value)/1e18,type:e.type,splitType:e.splitType,distributionType:e.distributionType,token:e.token}))}}getFlowSummary(){const e={totalInflow:0n,totalOutflow:0n,byDistributionType:{appreciation:0n,equal:0n,zone:0n,percentage:0n,peer_appreciation:0n}};for(const t of this.sankeyLinks)"external_inflow"===t.type&&(e.totalInflow+=t.value),"claim"!==t.type&&"transfer"!==t.type||(e.totalOutflow+=t.value),t.distributionType&&void 0!==e.byDistributionType[t.distributionType]&&(e.byDistributionType[t.distributionType]+=t.value);return{totalInflow:e.totalInflow.toString(),totalOutflow:e.totalOutflow.toString(),totalInflowEth:Number(e.totalInflow)/1e18,totalOutflowEth:Number(e.totalOutflow)/1e18,byDistributionType:Object.fromEntries(Object.entries(e.byDistributionType).map(([e,t])=>[e,t.toString()]))}}async queryPastEvents(e,t,n={}){const{fromBlock:s=0,toBlock:r="latest"}=n;try{const n=e.filters[t]?.();if(!n)return[];return(await e.queryFilter(n,s,r)).map(e=>({type:t,contractAddress:e.address,blockNumber:e.blockNumber,transactionHash:e.transactionHash,data:this._parseEventData(t,e.args)}))}catch(i){return console.error(`Error querying ${t}:`,i),[]}}async buildFromHistory(e,t,n={}){const s=["FundsReceived","FundsCascaded","FundsAllocated","FundsClaimed","FundsTransferred","MemberAdded"];for(const r of s){const s=await this.queryPastEvents(e,r,n);for(const e of s)e.holonId=t,this.eventHistory.push(e),this._updateSankeyData(e)}return this.getSankeyData()}clear(){this.eventHistory=[],this.sankeyNodes.clear(),this.sankeyLinks=[]}export(){return{events:this.eventHistory,nodes:Object.fromEntries(this.sankeyNodes),links:this.sankeyLinks.map(e=>({...e,value:e.value.toString()}))}}import(e){this.eventHistory=e.events||[],this.sankeyNodes=new Map(Object.entries(e.nodes||{})),this.sankeyLinks=(e.links||[]).map(e=>({...e,value:BigInt(e.value)}))}}const version="6.16.0";function checkType(e,t,n){const s=t.split("|").map(e=>e.trim());for(let i=0;i<s.length;i++)switch(t){case"any":return;case"bigint":case"boolean":case"number":case"string":if(typeof e===t)return}const r=new Error(`invalid value for type ${t}`);throw r.code="INVALID_ARGUMENT",r.argument=`value.${n}`,r.value=e,r}async function resolveProperties(e){const t=Object.keys(e);return(await Promise.all(t.map(t=>Promise.resolve(e[t])))).reduce((e,n,s)=>(e[t[s]]=n,e),{})}function defineProperties(e,t,n){for(let s in t){let r=t[s];const i=n?n[s]:null;i&&checkType(r,i,s),Object.defineProperty(e,s,{enumerable:!0,value:r,writable:!1})}}function stringify(e,t){if(null==e)return"null";if(null==t&&(t=new Set),"object"==typeof e){if(t.has(e))return"[Circular]";t.add(e)}if(Array.isArray(e))return"[ "+e.map(e=>stringify(e,t)).join(", ")+" ]";if(e instanceof Uint8Array){const t="0123456789abcdef";let n="0x";for(let s=0;s<e.length;s++)n+=t[e[s]>>4],n+=t[15&e[s]];return n}if("object"==typeof e&&"function"==typeof e.toJSON)return stringify(e.toJSON(),t);switch(typeof e){case"boolean":case"number":case"symbol":return e.toString();case"bigint":return BigInt(e).toString();case"string":return JSON.stringify(e);case"object":{const n=Object.keys(e);return n.sort(),"{ "+n.map(n=>`${stringify(n,t)}: ${stringify(e[n],t)}`).join(", ")+" }"}}return"[ COULD NOT SERIALIZE ]"}function isError(e,t){return e&&e.code===t}function isCallException(e){return isError(e,"CALL_EXCEPTION")}function makeError(e,t,n){let s,r=e;{const s=[];if(n){if("message"in n||"code"in n||"name"in n)throw new Error(`value will overwrite populated values: ${stringify(n)}`);for(const e in n){if("shortMessage"===e)continue;const t=n[e];s.push(e+"="+stringify(t))}}s.push(`code=${t}`),s.push(`version=${version}`),s.length&&(e+=" ("+s.join(", ")+")")}switch(t){case"INVALID_ARGUMENT":s=new TypeError(e);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":s=new RangeError(e);break;default:s=new Error(e)}return defineProperties(s,{code:t}),n&&Object.assign(s,n),null==s.shortMessage&&defineProperties(s,{shortMessage:r}),s}function assert(e,t,n,s){if(!e)throw makeError(t,n,s)}function assertArgument(e,t,n,s){assert(e,t,"INVALID_ARGUMENT",{argument:n,value:s})}function assertArgumentCount(e,t,n){null==n&&(n=""),n&&(n=": "+n),assert(e>=t,"missing argument"+n,"MISSING_ARGUMENT",{count:e,expectedCount:t}),assert(e<=t,"too many arguments"+n,"UNEXPECTED_ARGUMENT",{count:e,expectedCount:t})}const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((e,t)=>{try{if("test"!=="test".normalize(t))throw new Error("bad");if("NFD"===t){const e=String.fromCharCode(233).normalize("NFD");if(e!==String.fromCharCode(101,769))throw new Error("broken")}e.push(t)}catch(n){}return e},[]);function assertNormalize(e){assert(_normalizeForms.indexOf(e)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:e}})}function assertPrivate(e,t,n){if(null==n&&(n=""),e!==t){let e=n,t="new";n&&(e+=".",t+=" "+n),assert(!1,`private constructor; use ${e}from* methods`,"UNSUPPORTED_OPERATION",{operation:t})}}function _getBytes(e,t,n){if(e instanceof Uint8Array)return n?new Uint8Array(e):e;if("string"==typeof e&&e.length%2==0&&e.match(/^0x[0-9a-f]*$/i)){const t=new Uint8Array((e.length-2)/2);let n=2;for(let s=0;s<t.length;s++)t[s]=parseInt(e.substring(n,n+2),16),n+=2;return t}assertArgument(!1,"invalid BytesLike value",t||"value",e)}function getBytes(e,t){return _getBytes(e,t,!1)}function getBytesCopy(e,t){return _getBytes(e,t,!0)}function isHexString(e,t){return!("string"!=typeof e||!e.match(/^0x[0-9A-Fa-f]*$/))&&(("number"!=typeof t||e.length===2+2*t)&&(!0!==t||e.length%2==0))}function isBytesLike(e){return isHexString(e,!0)||e instanceof Uint8Array}const HexCharacters="0123456789abcdef";function hexlify(e){const t=getBytes(e);let n="0x";for(let s=0;s<t.length;s++){const e=t[s];n+=HexCharacters[(240&e)>>4]+HexCharacters[15&e]}return n}function concat(e){return"0x"+e.map(e=>hexlify(e).substring(2)).join("")}function dataLength(e){return isHexString(e,!0)?(e.length-2)/2:getBytes(e).length}function dataSlice(e,t,n){const s=getBytes(e);return null!=n&&n>s.length&&assert(!1,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:s,length:s.length,offset:n}),hexlify(s.slice(null==t?0:t,null==n?s.length:n))}function stripZerosLeft(e){let t=hexlify(e).substring(2);for(;t.startsWith("00");)t=t.substring(2);return"0x"+t}function zeroPad(e,t,n){const s=getBytes(e);assert(t>=s.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(s),length:t,offset:t+1});const r=new Uint8Array(t);return r.fill(0),n?r.set(s,t-s.length):r.set(s,0),hexlify(r)}function zeroPadValue(e,t){return zeroPad(e,t,!0)}function zeroPadBytes(e,t){return zeroPad(e,t,!1)}const BN_0$5=BigInt(0),BN_1$2=BigInt(1),maxValue=9007199254740991;function fromTwos(e,t){const n=getUint(e,"value"),s=BigInt(getNumber(t,"width"));if(assert(n>>s===BN_0$5,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:e}),n>>s-BN_1$2){return-((~n&(BN_1$2<<s)-BN_1$2)+BN_1$2)}return n}function toTwos(e,t){let n=getBigInt(e,"value");const s=BigInt(getNumber(t,"width")),r=BN_1$2<<s-BN_1$2;if(n<BN_0$5){n=-n,assert(n<=r,"too low","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e});return(~n&(BN_1$2<<s)-BN_1$2)+BN_1$2}return assert(n<r,"too high","NUMERIC_FAULT",{operation:"toTwos",fault:"overflow",value:e}),n}function mask(e,t){const n=getUint(e,"value"),s=BigInt(getNumber(t,"bits"));return n&(BN_1$2<<s)-BN_1$2}function getBigInt(e,t){switch(typeof e){case"bigint":return e;case"number":return assertArgument(Number.isInteger(e),"underflow",t||"value",e),assertArgument(e>=-maxValue&&e<=maxValue,"overflow",t||"value",e),BigInt(e);case"string":try{if(""===e)throw new Error("empty string");return"-"===e[0]&&"-"!==e[1]?-BigInt(e.substring(1)):BigInt(e)}catch(n){assertArgument(!1,`invalid BigNumberish string: ${n.message}`,t||"value",e)}}assertArgument(!1,"invalid BigNumberish value",t||"value",e)}function getUint(e,t){const n=getBigInt(e,t);return assert(n>=BN_0$5,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:e}),n}const Nibbles="0123456789abcdef";function toBigInt(e){if(e instanceof Uint8Array){let t="0x0";for(const n of e)t+=Nibbles[n>>4],t+=Nibbles[15&n];return BigInt(t)}return getBigInt(e)}function getNumber(e,t){switch(typeof e){case"bigint":return assertArgument(e>=-maxValue&&e<=maxValue,"overflow",t||"value",e),Number(e);case"number":return assertArgument(Number.isInteger(e),"underflow",t||"value",e),assertArgument(e>=-maxValue&&e<=maxValue,"overflow",t||"value",e),e;case"string":try{if(""===e)throw new Error("empty string");return getNumber(BigInt(e),t)}catch(n){assertArgument(!1,`invalid numeric string: ${n.message}`,t||"value",e)}}assertArgument(!1,"invalid numeric value",t||"value",e)}function toNumber(e){return getNumber(toBigInt(e))}function toBeHex(e,t){const n=getUint(e,"value");let s=n.toString(16);if(null==t)s.length%2&&(s="0"+s);else{const r=getNumber(t,"width");if(0===r&&n===BN_0$5)return"0x";for(assert(2*r>=s.length,`value exceeds width (${r} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:e});s.length<2*r;)s="0"+s}return"0x"+s}function toBeArray(e,t){const n=getUint(e,"value");if(n===BN_0$5){const e=null!=t?getNumber(t,"width"):0;return new Uint8Array(e)}let s=n.toString(16);if(s.length%2&&(s="0"+s),null!=t){const n=getNumber(t,"width");for(;s.length<2*n;)s="00"+s;assert(2*n===s.length,`value exceeds width (${n} bytes)`,"NUMERIC_FAULT",{operation:"toBeArray",fault:"overflow",value:e})}const r=new Uint8Array(s.length/2);for(let i=0;i<r.length;i++){const e=2*i;r[i]=parseInt(s.substring(e,e+2),16)}return r}function toQuantity(e){let t=hexlify(isBytesLike(e)?e:toBeArray(e)).substring(2);for(;t.startsWith("0");)t=t.substring(1);return""===t&&(t="0"),"0x"+t}class EventPayload{filter;emitter;#e;constructor(e,t,n){this.#e=t,defineProperties(this,{emitter:e,filter:n})}async removeListener(){null!=this.#e&&await this.emitter.off(this.filter,this.#e)}}function errorFunc(e,t,n,s,r){assertArgument(!1,`invalid codepoint at offset ${t}; ${e}`,"bytes",n)}function ignoreFunc(e,t,n,s,r){if("BAD_PREFIX"===e||"UNEXPECTED_CONTINUE"===e){let e=0;for(let s=t+1;s<n.length&&n[s]>>6==2;s++)e++;return e}return"OVERRUN"===e?n.length-t-1:0}function replaceFunc(e,t,n,s,r){return"OVERLONG"===e?(assertArgument("number"==typeof r,"invalid bad code point for replacement","badCodepoint",r),s.push(r),0):(s.push(65533),ignoreFunc(e,t,n))}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(e,t){null==t&&(t=Utf8ErrorFuncs.error);const n=getBytes(e,"bytes"),s=[];let r=0;for(;r<n.length;){const e=n[r++];if(!(e>>7)){s.push(e);continue}let i=null,a=null;if(192==(224&e))i=1,a=127;else if(224==(240&e))i=2,a=2047;else{if(240!=(248&e)){r+=t(128==(192&e)?"UNEXPECTED_CONTINUE":"BAD_PREFIX",r-1,n,s);continue}i=3,a=65535}if(r-1+i>=n.length){r+=t("OVERRUN",r-1,n,s);continue}let o=e&(1<<8-i-1)-1;for(let l=0;l<i;l++){let e=n[r];if(128!=(192&e)){r+=t("MISSING_CONTINUE",r,n,s),o=null;break}o=o<<6|63&e,r++}null!==o&&(o>1114111?r+=t("OUT_OF_RANGE",r-1-i,n,s,o):o>=55296&&o<=57343?r+=t("UTF16_SURROGATE",r-1-i,n,s,o):o<=a?r+=t("OVERLONG",r-1-i,n,s,o):s.push(o))}return s}function toUtf8Bytes(e,t){assertArgument("string"==typeof e,"invalid string value","str",e),null!=t&&(assertNormalize(t),e=e.normalize(t));let n=[];for(let s=0;s<e.length;s++){const t=e.charCodeAt(s);if(t<128)n.push(t);else if(t<2048)n.push(t>>6|192),n.push(63&t|128);else if(55296==(64512&t)){s++;const r=e.charCodeAt(s);assertArgument(s<e.length&&56320==(64512&r),"invalid surrogate pair","str",e);const i=65536+((1023&t)<<10)+(1023&r);n.push(i>>18|240),n.push(i>>12&63|128),n.push(i>>6&63|128),n.push(63&i|128)}else n.push(t>>12|224),n.push(t>>6&63|128),n.push(63&t|128)}return new Uint8Array(n)}function _toUtf8String(e){return e.map(e=>e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10&1023),56320+(1023&e)))).join("")}function toUtf8String(e,t){return _toUtf8String(getUtf8CodePoints(e,t))}function toUtf8CodePoints(e,t){return getUtf8CodePoints(toUtf8Bytes(e,t))}const BN_N1=BigInt(-1),BN_0$4=BigInt(0),BN_1$1=BigInt(1),BN_5=BigInt(5),_guard$2={};let Zeros="0000";for(;Zeros.length<80;)Zeros+=Zeros;function getTens(e){let t=Zeros;for(;t.length<e;)t+=t;return BigInt("1"+t.substring(0,e))}function checkValue(e,t,n){const s=BigInt(t.width);if(t.signed){const t=BN_1$1<<s-BN_1$1;assert(null==n||e>=-t&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=e>BN_0$4?fromTwos(mask(e,s),s):-fromTwos(mask(-e,s),s)}else{const t=BN_1$1<<s;assert(null==n||e>=0&&e<t,"overflow","NUMERIC_FAULT",{operation:n,fault:"overflow",value:e}),e=(e%t+t)%t&t-BN_1$1}return e}function getFormat(e){"number"==typeof e&&(e=`fixed128x${e}`);let t=!0,n=128,s=18;if("string"==typeof e)if("fixed"===e);else if("ufixed"===e)t=!1;else{const r=e.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);assertArgument(r,"invalid fixed format","format",e),t="u"!==r[1],n=parseInt(r[2]),s=parseInt(r[3])}else if(e){const r=e,i=(e,t,n)=>null==r[e]?n:(assertArgument(typeof r[e]===t,"invalid fixed format ("+e+" not "+t+")","format."+e,r[e]),r[e]);t=i("signed","boolean",t),n=i("width","number",n),s=i("decimals","number",s)}assertArgument(n%8==0,"invalid FixedNumber width (not byte aligned)","format.width",n),assertArgument(s<=80,"invalid FixedNumber decimals (too large)","format.decimals",s);return{signed:t,width:n,decimals:s,name:(t?"":"u")+"fixed"+String(n)+"x"+String(s)}}function toString(e,t){let n="";e<BN_0$4&&(n="-",e*=BN_N1);let s=e.toString();if(0===t)return n+s;for(;s.length<=t;)s=Zeros+s;const r=s.length-t;for(s=s.substring(0,r)+"."+s.substring(r);"0"===s[0]&&"."!==s[1];)s=s.substring(1);for(;"0"===s[s.length-1]&&"."!==s[s.length-2];)s=s.substring(0,s.length-1);return n+s}class FixedNumber{format;#t;#n;#s;_value;constructor(e,t,n){assertPrivate(e,_guard$2,"FixedNumber"),this.#n=t,this.#t=n;const s=toString(t,n.decimals);defineProperties(this,{format:n.name,_value:s}),this.#s=getTens(n.decimals)}get signed(){return this.#t.signed}get width(){return this.#t.width}get decimals(){return this.#t.decimals}get value(){return this.#n}#r(e){assertArgument(this.format===e.format,"incompatible format; use fixedNumber.toFormat","other",e)}#i(e,t){return e=checkValue(e,this.#t,t),new FixedNumber(_guard$2,e,this.#t)}#a(e,t){return this.#r(e),this.#i(this.#n+e.#n,t)}addUnsafe(e){return this.#a(e)}add(e){return this.#a(e,"add")}#o(e,t){return this.#r(e),this.#i(this.#n-e.#n,t)}subUnsafe(e){return this.#o(e)}sub(e){return this.#o(e,"sub")}#l(e,t){return this.#r(e),this.#i(this.#n*e.#n/this.#s,t)}mulUnsafe(e){return this.#l(e)}mul(e){return this.#l(e,"mul")}mulSignal(e){this.#r(e);const t=this.#n*e.#n;return assert(t%this.#s===BN_0$4,"precision lost during signalling mul","NUMERIC_FAULT",{operation:"mulSignal",fault:"underflow",value:this}),this.#i(t/this.#s,"mulSignal")}#c(e,t){return assert(e.#n!==BN_0$4,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#r(e),this.#i(this.#n*this.#s/e.#n,t)}divUnsafe(e){return this.#c(e)}div(e){return this.#c(e,"div")}divSignal(e){assert(e.#n!==BN_0$4,"division by zero","NUMERIC_FAULT",{operation:"div",fault:"divide-by-zero",value:this}),this.#r(e);const t=this.#n*this.#s;return assert(t%e.#n===BN_0$4,"precision lost during signalling div","NUMERIC_FAULT",{operation:"divSignal",fault:"underflow",value:this}),this.#i(t/e.#n,"divSignal")}cmp(e){let t=this.value,n=e.value;const s=this.decimals-e.decimals;return s>0?n*=getTens(s):s<0&&(t*=getTens(-s)),t<n?-1:t>n?1:0}eq(e){return 0===this.cmp(e)}lt(e){return this.cmp(e)<0}lte(e){return this.cmp(e)<=0}gt(e){return this.cmp(e)>0}gte(e){return this.cmp(e)>=0}floor(){let e=this.#n;return this.#n<BN_0$4&&(e-=this.#s-BN_1$1),e=this.#n/this.#s*this.#s,this.#i(e,"floor")}ceiling(){let e=this.#n;return this.#n>BN_0$4&&(e+=this.#s-BN_1$1),e=this.#n/this.#s*this.#s,this.#i(e,"ceiling")}round(e){if(null==e&&(e=0),e>=this.decimals)return this;const t=this.decimals-e,n=BN_5*getTens(t-1);let s=this.value+n;const r=getTens(t);return s=s/r*r,checkValue(s,this.#t,"round"),new FixedNumber(_guard$2,s,this.#t)}isZero(){return this.#n===BN_0$4}isNegative(){return this.#n<BN_0$4}toString(){return this._value}toUnsafeFloat(){return parseFloat(this.toString())}toFormat(e){return FixedNumber.fromString(this.toString(),e)}static fromValue(e,t,n){const s=null==t?0:getNumber(t),r=getFormat(n);let i=getBigInt(e,"value");const a=s-r.decimals;if(a>0){const t=getTens(a);assert(i%t===BN_0$4,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:e}),i/=t}else a<0&&(i*=getTens(-a));return checkValue(i,r,"fromValue"),new FixedNumber(_guard$2,i,r)}static fromString(e,t){const n=e.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(n&&n[2].length+n[3].length>0,"invalid FixedNumber string value","value",e);const s=getFormat(t);let r=n[2]||"0",i=n[3]||"";for(;i.length<s.decimals;)i+=Zeros;assert(i.substring(s.decimals).match(/^0*$/),"too many decimals for format","NUMERIC_FAULT",{operation:"fromString",fault:"underflow",value:e}),i=i.substring(0,s.decimals);const a=BigInt(n[1]+r+i);return checkValue(a,s,"fromString"),new FixedNumber(_guard$2,a,s)}static fromBytes(e,t){let n=toBigInt(getBytes(e,"value"));const s=getFormat(t);return s.signed&&(n=fromTwos(n,s.width)),checkValue(n,s,"fromBytes"),new FixedNumber(_guard$2,n,s)}}const names=["wei","kwei","mwei","gwei","szabo","finney","ether"];function formatUnits(e,t){let n=18;if("string"==typeof t){const e=names.indexOf(t);assertArgument(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=getNumber(t,"unit"));return FixedNumber.fromValue(e,n,{decimals:n,width:512}).toString()}function parseUnits(e,t){assertArgument("string"==typeof e,"value must be a string","value",e);let n=18;if("string"==typeof t){const e=names.indexOf(t);assertArgument(e>=0,"invalid unit","unit",t),n=3*e}else null!=t&&(n=getNumber(t,"unit"));return FixedNumber.fromString(e,{decimals:n,width:512}).value}function formatEther(e){return formatUnits(e,18)}function parseEther(e){return parseUnits(e,18)}const WordSize=32,Padding=new Uint8Array(WordSize),passProperties$1=["then"],_guard$1={},resultNames=new WeakMap;function getNames(e){return resultNames.get(e)}function setNames(e,t){resultNames.set(e,t)}function throwError(e,t){const n=new Error(`deferred error during ABI decoding triggered accessing ${e}`);throw n.error=t,n}function toObject(e,t,n){return e.indexOf(null)>=0?t.map((e,t)=>e instanceof Result?toObject(getNames(e),e,n):e):e.reduce((e,s,r)=>{let i=t.getValue(s);return s in e||(n&&i instanceof Result&&(i=toObject(getNames(i),i,n)),e[s]=i),e},{})}class Result extends Array{#u;constructor(...e){const t=e[0];let n=e[1],s=(e[2]||[]).slice(),r=!0;t!==_guard$1&&(n=e,s=[],r=!1),super(n.length),n.forEach((e,t)=>{this[t]=e});const i=s.reduce((e,t)=>("string"==typeof t&&e.set(t,(e.get(t)||0)+1),e),new Map);if(setNames(this,Object.freeze(n.map((e,t)=>{const n=s[t];return null!=n&&1===i.get(n)?n:null}))),this.#u=[],null==this.#u&&this.#u,!r)return;Object.freeze(this);const a=new Proxy(this,{get:(e,t,n)=>{if("string"==typeof t){if(t.match(/^[0-9]+$/)){const n=getNumber(t,"%index");if(n<0||n>=this.length)throw new RangeError("out of result range");const s=e[n];return s instanceof Error&&throwError(`index ${n}`,s),s}if(passProperties$1.indexOf(t)>=0)return Reflect.get(e,t,n);const s=e[t];if(s instanceof Function)return function(...t){return s.apply(this===n?e:this,t)};if(!(t in e))return e.getValue.apply(this===n?e:this,[t])}return Reflect.get(e,t,n)}});return setNames(a,getNames(this)),a}toArray(e){const t=[];return this.forEach((n,s)=>{n instanceof Error&&throwError(`index ${s}`,n),e&&n instanceof Result&&(n=n.toArray(e)),t.push(n)}),t}toObject(e){const t=getNames(this);return t.reduce((n,s,r)=>(assert(null!=s,`value at index ${r} unnamed`,"UNSUPPORTED_OPERATION",{operation:"toObject()"}),toObject(t,this,e)),{})}slice(e,t){null==e&&(e=0),e<0&&(e+=this.length)<0&&(e=0),null==t&&(t=this.length),t<0&&(t+=this.length)<0&&(t=0),t>this.length&&(t=this.length);const n=getNames(this),s=[],r=[];for(let i=e;i<t;i++)s.push(this[i]),r.push(n[i]);return new Result(_guard$1,s,r)}filter(e,t){const n=getNames(this),s=[],r=[];for(let i=0;i<this.length;i++){const a=this[i];a instanceof Error&&throwError(`index ${i}`,a),e.call(t,a,i,this)&&(s.push(a),r.push(n[i]))}return new Result(_guard$1,s,r)}map(e,t){const n=[];for(let s=0;s<this.length;s++){const r=this[s];r instanceof Error&&throwError(`index ${s}`,r),n.push(e.call(t,r,s,this))}return n}getValue(e){const t=getNames(this).indexOf(e);if(-1===t)return;const n=this[t];return n instanceof Error&&throwError(`property ${JSON.stringify(e)}`,n.error),n}static fromItems(e,t){return new Result(_guard$1,e,t)}}function checkResultErrors(e){const t=[],n=function(e,s){if(Array.isArray(s))for(let i in s){const a=e.slice();a.push(i);try{n(a,s[i])}catch(r){t.push({path:a,error:r})}}};return n([],e),t}function getValue$1(e){let t=toBeArray(e);return assert(t.length<=WordSize,"value out-of-bounds","BUFFER_OVERRUN",{buffer:t,length:WordSize,offset:t.length}),t.length!==WordSize&&(t=getBytesCopy(concat([Padding.slice(t.length%WordSize),t]))),t}class Coder{name;type;localName;dynamic;constructor(e,t,n,s){defineProperties(this,{name:e,type:t,localName:n,dynamic:s},{name:"string",type:"string",localName:"string",dynamic:"boolean"})}_throwError(e,t){assertArgument(!1,e,this.localName,t)}}class Writer{#d;#f;constructor(){this.#d=[],this.#f=0}get data(){return concat(this.#d)}get length(){return this.#f}#h(e){return this.#d.push(e),this.#f+=e.length,e.length}appendWriter(e){return this.#h(getBytesCopy(e.data))}writeBytes(e){let t=getBytesCopy(e);const n=t.length%WordSize;return n&&(t=getBytesCopy(concat([t,Padding.slice(n)]))),this.#h(t)}writeValue(e){return this.#h(getValue$1(e))}writeUpdatableValue(){const e=this.#d.length;return this.#d.push(Padding),this.#f+=WordSize,t=>{this.#d[e]=getValue$1(t)}}}class Reader{allowLoose;#d;#p;#y;#g;#m;constructor(e,t,n){defineProperties(this,{allowLoose:!!t}),this.#d=getBytesCopy(e),this.#y=0,this.#g=null,this.#m=null!=n?n:1024,this.#p=0}get data(){return hexlify(this.#d)}get dataLength(){return this.#d.length}get consumed(){return this.#p}get bytes(){return new Uint8Array(this.#d)}#b(e){if(this.#g)return this.#g.#b(e);this.#y+=e,assert(this.#m<1||this.#y<=this.#m*this.dataLength,`compressed ABI data exceeds inflation ratio of ${this.#m} ( see: https://github.com/ethers-io/ethers.js/issues/4537 )`,"BUFFER_OVERRUN",{buffer:getBytesCopy(this.#d),offset:this.#p,length:e,info:{bytesRead:this.#y,dataLength:this.dataLength}})}#w(e,t,n){let s=Math.ceil(t/WordSize)*WordSize;return this.#p+s>this.#d.length&&(this.allowLoose&&n&&this.#p+t<=this.#d.length?s=t:assert(!1,"data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#d),length:this.#d.length,offset:this.#p+s})),this.#d.slice(this.#p,this.#p+s)}subReader(e){const t=new Reader(this.#d.slice(this.#p+e),this.allowLoose,this.#m);return t.#g=this,t}readBytes(e,t){let n=this.#w(0,e,!!t);return this.#b(e),this.#p+=n.length,n.slice(0,e)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function number(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}function bytes(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(e.outputLen),number(e.blockLen)}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}`)}const crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,u8a=e=>e instanceof Uint8Array,u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),rotr=(e,t)=>e<<32-t|e>>>t,isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0];
16
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */if(!isLE)throw new Error("Non little-endian hardware is not supported");const nextTick=async()=>{};async function asyncLoop(e,t,n){let s=Date.now();for(let r=0;r<e;r++){n(r);const e=Date.now()-s;e>=0&&e<t||(await nextTick(),s+=e)}}function utf8ToBytes(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function toBytes(e){if("string"==typeof e&&(e=utf8ToBytes(e)),!u8a(e))throw new Error("expected Uint8Array, got "+typeof e);return e}function concatBytes(...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}class Hash{clone(){return this._cloneInto()}}const toStr={}.toString;function checkOpts(e,t){if(void 0!==t&&"[object Object]"!==toStr.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)}function wrapConstructor(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));throw new Error("crypto.getRandomValues must be defined")}const U32_MASK64=BigInt(2**32-1),_32n=BigInt(32);function fromBig(e,t=!1){return t?{h:Number(e&U32_MASK64),l:Number(e>>_32n&U32_MASK64)}:{h:0|Number(e>>_32n&U32_MASK64),l:0|Number(e&U32_MASK64)}}function split(e,t=!1){let n=new Uint32Array(e.length),s=new Uint32Array(e.length);for(let r=0;r<e.length;r++){const{h:i,l:a}=fromBig(e[r],t);[n[r],s[r]]=[i,a]}return[n,s]}const toBig=(e,t)=>BigInt(e>>>0)<<_32n|BigInt(t>>>0),shrSH=(e,t,n)=>e>>>n,shrSL=(e,t,n)=>e<<32-n|t>>>n,rotrSH=(e,t,n)=>e>>>n|t<<32-n,rotrSL=(e,t,n)=>e<<32-n|t>>>n,rotrBH=(e,t,n)=>e<<64-n|t>>>n-32,rotrBL=(e,t,n)=>e>>>n-32|t<<64-n,rotr32H=(e,t)=>t,rotr32L=(e,t)=>e,rotlSH=(e,t,n)=>e<<n|t>>>32-n,rotlSL=(e,t,n)=>t<<n|e>>>32-n,rotlBH=(e,t,n)=>t<<n-32|e>>>64-n,rotlBL=(e,t,n)=>e<<n-32|t>>>64-n;function add(e,t,n,s){const r=(t>>>0)+(s>>>0);return{h:e+n+(r/2**32|0)|0,l:0|r}}const add3L=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),add3H=(e,t,n,s)=>t+n+s+(e/2**32|0)|0,add4L=(e,t,n,s)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0),add4H=(e,t,n,s,r)=>t+n+s+r+(e/2**32|0)|0,add5L=(e,t,n,s,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(s>>>0)+(r>>>0),add5H=(e,t,n,s,r,i)=>t+n+s+r+i+(e/2**32|0)|0,u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L},[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]],_0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),_7n=BigInt(7),_256n=BigInt(256),_0x71n=BigInt(113);for(let e=0,t=_1n,s=1,r=0;e<24;e++){[s,r]=[r,(2*s+3*r)%5],SHA3_PI.push(2*(5*r+s)),SHA3_ROTL.push((e+1)*(e+2)/2%64);let n=_0n;for(let e=0;e<7;e++)t=(t<<_1n^(t>>_7n)*_0x71n)%_256n,t&_2n&&(n^=_1n<<(_1n<<BigInt(e))-_1n);_SHA3_IOTA.push(n)}const[SHA3_IOTA_H,SHA3_IOTA_L]=split(_SHA3_IOTA,!0),rotlH=(e,t,n)=>n>32?rotlBH(e,t,n):rotlSH(e,t,n),rotlL=(e,t,n)=>n>32?rotlBL(e,t,n):rotlSL(e,t,n);function keccakP(e,t=24){const n=new Uint32Array(10);for(let s=24-t;s<24;s++){for(let s=0;s<10;s++)n[s]=e[s]^e[s+10]^e[s+20]^e[s+30]^e[s+40];for(let s=0;s<10;s+=2){const t=(s+8)%10,r=(s+2)%10,i=n[r],a=n[r+1],o=rotlH(i,a,1)^n[t],l=rotlL(i,a,1)^n[t+1];for(let n=0;n<50;n+=10)e[s+n]^=o,e[s+n+1]^=l}let t=e[2],r=e[3];for(let n=0;n<24;n++){const s=SHA3_ROTL[n],i=rotlH(t,r,s),a=rotlL(t,r,s),o=SHA3_PI[n];t=e[o],r=e[o+1],e[o]=i,e[o+1]=a}for(let s=0;s<50;s+=10){for(let t=0;t<10;t++)n[t]=e[s+t];for(let t=0;t<10;t++)e[s+t]^=~n[(t+2)%10]&n[(t+4)%10]}e[0]^=SHA3_IOTA_H[s],e[1]^=SHA3_IOTA_L[s]}n.fill(0)}class Keccak extends Hash{constructor(e,t,n,s=!1,r=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=s,this.rounds=r,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,number(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){exists(this);const{blockLen:t,state:n}=this,s=(e=toBytes(e)).length;for(let r=0;r<s;){const i=Math.min(t-this.pos,s-r);for(let t=0;t<i;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:s}=this;e[n]^=t,128&t&&n===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){exists(this,!1),bytes(e),this.finish();const t=this.state,{blockLen:n}=this;for(let s=0,r=e.length;s<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-s);e.set(t.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:s,rounds:r,enableXOF:i}=this;return e||(e=new Keccak(t,n,s,i,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}}const gen=(e,t,n)=>wrapConstructor(()=>new Keccak(t,e,n)),keccak_256=gen(1,136,32);let locked=!1;const _keccak256=function(e){return keccak_256(e)};let __keccak256=_keccak256;function keccak256(e){const t=getBytes(e,"data");return hexlify(__keccak256(t))}keccak256._=_keccak256,keccak256.lock=function(){locked=!0},keccak256.register=function(e){if(locked)throw new TypeError("keccak256 is locked");__keccak256=e},Object.freeze(keccak256);const ZeroAddress="0x0000000000000000000000000000000000000000",BN_0$3=BigInt(0),BN_36=BigInt(36);function getChecksumAddress(e){const t=(e=e.toLowerCase()).substring(2).split(""),n=new Uint8Array(40);for(let r=0;r<40;r++)n[r]=t[r].charCodeAt(0);const s=getBytes(keccak256(n));for(let r=0;r<40;r+=2)s[r>>1]>>4>=8&&(t[r]=t[r].toUpperCase()),(15&s[r>>1])>=8&&(t[r+1]=t[r+1].toUpperCase());return"0x"+t.join("")}const ibanLookup={};for(let e=0;e<10;e++)ibanLookup[String(e)]=String(e);for(let e=0;e<26;e++)ibanLookup[String.fromCharCode(65+e)]=String(10+e);const safeDigits=15;function ibanChecksum(e){let t=(e=(e=e.toUpperCase()).substring(4)+e.substring(0,2)+"00").split("").map(e=>ibanLookup[e]).join("");for(;t.length>=safeDigits;){let e=t.substring(0,safeDigits);t=parseInt(e,10)%97+t.substring(e.length)}let n=String(98-parseInt(t,10)%97);for(;n.length<2;)n="0"+n;return n}const Base36=function(){const e={};for(let t=0;t<36;t++){e["0123456789abcdefghijklmnopqrstuvwxyz"[t]]=BigInt(t)}return e}();function fromBase36(e){e=e.toLowerCase();let t=BN_0$3;for(let n=0;n<e.length;n++)t=t*BN_36+Base36[e[n]];return t}function getAddress(e){if(assertArgument("string"==typeof e,"invalid address","address",e),e.match(/^(0x)?[0-9a-fA-F]{40}$/)){e.startsWith("0x")||(e="0x"+e);const t=getChecksumAddress(e);return assertArgument(!e.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||t===e,"bad address checksum","address",e),t}if(e.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)){assertArgument(e.substring(2,4)===ibanChecksum(e),"bad icap checksum","address",e);let t=fromBase36(e.substring(4)).toString(16);for(;t.length<40;)t="0"+t;return getChecksumAddress("0x"+t)}assertArgument(!1,"invalid address","address",e)}function getIcapAddress(e){let t=BigInt(getAddress(e)).toString(36).toUpperCase();for(;t.length<30;)t="0"+t;return"XE"+ibanChecksum("XE00"+t)+t}function isAddressable(e){return e&&"function"==typeof e.getAddress}function isAddress(e){try{return getAddress(e),!0}catch(t){}return!1}async function checkAddress(e,t){const n=await t;return null!=n&&"0x0000000000000000000000000000000000000000"!==n||(assert("string"!=typeof e,"unconfigured name","UNCONFIGURED_NAME",{value:e}),assertArgument(!1,"invalid AddressLike value; did not resolve to a value address","target",e)),getAddress(n)}function resolveAddress(e,t){return"string"==typeof e?e.match(/^0x[0-9a-f]{40}$/i)?getAddress(e):(assert(null!=t,"ENS resolution requires a provider","UNSUPPORTED_OPERATION",{operation:"resolveName"}),checkAddress(e,t.resolveName(e))):isAddressable(e)?checkAddress(e,e.getAddress()):e&&"function"==typeof e.then?checkAddress(e,e):void assertArgument(!1,"unsupported addressable value","target",e)}const _gaurd={};function n(e,t){let n=!1;return t<0&&(n=!0,t*=-1),new Typed(_gaurd,`${n?"":"u"}int${t}`,e,{signed:n,width:t})}function b(e,t){return new Typed(_gaurd,`bytes${t||""}`,e,{size:t})}const _typedSymbol=Symbol.for("_ethers_typed");class Typed{type;value;#_;_typedSymbol;constructor(e,t,n,s){null==s&&(s=null),assertPrivate(_gaurd,e,"Typed"),defineProperties(this,{_typedSymbol:_typedSymbol,type:t,value:n}),this.#_=s,this.format()}format(){if("array"===this.type)throw new Error("");if("dynamicArray"===this.type)throw new Error("");return"tuple"===this.type?`tuple(${this.value.map(e=>e.format()).join(",")})`:this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return"string"===this.type}get tupleName(){if("tuple"!==this.type)throw TypeError("not a tuple");return this.#_}get arrayLength(){if("array"!==this.type)throw TypeError("not an array");return!0===this.#_?-1:!1===this.#_?this.value.length:null}static from(e,t){return new Typed(_gaurd,e,t)}static uint8(e){return n(e,8)}static uint16(e){return n(e,16)}static uint24(e){return n(e,24)}static uint32(e){return n(e,32)}static uint40(e){return n(e,40)}static uint48(e){return n(e,48)}static uint56(e){return n(e,56)}static uint64(e){return n(e,64)}static uint72(e){return n(e,72)}static uint80(e){return n(e,80)}static uint88(e){return n(e,88)}static uint96(e){return n(e,96)}static uint104(e){return n(e,104)}static uint112(e){return n(e,112)}static uint120(e){return n(e,120)}static uint128(e){return n(e,128)}static uint136(e){return n(e,136)}static uint144(e){return n(e,144)}static uint152(e){return n(e,152)}static uint160(e){return n(e,160)}static uint168(e){return n(e,168)}static uint176(e){return n(e,176)}static uint184(e){return n(e,184)}static uint192(e){return n(e,192)}static uint200(e){return n(e,200)}static uint208(e){return n(e,208)}static uint216(e){return n(e,216)}static uint224(e){return n(e,224)}static uint232(e){return n(e,232)}static uint240(e){return n(e,240)}static uint248(e){return n(e,248)}static uint256(e){return n(e,256)}static uint(e){return n(e,256)}static int8(e){return n(e,-8)}static int16(e){return n(e,-16)}static int24(e){return n(e,-24)}static int32(e){return n(e,-32)}static int40(e){return n(e,-40)}static int48(e){return n(e,-48)}static int56(e){return n(e,-56)}static int64(e){return n(e,-64)}static int72(e){return n(e,-72)}static int80(e){return n(e,-80)}static int88(e){return n(e,-88)}static int96(e){return n(e,-96)}static int104(e){return n(e,-104)}static int112(e){return n(e,-112)}static int120(e){return n(e,-120)}static int128(e){return n(e,-128)}static int136(e){return n(e,-136)}static int144(e){return n(e,-144)}static int152(e){return n(e,-152)}static int160(e){return n(e,-160)}static int168(e){return n(e,-168)}static int176(e){return n(e,-176)}static int184(e){return n(e,-184)}static int192(e){return n(e,-192)}static int200(e){return n(e,-200)}static int208(e){return n(e,-208)}static int216(e){return n(e,-216)}static int224(e){return n(e,-224)}static int232(e){return n(e,-232)}static int240(e){return n(e,-240)}static int248(e){return n(e,-248)}static int256(e){return n(e,-256)}static int(e){return n(e,-256)}static bytes1(e){return b(e,1)}static bytes2(e){return b(e,2)}static bytes3(e){return b(e,3)}static bytes4(e){return b(e,4)}static bytes5(e){return b(e,5)}static bytes6(e){return b(e,6)}static bytes7(e){return b(e,7)}static bytes8(e){return b(e,8)}static bytes9(e){return b(e,9)}static bytes10(e){return b(e,10)}static bytes11(e){return b(e,11)}static bytes12(e){return b(e,12)}static bytes13(e){return b(e,13)}static bytes14(e){return b(e,14)}static bytes15(e){return b(e,15)}static bytes16(e){return b(e,16)}static bytes17(e){return b(e,17)}static bytes18(e){return b(e,18)}static bytes19(e){return b(e,19)}static bytes20(e){return b(e,20)}static bytes21(e){return b(e,21)}static bytes22(e){return b(e,22)}static bytes23(e){return b(e,23)}static bytes24(e){return b(e,24)}static bytes25(e){return b(e,25)}static bytes26(e){return b(e,26)}static bytes27(e){return b(e,27)}static bytes28(e){return b(e,28)}static bytes29(e){return b(e,29)}static bytes30(e){return b(e,30)}static bytes31(e){return b(e,31)}static bytes32(e){return b(e,32)}static address(e){return new Typed(_gaurd,"address",e)}static bool(e){return new Typed(_gaurd,"bool",!!e)}static bytes(e){return new Typed(_gaurd,"bytes",e)}static string(e){return new Typed(_gaurd,"string",e)}static array(e,t){throw new Error("not implemented yet")}static tuple(e,t){throw new Error("not implemented yet")}static overrides(e){return new Typed(_gaurd,"overrides",Object.assign({},e))}static isTyped(e){return e&&"object"==typeof e&&"_typedSymbol"in e&&e._typedSymbol===_typedSymbol}static dereference(e,t){if(Typed.isTyped(e)){if(e.type!==t)throw new Error(`invalid type: expecetd ${t}, got ${e.type}`);return e.value}return e}}class AddressCoder extends Coder{constructor(e){super("address","address",e,!1)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(e,t){let n=Typed.dereference(t,"string");try{n=getAddress(n)}catch(s){return this._throwError(s.message,t)}return e.writeValue(n)}decode(e){return getAddress(toBeHex(e.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(e){super(e.name,e.type,"_",e.dynamic),this.coder=e}defaultValue(){return this.coder.defaultValue()}encode(e,t){return this.coder.encode(e,t)}decode(e){return this.coder.decode(e)}}function pack(e,t,n){let s=[];if(Array.isArray(n))s=n;else if(n&&"object"==typeof n){let e={};s=t.map(t=>{const s=t.localName;return assert(s,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),assert(!e[s],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:t},value:n}),e[s]=!0,n[s]})}else assertArgument(!1,"invalid tuple value","tuple",n);assertArgument(t.length===s.length,"types/value length mismatch","tuple",n);let r=new Writer,i=new Writer,a=[];t.forEach((e,t)=>{let n=s[t];if(e.dynamic){let t=i.length;e.encode(i,n);let s=r.writeUpdatableValue();a.push(e=>{s(e+t)})}else e.encode(r,n)}),a.forEach(e=>{e(r.length)});let o=e.appendWriter(r);return o+=e.appendWriter(i),o}function unpack(e,t){let n=[],s=[],r=e.subReader(0);return t.forEach(t=>{let i=null;if(t.dynamic){let n=e.readIndex(),s=r.subReader(n);try{i=t.decode(s)}catch(a){if(isError(a,"BUFFER_OVERRUN"))throw a;i=a,i.baseType=t.name,i.name=t.localName,i.type=t.type}}else try{i=t.decode(e)}catch(a){if(isError(a,"BUFFER_OVERRUN"))throw a;i=a,i.baseType=t.name,i.name=t.localName,i.type=t.type}if(null==i)throw new Error("investigate");n.push(i),s.push(t.localName||null)}),Result.fromItems(n,s)}class ArrayCoder extends Coder{coder;length;constructor(e,t,n){super("array",e.type+"["+(t>=0?t:"")+"]",n,-1===t||e.dynamic),defineProperties(this,{coder:e,length:t})}defaultValue(){const e=this.coder.defaultValue(),t=[];for(let n=0;n<this.length;n++)t.push(e);return t}encode(e,t){const n=Typed.dereference(t,"array");Array.isArray(n)||this._throwError("expected array value",n);let s=this.length;-1===s&&(s=n.length,e.writeValue(n.length)),assertArgumentCount(n.length,s,"coder array"+(this.localName?" "+this.localName:""));let r=[];for(let i=0;i<n.length;i++)r.push(this.coder);return pack(e,r,n)}decode(e){let t=this.length;-1===t&&(t=e.readIndex(),assert(t*WordSize<=e.dataLength,"insufficient data length","BUFFER_OVERRUN",{buffer:e.bytes,offset:t*WordSize,length:e.dataLength}));let n=[];for(let s=0;s<t;s++)n.push(new AnonymousCoder(this.coder));return unpack(e,n)}}class BooleanCoder extends Coder{constructor(e){super("bool","bool",e,!1)}defaultValue(){return!1}encode(e,t){const n=Typed.dereference(t,"bool");return e.writeValue(n?1:0)}decode(e){return!!e.readValue()}}class DynamicBytesCoder extends Coder{constructor(e,t){super(e,e,t,!0)}defaultValue(){return"0x"}encode(e,t){t=getBytesCopy(t);let n=e.writeValue(t.length);return n+=e.writeBytes(t),n}decode(e){return e.readBytes(e.readIndex(),!0)}}class BytesCoder extends DynamicBytesCoder{constructor(e){super("bytes",e)}decode(e){return hexlify(super.decode(e))}}class FixedBytesCoder extends Coder{size;constructor(e,t){let n="bytes"+String(e);super(n,n,t,!1),defineProperties(this,{size:e},{size:"number"})}defaultValue(){return"0x0000000000000000000000000000000000000000000000000000000000000000".substring(0,2+2*this.size)}encode(e,t){let n=getBytesCopy(Typed.dereference(t,this.type));return n.length!==this.size&&this._throwError("incorrect data length",t),e.writeBytes(n)}decode(e){return hexlify(e.readBytes(this.size))}}const Empty=new Uint8Array([]);class NullCoder extends Coder{constructor(e){super("null","",e,!1)}defaultValue(){return null}encode(e,t){return null!=t&&this._throwError("not null",t),e.writeBytes(Empty)}decode(e){return e.readBytes(0),null}}const BN_0$2=BigInt(0),BN_1=BigInt(1),BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");class NumberCoder extends Coder{size;signed;constructor(e,t,n){const s=(t?"int":"uint")+8*e;super(s,s,n,!1),defineProperties(this,{size:e,signed:t},{size:"number",signed:"boolean"})}defaultValue(){return 0}encode(e,t){let n=getBigInt(Typed.dereference(t,this.type)),s=mask(BN_MAX_UINT256,8*WordSize);if(this.signed){let e=mask(s,8*this.size-1);(n>e||n<-(e+BN_1))&&this._throwError("value out-of-bounds",t),n=toTwos(n,8*WordSize)}else(n<BN_0$2||n>mask(s,8*this.size))&&this._throwError("value out-of-bounds",t);return e.writeValue(n)}decode(e){let t=mask(e.readValue(),8*this.size);return this.signed&&(t=fromTwos(t,8*this.size)),t}}class StringCoder extends DynamicBytesCoder{constructor(e){super("string",e)}defaultValue(){return""}encode(e,t){return super.encode(e,toUtf8Bytes(Typed.dereference(t,"string")))}decode(e){return toUtf8String(super.decode(e))}}class TupleCoder extends Coder{coders;constructor(e,t){let n=!1;const s=[];e.forEach(e=>{e.dynamic&&(n=!0),s.push(e.type)});super("tuple","tuple("+s.join(",")+")",t,n),defineProperties(this,{coders:Object.freeze(e.slice())})}defaultValue(){const e=[];this.coders.forEach(t=>{e.push(t.defaultValue())});const t=this.coders.reduce((e,t)=>{const n=t.localName;return n&&(e[n]||(e[n]=0),e[n]++),e},{});return this.coders.forEach((n,s)=>{let r=n.localName;r&&1===t[r]&&("length"===r&&(r="_length"),null==e[r]&&(e[r]=e[s]))}),Object.freeze(e)}encode(e,t){const n=Typed.dereference(t,"tuple");return pack(e,this.coders,n)}decode(e){return unpack(e,this.coders)}}function accessSetify(e,t){return{address:getAddress(e),storageKeys:t.map((e,t)=>(assertArgument(isHexString(e,32),"invalid slot",`storageKeys[${t}]`,e),e.toLowerCase()))}}function accessListify(e){if(Array.isArray(e))return e.map((t,n)=>Array.isArray(t)?(assertArgument(2===t.length,"invalid slot set",`value[${n}]`,t),accessSetify(t[0],t[1])):(assertArgument(null!=t&&"object"==typeof t,"invalid address-slot set","value",e),accessSetify(t.address,t.storageKeys)));assertArgument(null!=e&&"object"==typeof e,"invalid access list","value",e);const t=Object.keys(e).map(t=>{const n=e[t].reduce((e,t)=>(e[t]=!0,e),{});return accessSetify(t,Object.keys(n).sort())});return t.sort((e,t)=>e.address.localeCompare(t.address)),t}function id(e){return keccak256(toUtf8Bytes(e))}function setify(e){const t=new Set;return e.forEach(e=>t.add(e)),Object.freeze(t)}const _kwVisibDeploy="external public payable override",KwVisibDeploy=setify(_kwVisibDeploy.split(" ")),_kwVisib="constant external internal payable private public pure view override",KwVisib=setify(_kwVisib.split(" ")),_kwTypes="constructor error event fallback function receive struct",KwTypes=setify(_kwTypes.split(" ")),_kwModifiers="calldata memory storage payable indexed",KwModifiers=setify(_kwModifiers.split(" ")),_kwOther="tuple returns",_keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" "),Keywords=setify(_keywords.split(" ")),SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"},regexWhitespacePrefix=new RegExp("^(\\s*)"),regexNumberPrefix=new RegExp("^([0-9]+)"),regexIdPrefix=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"),regexId=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"),regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class TokenString{#p;#v;get offset(){return this.#p}get length(){return this.#v.length-this.#p}constructor(e){this.#p=0,this.#v=e.slice()}clone(){return new TokenString(this.#v)}reset(){this.#p=0}#E(e=0,t=0){return new TokenString(this.#v.slice(e,t).map(t=>Object.freeze(Object.assign({},t,{match:t.match-e,linkBack:t.linkBack-e,linkNext:t.linkNext-e}))))}popKeyword(e){const t=this.peek();if("KEYWORD"!==t.type||!e.has(t.text))throw new Error(`expected keyword ${t.text}`);return this.pop().text}popType(e){if(this.peek().type!==e){const t=this.peek();throw new Error(`expected ${e}; got ${t.type} ${JSON.stringify(t.text)}`)}return this.pop().text}popParen(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=this.#E(this.#p+1,e.match+1);return this.#p=e.match+1,t}popParams(){const e=this.peek();if("OPEN_PAREN"!==e.type)throw new Error("bad start");const t=[];for(;this.#p<e.match-1;){const e=this.peek().linkNext;t.push(this.#E(this.#p+1,e)),this.#p=e}return this.#p=e.match+1,t}peek(){if(this.#p>=this.#v.length)throw new Error("out-of-bounds");return this.#v[this.#p]}peekKeyword(e){const t=this.peekType("KEYWORD");return null!=t&&e.has(t)?t:null}peekType(e){if(0===this.length)return null;const t=this.peek();return t.type===e?t.text:null}pop(){const e=this.peek();return this.#p++,e}toString(){const e=[];for(let t=this.#p;t<this.#v.length;t++){const n=this.#v[t];e.push(`${n.type}:${n.text}`)}return`<TokenString ${e.join(" ")}>`}}function lex(e){const t=[],n=t=>{const n=i<e.length?JSON.stringify(e[i]):"$EOI";throw new Error(`invalid token ${n} at ${i}: ${t}`)};let s=[],r=[],i=0;for(;i<e.length;){let a=e.substring(i),o=a.match(regexWhitespacePrefix);o&&(i+=o[1].length,a=e.substring(i));const l={depth:s.length,linkBack:-1,linkNext:-1,match:-1,type:"",text:"",offset:i,value:-1};t.push(l);let c=SimpleTokens[a[0]]||"";if(c){if(l.type=c,l.text=a[0],i++,"OPEN_PAREN"===c)s.push(t.length-1),r.push(t.length-1);else if("CLOSE_PAREN"==c)0===s.length&&n("no matching open bracket"),l.match=s.pop(),t[l.match].match=t.length-1,l.depth--,l.linkBack=r.pop(),t[l.linkBack].linkNext=t.length-1;else if("COMMA"===c)l.linkBack=r.pop(),t[l.linkBack].linkNext=t.length-1,r.push(t.length-1);else if("OPEN_BRACKET"===c)l.type="BRACKET";else if("CLOSE_BRACKET"===c){let e=t.pop().text;if(t.length>0&&"NUMBER"===t[t.length-1].type){const n=t.pop().text;e=n+e,t[t.length-1].value=getNumber(n)}if(0===t.length||"BRACKET"!==t[t.length-1].type)throw new Error("missing opening bracket");t[t.length-1].text+=e}}else if(o=a.match(regexIdPrefix),o){if(l.text=o[1],i+=l.text.length,Keywords.has(l.text)){l.type="KEYWORD";continue}if(l.text.match(regexType)){l.type="TYPE";continue}l.type="ID"}else{if(o=a.match(regexNumberPrefix),!o)throw new Error(`unexpected token ${JSON.stringify(a[0])} at position ${i}`);l.text=o[1],l.type="NUMBER",i+=l.text.length}}return new TokenString(t.map(e=>Object.freeze(e)))}function allowSingle(e,t){let n=[];for(const s in t.keys())e.has(s)&&n.push(s);if(n.length>1)throw new Error(`conflicting types: ${n.join(", ")}`)}function consumeName(e,t){if(t.peekKeyword(KwTypes)){const n=t.pop().text;if(n!==e)throw new Error(`expected ${e}, got ${n}`)}return t.popType("ID")}function consumeKeywords(e,t){const n=new Set;for(;;){const s=e.peekType("KEYWORD");if(null==s||t&&!t.has(s))break;if(e.pop(),n.has(s))throw new Error(`duplicate keywords: ${JSON.stringify(s)}`);n.add(s)}return Object.freeze(n)}function consumeMutability(e){let t=consumeKeywords(e,KwVisib);return allowSingle(t,setify("constant payable nonpayable".split(" "))),allowSingle(t,setify("pure view payable nonpayable".split(" "))),t.has("view")?"view":t.has("pure")?"pure":t.has("payable")?"payable":t.has("nonpayable")?"nonpayable":t.has("constant")?"view":"nonpayable"}function consumeParams(e,t){return e.popParams().map(e=>ParamType.from(e,t))}function consumeGas(e){if(e.peekType("AT")){if(e.pop(),e.peekType("NUMBER"))return getBigInt(e.pop().text);throw new Error("invalid gas")}return null}function consumeEoi(e){if(e.length)throw new Error(`unexpected tokens at offset ${e.offset}: ${e.toString()}`)}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(e){const t=e.match(regexType);if(assertArgument(t,"invalid type","type",e),"uint"===e)return"uint256";if("int"===e)return"int256";if(t[2]){const n=parseInt(t[2]);assertArgument(0!==n&&n<=32,"invalid bytes length","type",e)}else if(t[3]){const n=parseInt(t[3]);assertArgument(0!==n&&n<=256&&n%8==0,"invalid numeric width","type",e)}return e}const _guard={},internal$1=Symbol.for("_ethers_internal"),ParamTypeInternal="_ParamTypeInternal",ErrorFragmentInternal="_ErrorInternal",EventFragmentInternal="_EventInternal",ConstructorFragmentInternal="_ConstructorInternal",FallbackFragmentInternal="_FallbackInternal",FunctionFragmentInternal="_FunctionInternal",StructFragmentInternal="_StructInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(e,t,n,s,r,i,a,o){if(assertPrivate(e,_guard,"ParamType"),Object.defineProperty(this,internal$1,{value:ParamTypeInternal}),i&&(i=Object.freeze(i.slice())),"array"===s){if(null==a||null==o)throw new Error("")}else if(null!=a||null!=o)throw new Error("");if("tuple"===s){if(null==i)throw new Error("")}else if(null!=i)throw new Error("");defineProperties(this,{name:t,type:n,baseType:s,indexed:r,components:i,arrayLength:a,arrayChildren:o})}format(e){if(null==e&&(e="sighash"),"json"===e){const t=this.name||"";if(this.isArray()){const e=JSON.parse(this.arrayChildren.format("json"));return e.name=t,e.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`,JSON.stringify(e)}const n={type:"tuple"===this.baseType?"tuple":this.type,name:t};return"boolean"==typeof this.indexed&&(n.indexed=this.indexed),this.isTuple()&&(n.components=this.components.map(t=>JSON.parse(t.format(e)))),JSON.stringify(n)}let t="";return this.isArray()?(t+=this.arrayChildren.format(e),t+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`):this.isTuple()?t+="("+this.components.map(t=>t.format(e)).join("full"===e?", ":",")+")":t+=this.type,"sighash"!==e&&(!0===this.indexed&&(t+=" indexed"),"full"===e&&this.name&&(t+=" "+this.name)),t}isArray(){return"array"===this.baseType}isTuple(){return"tuple"===this.baseType}isIndexable(){return null!=this.indexed}walk(e,t){if(this.isArray()){if(!Array.isArray(e))throw new Error("invalid array value");if(-1!==this.arrayLength&&e.length!==this.arrayLength)throw new Error("array is wrong length");const n=this;return e.map(e=>n.arrayChildren.walk(e,t))}if(this.isTuple()){if(!Array.isArray(e))throw new Error("invalid tuple value");if(e.length!==this.components.length)throw new Error("array is wrong length");const n=this;return e.map((e,s)=>n.components[s].walk(e,t))}return t(this.type,e)}#A(e,t,n,s){if(this.isArray()){if(!Array.isArray(t))throw new Error("invalid array value");if(-1!==this.arrayLength&&t.length!==this.arrayLength)throw new Error("array is wrong length");const r=this.arrayChildren,i=t.slice();return i.forEach((t,s)=>{r.#A(e,t,n,e=>{i[s]=e})}),void s(i)}if(this.isTuple()){const r=this.components;let i;if(Array.isArray(t))i=t.slice();else{if(null==t||"object"!=typeof t)throw new Error("invalid tuple value");i=r.map(e=>{if(!e.name)throw new Error("cannot use object value with unnamed components");if(!(e.name in t))throw new Error(`missing value for component ${e.name}`);return t[e.name]})}if(i.length!==this.components.length)throw new Error("array is wrong length");return i.forEach((t,s)=>{r[s].#A(e,t,n,e=>{i[s]=e})}),void s(i)}const r=n(this.type,t);r.then?e.push(async function(){s(await r)}()):s(r)}async walkAsync(e,t){const n=[],s=[e];return this.#A(n,e,t,e=>{s[0]=e}),n.length&&await Promise.all(n),s[0]}static from(e,t){if(ParamType.isParamType(e))return e;if("string"==typeof e)try{return ParamType.from(lex(e),t)}catch(a){assertArgument(!1,"invalid param type","obj",e)}else if(e instanceof TokenString){let n="",s="",r=null;consumeKeywords(e,setify(["tuple"])).has("tuple")||e.peekType("OPEN_PAREN")?(s="tuple",r=e.popParams().map(e=>ParamType.from(e)),n=`tuple(${r.map(e=>e.format()).join(",")})`):(n=verifyBasicType(e.popType("TYPE")),s=n);let i=null,a=null;for(;e.length&&e.peekType("BRACKET");){const t=e.pop();i=new ParamType(_guard,"",n,s,null,r,a,i),a=t.value,n+=t.text,s="array",r=null}let o=null;if(consumeKeywords(e,KwModifiers).has("indexed")){if(!t)throw new Error("");o=!0}const l=e.peekType("ID")?e.pop().text:"";if(e.length)throw new Error("leftover tokens");return new ParamType(_guard,l,n,s,o,r,a,i)}const n=e.name;assertArgument(!n||"string"==typeof n&&n.match(regexId),"invalid name","obj.name",n);let s=e.indexed;null!=s&&(assertArgument(t,"parameter cannot be indexed","obj.indexed",e.indexed),s=!!s);let r=e.type,i=r.match(regexArrayType);if(i){const t=parseInt(i[2]||"-1"),a=ParamType.from({type:i[1],components:e.components});return new ParamType(_guard,n||"",r,"array",s,null,t,a)}if("tuple"===r||r.startsWith("tuple(")||r.startsWith("(")){const t=null!=e.components?e.components.map(e=>ParamType.from(e)):null;return new ParamType(_guard,n||"",r,"tuple",s,t,null,null)}return r=verifyBasicType(e.type),new ParamType(_guard,n||"",r,r,s,null,null,null)}static isParamType(e){return e&&e[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(e,t,n){assertPrivate(e,_guard,"Fragment"),defineProperties(this,{type:t,inputs:n=Object.freeze(n.slice())})}static from(e){if("string"==typeof e){try{Fragment.from(JSON.parse(e))}catch(t){}return Fragment.from(lex(e))}if(e instanceof TokenString){switch(e.peekKeyword(KwTypes)){case"constructor":return ConstructorFragment.from(e);case"error":return ErrorFragment.from(e);case"event":return EventFragment.from(e);case"fallback":case"receive":return FallbackFragment.from(e);case"function":return FunctionFragment.from(e);case"struct":return StructFragment.from(e)}}else if("object"==typeof e){switch(e.type){case"constructor":return ConstructorFragment.from(e);case"error":return ErrorFragment.from(e);case"event":return EventFragment.from(e);case"fallback":case"receive":return FallbackFragment.from(e);case"function":return FunctionFragment.from(e);case"struct":return StructFragment.from(e)}assert(!1,`unsupported type: ${e.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}assertArgument(!1,"unsupported frgament object","obj",e)}static isConstructor(e){return ConstructorFragment.isFragment(e)}static isError(e){return ErrorFragment.isFragment(e)}static isEvent(e){return EventFragment.isFragment(e)}static isFunction(e){return FunctionFragment.isFragment(e)}static isStruct(e){return StructFragment.isFragment(e)}}class NamedFragment extends Fragment{name;constructor(e,t,n,s){super(e,t,s),assertArgument("string"==typeof n&&n.match(regexId),"invalid identifier","name",n),s=Object.freeze(s.slice()),defineProperties(this,{name:n})}}function joinParams(e,t){return"("+t.map(t=>t.format(e)).join("full"===e?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(e,t,n){super(e,"error",t,n),Object.defineProperty(this,internal$1,{value:ErrorFragmentInternal})}get selector(){return id(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("error"),t.push(this.name+joinParams(e,this.inputs)),t.join(" ")}static from(e){if(ErrorFragment.isFragment(e))return e;if("string"==typeof e)return ErrorFragment.from(lex(e));if(e instanceof TokenString){const t=consumeName("error",e),n=consumeParams(e);return consumeEoi(e),new ErrorFragment(_guard,t,n)}return new ErrorFragment(_guard,e.name,e.inputs?e.inputs.map(ParamType.from):[])}static isFragment(e){return e&&e[internal$1]===ErrorFragmentInternal}}class EventFragment extends NamedFragment{anonymous;constructor(e,t,n,s){super(e,"event",t,n),Object.defineProperty(this,internal$1,{value:EventFragmentInternal}),defineProperties(this,{anonymous:s})}get topicHash(){return id(this.format("sighash"))}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("event"),t.push(this.name+joinParams(e,this.inputs)),"sighash"!==e&&this.anonymous&&t.push("anonymous"),t.join(" ")}static getTopicHash(e,t){t=(t||[]).map(e=>ParamType.from(e));return new EventFragment(_guard,e,t,!1).topicHash}static from(e){if(EventFragment.isFragment(e))return e;if("string"==typeof e)try{return EventFragment.from(lex(e))}catch(t){assertArgument(!1,"invalid event fragment","obj",e)}else if(e instanceof TokenString){const t=consumeName("event",e),n=consumeParams(e,!0),s=!!consumeKeywords(e,setify(["anonymous"])).has("anonymous");return consumeEoi(e),new EventFragment(_guard,t,n,s)}return new EventFragment(_guard,e.name,e.inputs?e.inputs.map(e=>ParamType.from(e,!0)):[],!!e.anonymous)}static isFragment(e){return e&&e[internal$1]===EventFragmentInternal}}class ConstructorFragment extends Fragment{payable;gas;constructor(e,t,n,s,r){super(e,t,n),Object.defineProperty(this,internal$1,{value:ConstructorFragmentInternal}),defineProperties(this,{payable:s,gas:r})}format(e){if(assert(null!=e&&"sighash"!==e,"cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"}),"json"===e)return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e)))});const t=[`constructor${joinParams(e,this.inputs)}`];return this.payable&&t.push("payable"),null!=this.gas&&t.push(`@${this.gas.toString()}`),t.join(" ")}static from(e){if(ConstructorFragment.isFragment(e))return e;if("string"==typeof e)try{return ConstructorFragment.from(lex(e))}catch(t){assertArgument(!1,"invalid constuctor fragment","obj",e)}else if(e instanceof TokenString){consumeKeywords(e,setify(["constructor"]));const t=consumeParams(e),n=!!consumeKeywords(e,KwVisibDeploy).has("payable"),s=consumeGas(e);return consumeEoi(e),new ConstructorFragment(_guard,"constructor",t,n,s)}return new ConstructorFragment(_guard,"constructor",e.inputs?e.inputs.map(ParamType.from):[],!!e.payable,null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[internal$1]===ConstructorFragmentInternal}}class FallbackFragment extends Fragment{payable;constructor(e,t,n){super(e,"fallback",t),Object.defineProperty(this,internal$1,{value:FallbackFragmentInternal}),defineProperties(this,{payable:n})}format(e){const t=0===this.inputs.length?"receive":"fallback";if("json"===e){const e=this.payable?"payable":"nonpayable";return JSON.stringify({type:t,stateMutability:e})}return`${t}()${this.payable?" payable":""}`}static from(e){if(FallbackFragment.isFragment(e))return e;if("string"==typeof e)try{return FallbackFragment.from(lex(e))}catch(t){assertArgument(!1,"invalid fallback fragment","obj",e)}else if(e instanceof TokenString){const t=e.toString();assertArgument(e.peekKeyword(setify(["fallback","receive"])),"type must be fallback or receive","obj",t);if("receive"===e.popKeyword(setify(["fallback","receive"]))){const t=consumeParams(e);return assertArgument(0===t.length,"receive cannot have arguments","obj.inputs",t),consumeKeywords(e,setify(["payable"])),consumeEoi(e),new FallbackFragment(_guard,[],!0)}let n=consumeParams(e);n.length?assertArgument(1===n.length&&"bytes"===n[0].type,"invalid fallback inputs","obj.inputs",n.map(e=>e.format("minimal")).join(", ")):n=[ParamType.from("bytes")];const s=consumeMutability(e);if(assertArgument("nonpayable"===s||"payable"===s,"fallback cannot be constants","obj.stateMutability",s),consumeKeywords(e,setify(["returns"])).has("returns")){const t=consumeParams(e);assertArgument(1===t.length&&"bytes"===t[0].type,"invalid fallback outputs","obj.outputs",t.map(e=>e.format("minimal")).join(", "))}return consumeEoi(e),new FallbackFragment(_guard,n,"payable"===s)}if("receive"===e.type)return new FallbackFragment(_guard,[],!0);if("fallback"===e.type){const t=[ParamType.from("bytes")],n="payable"===e.stateMutability;return new FallbackFragment(_guard,t,n)}assertArgument(!1,"invalid fallback description","obj",e)}static isFragment(e){return e&&e[internal$1]===FallbackFragmentInternal}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(e,t,n,s,r,i){super(e,"function",t,s),Object.defineProperty(this,internal$1,{value:FunctionFragmentInternal});defineProperties(this,{constant:"view"===n||"pure"===n,gas:i,outputs:r=Object.freeze(r.slice()),payable:"payable"===n,stateMutability:n})}get selector(){return id(this.format("sighash")).substring(0,10)}format(e){if(null==e&&(e="sighash"),"json"===e)return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:"nonpayable"!==this.stateMutability?this.stateMutability:void 0,payable:this.payable,gas:null!=this.gas?this.gas:void 0,inputs:this.inputs.map(t=>JSON.parse(t.format(e))),outputs:this.outputs.map(t=>JSON.parse(t.format(e)))});const t=[];return"sighash"!==e&&t.push("function"),t.push(this.name+joinParams(e,this.inputs)),"sighash"!==e&&("nonpayable"!==this.stateMutability&&t.push(this.stateMutability),this.outputs&&this.outputs.length&&(t.push("returns"),t.push(joinParams(e,this.outputs))),null!=this.gas&&t.push(`@${this.gas.toString()}`)),t.join(" ")}static getSelector(e,t){t=(t||[]).map(e=>ParamType.from(e));return new FunctionFragment(_guard,e,"view",t,[],null).selector}static from(e){if(FunctionFragment.isFragment(e))return e;if("string"==typeof e)try{return FunctionFragment.from(lex(e))}catch(n){assertArgument(!1,"invalid function fragment","obj",e)}else if(e instanceof TokenString){const t=consumeName("function",e),n=consumeParams(e),s=consumeMutability(e);let r=[];consumeKeywords(e,setify(["returns"])).has("returns")&&(r=consumeParams(e));const i=consumeGas(e);return consumeEoi(e),new FunctionFragment(_guard,t,s,n,r,i)}let t=e.stateMutability;return null==t&&(t="payable","boolean"==typeof e.constant?(t="view",e.constant||(t="payable","boolean"!=typeof e.payable||e.payable||(t="nonpayable"))):"boolean"!=typeof e.payable||e.payable||(t="nonpayable")),new FunctionFragment(_guard,e.name,t,e.inputs?e.inputs.map(ParamType.from):[],e.outputs?e.outputs.map(ParamType.from):[],null!=e.gas?e.gas:null)}static isFragment(e){return e&&e[internal$1]===FunctionFragmentInternal}}class StructFragment extends NamedFragment{constructor(e,t,n){super(e,"struct",t,n),Object.defineProperty(this,internal$1,{value:StructFragmentInternal})}format(){throw new Error("@TODO")}static from(e){if("string"==typeof e)try{return StructFragment.from(lex(e))}catch(t){assertArgument(!1,"invalid struct fragment","obj",e)}else if(e instanceof TokenString){const t=consumeName("struct",e),n=consumeParams(e);return consumeEoi(e),new StructFragment(_guard,t,n)}return new StructFragment(_guard,e.name,e.inputs?e.inputs.map(ParamType.from):[])}static isFragment(e){return e&&e[internal$1]===StructFragmentInternal}}const PanicReasons$1=new Map;PanicReasons$1.set(0,"GENERIC_PANIC"),PanicReasons$1.set(1,"ASSERT_FALSE"),PanicReasons$1.set(17,"OVERFLOW"),PanicReasons$1.set(18,"DIVIDE_BY_ZERO"),PanicReasons$1.set(33,"ENUM_RANGE_ERROR"),PanicReasons$1.set(34,"BAD_STORAGE_DATA"),PanicReasons$1.set(49,"STACK_UNDERFLOW"),PanicReasons$1.set(50,"ARRAY_RANGE_ERROR"),PanicReasons$1.set(65,"OUT_OF_MEMORY"),PanicReasons$1.set(81,"UNINITIALIZED_FUNCTION_CALL");const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/),paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);let defaultCoder=null,defaultMaxInflation=1024;function getBuiltinCallException(e,t,n,s){let r="missing revert data",i=null;let a=null;if(n){r="execution reverted";const e=getBytes(n);if(n=hexlify(n),0===e.length)r+=" (no data present; likely require(false) occurred",i="require(false)";else if(e.length%32!=4)r+=" (could not decode reason; invalid data length)";else if("0x08c379a0"===hexlify(e.slice(0,4)))try{i=s.decode(["string"],e.slice(4))[0],a={signature:"Error(string)",name:"Error",args:[i]},r+=`: ${JSON.stringify(i)}`}catch(l){r+=" (could not decode reason; invalid string data)"}else if("0x4e487b71"===hexlify(e.slice(0,4)))try{const t=Number(s.decode(["uint256"],e.slice(4))[0]);a={signature:"Panic(uint256)",name:"Panic",args:[t]},i=`Panic due to ${PanicReasons$1.get(t)||"UNKNOWN"}(${t})`,r+=`: ${i}`}catch(l){r+=" (could not decode panic code)"}else r+=" (unknown custom error)"}const o={to:t.to?getAddress(t.to):null,data:t.data||"0x"};return t.from&&(o.from=getAddress(t.from)),makeError(r,"CALL_EXCEPTION",{action:e,data:n,reason:i,transaction:o,invocation:null,revert:a})}class AbiCoder{#S(e){if(e.isArray())return new ArrayCoder(this.#S(e.arrayChildren),e.arrayLength,e.name);if(e.isTuple())return new TupleCoder(e.components.map(e=>this.#S(e)),e.name);switch(e.baseType){case"address":return new AddressCoder(e.name);case"bool":return new BooleanCoder(e.name);case"string":return new StringCoder(e.name);case"bytes":return new BytesCoder(e.name);case"":return new NullCoder(e.name)}let t=e.type.match(paramTypeNumber);if(t){let n=parseInt(t[2]||"256");return assertArgument(0!==n&&n<=256&&n%8==0,"invalid "+t[1]+" bit length","param",e),new NumberCoder(n/8,"int"===t[1],e.name)}if(t=e.type.match(paramTypeBytes),t){let n=parseInt(t[1]);return assertArgument(0!==n&&n<=32,"invalid bytes length","param",e),new FixedBytesCoder(n,e.name)}assertArgument(!1,"invalid type","type",e.type)}getDefaultValue(e){const t=e.map(e=>this.#S(ParamType.from(e)));return new TupleCoder(t,"_").defaultValue()}encode(e,t){assertArgumentCount(t.length,e.length,"types/values length mismatch");const n=e.map(e=>this.#S(ParamType.from(e))),s=new TupleCoder(n,"_"),r=new Writer;return s.encode(r,t),r.data}decode(e,t,n){const s=e.map(e=>this.#S(ParamType.from(e)));return new TupleCoder(s,"_").decode(new Reader(t,n,defaultMaxInflation))}static _setDefaultMaxInflation(e){assertArgument("number"==typeof e&&Number.isInteger(e),"invalid defaultMaxInflation factor","value",e),defaultMaxInflation=e}static defaultAbiCoder(){return null==defaultCoder&&(defaultCoder=new AbiCoder),defaultCoder}static getBuiltinCallException(e,t,n){return getBuiltinCallException(e,t,n,AbiCoder.defaultAbiCoder())}}class LogDescription{fragment;name;signature;topic;args;constructor(e,t,n){const s=e.name,r=e.format();defineProperties(this,{fragment:e,name:s,signature:r,topic:t,args:n})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(e,t,n,s){const r=e.name,i=e.format();defineProperties(this,{fragment:e,name:r,args:n,signature:i,selector:t,value:s})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(e,t,n){const s=e.name,r=e.format();defineProperties(this,{fragment:e,name:s,args:n,signature:r,selector:t})}}class Indexed{hash;_isIndexed;static isIndexed(e){return!(!e||!e._isIndexed)}constructor(e){defineProperties(this,{hash:e,_isIndexed:!0})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"},BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:e=>`reverted with reason string ${JSON.stringify(e)}`},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:e=>{let t="unknown panic code";return e>=0&&e<=255&&PanicReasons[e.toString()]&&(t=PanicReasons[e.toString()]),`reverted with panic code 0x${e.toString(16)} (${t})`}}};class Interface{fragments;deploy;fallback;receive;#k;#T;#C;#x;constructor(e){let t=[];t="string"==typeof e?JSON.parse(e):e,this.#C=new Map,this.#k=new Map,this.#T=new Map;const n=[];for(const a of t)try{n.push(Fragment.from(a))}catch(i){console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`,i.message)}defineProperties(this,{fragments:Object.freeze(n)});let s=null,r=!1;this.#x=this.getAbiCoder(),this.fragments.forEach((e,t)=>{let n;switch(e.type){case"constructor":return this.deploy?void console.log("duplicate definition - constructor"):void defineProperties(this,{deploy:e});case"fallback":return void(0===e.inputs.length?r=!0:(assertArgument(!s||e.payable!==s.payable,"conflicting fallback fragments",`fragments[${t}]`,e),s=e,r=s.payable));case"function":n=this.#C;break;case"event":n=this.#T;break;case"error":n=this.#k;break;default:return}const i=e.format();n.has(i)||n.set(i,e)}),this.deploy||defineProperties(this,{deploy:ConstructorFragment.from("constructor()")}),defineProperties(this,{fallback:s,receive:r})}format(e){const t=e?"minimal":"full";return this.fragments.map(e=>e.format(t))}formatJson(){const e=this.fragments.map(e=>e.format("json"));return JSON.stringify(e.map(e=>JSON.parse(e)))}getAbiCoder(){return AbiCoder.defaultAbiCoder()}#R(e,t,n){if(isHexString(e)){const t=e.toLowerCase();for(const e of this.#C.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const s=[];for(const[t,n]of this.#C)t.split("(")[0]===e&&s.push(n);if(t){const e=t.length>0?t[t.length-1]:null;let n=t.length,r=!0;Typed.isTyped(e)&&"overrides"===e.type&&(r=!1,n--);for(let t=s.length-1;t>=0;t--){const e=s[t].inputs.length;e===n||r&&e===n-1||s.splice(t,1)}for(let i=s.length-1;i>=0;i--){const e=s[i].inputs;for(let n=0;n<t.length;n++)if(Typed.isTyped(t[n])){if(n>=e.length){if("overrides"===t[n].type)continue;s.splice(i,1);break}if(t[n].type!==e[n].baseType){s.splice(i,1);break}}}}if(1===s.length&&t&&t.length!==s[0].inputs.length){const e=t[t.length-1];(null==e||Array.isArray(e)||"object"!=typeof e)&&s.splice(0,1)}if(0===s.length)return null;if(s.length>1&&n){assertArgument(!1,`ambiguous function description (i.e. matches ${s.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return s[0]}const s=this.#C.get(FunctionFragment.from(e).format());return s||null}getFunctionName(e){const t=this.#R(e,null,!1);return assertArgument(t,"no matching function","key",e),t.name}hasFunction(e){return!!this.#R(e,null,!1)}getFunction(e,t){return this.#R(e,t||null,!0)}forEachFunction(e){const t=Array.from(this.#C.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#C.get(s),n)}}#I(e,t,n){if(isHexString(e)){const t=e.toLowerCase();for(const e of this.#T.values())if(t===e.topicHash)return e;return null}if(-1===e.indexOf("(")){const s=[];for(const[t,n]of this.#T)t.split("(")[0]===e&&s.push(n);if(t){for(let e=s.length-1;e>=0;e--)s[e].inputs.length<t.length&&s.splice(e,1);for(let e=s.length-1;e>=0;e--){const n=s[e].inputs;for(let r=0;r<t.length;r++)if(Typed.isTyped(t[r])&&t[r].type!==n[r].baseType){s.splice(e,1);break}}}if(0===s.length)return null;if(s.length>1&&n){assertArgument(!1,`ambiguous event description (i.e. matches ${s.map(e=>JSON.stringify(e.format())).join(", ")})`,"key",e)}return s[0]}const s=this.#T.get(EventFragment.from(e).format());return s||null}getEventName(e){const t=this.#I(e,null,!1);return assertArgument(t,"no matching event","key",e),t.name}hasEvent(e){return!!this.#I(e,null,!1)}getEvent(e,t){return this.#I(e,t||null,!0)}forEachEvent(e){const t=Array.from(this.#T.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#T.get(s),n)}}getError(e,t){if(isHexString(e)){const t=e.toLowerCase();if(BuiltinErrors[t])return ErrorFragment.from(BuiltinErrors[t].signature);for(const e of this.#k.values())if(t===e.selector)return e;return null}if(-1===e.indexOf("(")){const t=[];for(const[n,s]of this.#k)n.split("(")[0]===e&&t.push(s);if(0===t.length)return"Error"===e?ErrorFragment.from("error Error(string)"):"Panic"===e?ErrorFragment.from("error Panic(uint256)"):null;if(t.length>1){assertArgument(!1,`ambiguous error description (i.e. ${t.map(e=>JSON.stringify(e.format())).join(", ")})`,"name",e)}return t[0]}if("Error(string)"===(e=ErrorFragment.from(e).format()))return ErrorFragment.from("error Error(string)");if("Panic(uint256)"===e)return ErrorFragment.from("error Panic(uint256)");const n=this.#k.get(e);return n||null}forEachError(e){const t=Array.from(this.#k.keys());t.sort((e,t)=>e.localeCompare(t));for(let n=0;n<t.length;n++){const s=t[n];e(this.#k.get(s),n)}}_decodeParams(e,t){return this.#x.decode(e,t)}_encodeParams(e,t){return this.#x.encode(e,t)}encodeDeploy(e){return this._encodeParams(this.deploy.inputs,e||[])}decodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);assertArgument(t,"unknown error","fragment",e),e=t}return assertArgument(dataSlice(t,0,4)===e.selector,`data signature does not match error ${e.name}.`,"data",t),this._decodeParams(e.inputs,dataSlice(t,4))}encodeErrorResult(e,t){if("string"==typeof e){const t=this.getError(e);assertArgument(t,"unknown error","fragment",e),e=t}return concat([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);assertArgument(t,"unknown function","fragment",e),e=t}return assertArgument(dataSlice(t,0,4)===e.selector,`data signature does not match function ${e.name}.`,"data",t),this._decodeParams(e.inputs,dataSlice(t,4))}encodeFunctionData(e,t){if("string"==typeof e){const t=this.getFunction(e);assertArgument(t,"unknown function","fragment",e),e=t}return concat([e.selector,this._encodeParams(e.inputs,t||[])])}decodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);assertArgument(t,"unknown function","fragment",e),e=t}let n="invalid length for result data";const s=getBytesCopy(t);if(s.length%32==0)try{return this.#x.decode(e.outputs,s)}catch(r){n="could not decode result data"}assert(!1,n,"BAD_DATA",{value:hexlify(s),info:{method:e.name,signature:e.format()}})}makeError(e,t){const n=getBytes(e,"data"),s=AbiCoder.getBuiltinCallException("call",t,n);if(s.message.startsWith("execution reverted (unknown custom error)")){const e=hexlify(n.slice(0,4)),t=this.getError(e);if(t)try{const e=this.#x.decode(t.inputs,n.slice(4));s.revert={name:t.name,signature:t.format(),args:e},s.reason=s.revert.signature,s.message=`execution reverted: ${s.reason}`}catch(i){s.message="execution reverted (coult not decode custom error)"}}const r=this.parseTransaction(t);return r&&(s.invocation={method:r.name,signature:r.signature,args:r.args}),s}encodeFunctionResult(e,t){if("string"==typeof e){const t=this.getFunction(e);assertArgument(t,"unknown function","fragment",e),e=t}return hexlify(this.#x.encode(e.outputs,t||[]))}encodeFilterTopics(e,t){if("string"==typeof e){const t=this.getEvent(e);assertArgument(t,"unknown event","eventFragment",e),e=t}assert(t.length<=e.inputs.length,`too many arguments for ${e.format()}`,"UNEXPECTED_ARGUMENT",{count:t.length,expectedCount:e.inputs.length});const n=[];e.anonymous||n.push(e.topicHash);const s=(e,t)=>"string"===e.type?id(t):"bytes"===e.type?keccak256(hexlify(t)):("bool"===e.type&&"boolean"==typeof t?t=t?"0x01":"0x00":e.type.match(/^u?int/)?t=toBeHex(t):e.type.match(/^bytes/)?t=zeroPadBytes(t,32):"address"===e.type&&this.#x.encode(["address"],[t]),zeroPadValue(hexlify(t),32));for(t.forEach((t,r)=>{const i=e.inputs[r];i.indexed?null==t?n.push(null):"array"===i.baseType||"tuple"===i.baseType?assertArgument(!1,"filtering with tuples or arrays not supported","contract."+i.name,t):Array.isArray(t)?n.push(t.map(e=>s(i,e))):n.push(s(i,t)):assertArgument(null==t,"cannot filter non-indexed parameters; must be null","contract."+i.name,t)});n.length&&null===n[n.length-1];)n.pop();return n}encodeEventLog(e,t){if("string"==typeof e){const t=this.getEvent(e);assertArgument(t,"unknown event","eventFragment",e),e=t}const n=[],s=[],r=[];return e.anonymous||n.push(e.topicHash),assertArgument(t.length===e.inputs.length,"event arguments/values mismatch","values",t),e.inputs.forEach((e,i)=>{const a=t[i];if(e.indexed)if("string"===e.type)n.push(id(a));else if("bytes"===e.type)n.push(keccak256(a));else{if("tuple"===e.baseType||"array"===e.baseType)throw new Error("not implemented");n.push(this.#x.encode([e.type],[a]))}else s.push(e),r.push(a)}),{data:this.#x.encode(s,r),topics:n}}decodeEventLog(e,t,n){if("string"==typeof e){const t=this.getEvent(e);assertArgument(t,"unknown event","eventFragment",e),e=t}if(null!=n&&!e.anonymous){const t=e.topicHash;assertArgument(isHexString(n[0],32)&&n[0].toLowerCase()===t,"fragment/topic mismatch","topics[0]",n[0]),n=n.slice(1)}const s=[],r=[],i=[];e.inputs.forEach((e,t)=>{e.indexed?"string"===e.type||"bytes"===e.type||"tuple"===e.baseType||"array"===e.baseType?(s.push(ParamType.from({type:"bytes32",name:e.name})),i.push(!0)):(s.push(e),i.push(!1)):(r.push(e),i.push(!1))});const a=null!=n?this.#x.decode(s,concat(n)):null,o=this.#x.decode(r,t,!0),l=[],c=[];let u=0,d=0;return e.inputs.forEach((e,t)=>{let n=null;if(e.indexed)if(null==a)n=new Indexed(null);else if(i[t])n=new Indexed(a[d++]);else try{n=a[d++]}catch(s){n=s}else try{n=o[u++]}catch(s){n=s}l.push(n),c.push(e.name||null)}),Result.fromItems(l,c)}parseTransaction(e){const t=getBytes(e.data,"tx.data"),n=getBigInt(null!=e.value?e.value:0,"tx.value"),s=this.getFunction(hexlify(t.slice(0,4)));if(!s)return null;const r=this.#x.decode(s.inputs,t.slice(4));return new TransactionDescription(s,s.selector,r,n)}parseCallResult(e){throw new Error("@TODO")}parseLog(e){const t=this.getEvent(e.topics[0]);return!t||t.anonymous?null:new LogDescription(t,t.topicHash,this.decodeEventLog(t,e.data,e.topics))}parseError(e){const t=hexlify(e),n=this.getError(dataSlice(t,0,4));if(!n)return null;const s=this.#x.decode(n.inputs,dataSlice(t,4));return new ErrorDescription(n,n.selector,s)}static from(e){return e instanceof Interface?e:"string"==typeof e?new Interface(JSON.parse(e)):"function"==typeof e.formatJson?new Interface(e.formatJson()):"function"==typeof e.format?new Interface(e.format("json")):new Interface(e)}}const BN_0$1=BigInt(0);function getValue(e){return null==e?null:e}function toJson(e){return null==e?null:e.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(e,t,n){defineProperties(this,{gasPrice:getValue(e),maxFeePerGas:getValue(t),maxPriorityFeePerGas:getValue(n)})}toJSON(){const{gasPrice:e,maxFeePerGas:t,maxPriorityFeePerGas:n}=this;return{_type:"FeeData",gasPrice:toJson(e),maxFeePerGas:toJson(t),maxPriorityFeePerGas:toJson(n)}}}function copyRequest(e){const t={};e.to&&(t.to=e.to),e.from&&(t.from=e.from),e.data&&(t.data=hexlify(e.data));const n="chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const r of n)r in e&&null!=e[r]&&(t[r]=getBigInt(e[r],`request.${r}`));const s="type,nonce".split(/,/);for(const r of s)r in e&&null!=e[r]&&(t[r]=getNumber(e[r],`request.${r}`));return e.accessList&&(t.accessList=accessListify(e.accessList)),e.authorizationList&&(t.authorizationList=e.authorizationList.slice()),"blockTag"in e&&(t.blockTag=e.blockTag),"enableCcipRead"in e&&(t.enableCcipRead=!!e.enableCcipRead),"customData"in e&&(t.customData=e.customData),"blobVersionedHashes"in e&&e.blobVersionedHashes&&(t.blobVersionedHashes=e.blobVersionedHashes.slice()),"kzg"in e&&(t.kzg=e.kzg),"blobWrapperVersion"in e&&(t.blobWrapperVersion=e.blobWrapperVersion),"blobs"in e&&e.blobs&&(t.blobs=e.blobs.map(e=>isBytesLike(e)?hexlify(e):Object.assign({},e))),t}class Block{provider;number;hash;timestamp;parentHash;parentBeaconBlockRoot;nonce;difficulty;gasLimit;gasUsed;stateRoot;receiptsRoot;blobGasUsed;excessBlobGas;miner;prevRandao;extraData;baseFeePerGas;#$;constructor(e,t){this.#$=e.transactions.map(e=>"string"!=typeof e?new TransactionResponse(e,t):e),defineProperties(this,{provider:t,hash:getValue(e.hash),number:e.number,timestamp:e.timestamp,parentHash:e.parentHash,parentBeaconBlockRoot:e.parentBeaconBlockRoot,nonce:e.nonce,difficulty:e.difficulty,gasLimit:e.gasLimit,gasUsed:e.gasUsed,blobGasUsed:e.blobGasUsed,excessBlobGas:e.excessBlobGas,miner:e.miner,prevRandao:getValue(e.prevRandao),extraData:e.extraData,baseFeePerGas:getValue(e.baseFeePerGas),stateRoot:e.stateRoot,receiptsRoot:e.receiptsRoot})}get transactions(){return this.#$.map(e=>"string"==typeof e?e:e.hash)}get prefetchedTransactions(){const e=this.#$.slice();return 0===e.length?[]:(assert("object"==typeof e[0],"transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"}),e)}toJSON(){const{baseFeePerGas:e,difficulty:t,extraData:n,gasLimit:s,gasUsed:r,hash:i,miner:a,prevRandao:o,nonce:l,number:c,parentHash:u,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:h,timestamp:p,transactions:y}=this;return{_type:"Block",baseFeePerGas:toJson(e),difficulty:toJson(t),extraData:n,gasLimit:toJson(s),gasUsed:toJson(r),blobGasUsed:toJson(this.blobGasUsed),excessBlobGas:toJson(this.excessBlobGas),hash:i,miner:a,prevRandao:o,nonce:l,number:c,parentHash:u,timestamp:p,parentBeaconBlockRoot:d,stateRoot:f,receiptsRoot:h,transactions:y}}[Symbol.iterator](){let e=0;const t=this.transactions;return{next:()=>e<this.length?{value:t[e++],done:!1}:{value:void 0,done:!0}}}get length(){return this.#$.length}get date(){return null==this.timestamp?null:new Date(1e3*this.timestamp)}async getTransaction(e){let t;if("number"==typeof e)t=this.#$[e];else{const n=e.toLowerCase();for(const e of this.#$){if("string"==typeof e){if(e!==n)continue;t=e;break}if(e.hash===n){t=e;break}}}if(null==t)throw new Error("no such tx");return"string"==typeof t?await this.provider.getTransaction(t):t}getPrefetchedTransaction(e){const t=this.prefetchedTransactions;if("number"==typeof e)return t[e];e=e.toLowerCase();for(const n of t)if(n.hash===e)return n;assertArgument(!1,"no matching transaction","indexOrHash",e)}isMined(){return!!this.hash}isLondon(){return!!this.baseFeePerGas}orphanedEvent(){if(!this.isMined())throw new Error("");return createOrphanedBlockFilter(this)}}class Log{provider;transactionHash;blockHash;blockNumber;removed;address;data;topics;index;transactionIndex;constructor(e,t){this.provider=t;const n=Object.freeze(e.topics.slice());defineProperties(this,{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,removed:e.removed,address:e.address,data:e.data,topics:n,index:e.index,transactionIndex:e.transactionIndex})}toJSON(){const{address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:i,topics:a,transactionHash:o,transactionIndex:l}=this;return{_type:"log",address:e,blockHash:t,blockNumber:n,data:s,index:r,removed:i,topics:a,transactionHash:o,transactionIndex:l}}async getBlock(){const e=await this.provider.getBlock(this.blockHash);return assert(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransaction(){const e=await this.provider.getTransaction(this.transactionHash);return assert(!!e,"failed to find transaction","UNKNOWN_ERROR",{}),e}async getTransactionReceipt(){const e=await this.provider.getTransactionReceipt(this.transactionHash);return assert(!!e,"failed to find transaction receipt","UNKNOWN_ERROR",{}),e}removedEvent(){return createRemovedLogFilter(this)}}class TransactionReceipt{provider;to;from;contractAddress;hash;index;blockHash;blockNumber;logsBloom;gasUsed;blobGasUsed;cumulativeGasUsed;gasPrice;blobGasPrice;type;status;root;#P;constructor(e,t){this.#P=Object.freeze(e.logs.map(e=>new Log(e,t)));let n=BN_0$1;null!=e.effectiveGasPrice?n=e.effectiveGasPrice:null!=e.gasPrice&&(n=e.gasPrice),defineProperties(this,{provider:t,to:e.to,from:e.from,contractAddress:e.contractAddress,hash:e.hash,index:e.index,blockHash:e.blockHash,blockNumber:e.blockNumber,logsBloom:e.logsBloom,gasUsed:e.gasUsed,cumulativeGasUsed:e.cumulativeGasUsed,blobGasUsed:e.blobGasUsed,gasPrice:n,blobGasPrice:e.blobGasPrice,type:e.type,status:e.status,root:e.root})}get logs(){return this.#P}toJSON(){const{to:e,from:t,contractAddress:n,hash:s,index:r,blockHash:i,blockNumber:a,logsBloom:o,logs:l,status:c,root:u}=this;return{_type:"TransactionReceipt",blockHash:i,blockNumber:a,contractAddress:n,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:t,gasPrice:toJson(this.gasPrice),blobGasUsed:toJson(this.blobGasUsed),blobGasPrice:toJson(this.blobGasPrice),gasUsed:toJson(this.gasUsed),hash:s,index:r,logs:l,logsBloom:o,root:u,status:c,to:e}}get length(){return this.logs.length}[Symbol.iterator](){let e=0;return{next:()=>e<this.length?{value:this.logs[e++],done:!1}:{value:void 0,done:!0}}}get fee(){return this.gasUsed*this.gasPrice}async getBlock(){const e=await this.provider.getBlock(this.blockHash);if(null==e)throw new Error("TODO");return e}async getTransaction(){const e=await this.provider.getTransaction(this.hash);if(null==e)throw new Error("TODO");return e}async getResult(){return await this.provider.getTransactionResult(this.hash)}async confirmations(){return await this.provider.getBlockNumber()-this.blockNumber+1}removedEvent(){return createRemovedTransactionFilter(this)}reorderedEvent(e){return assert(!e||e.isMined(),"unmined 'other' transction cannot be orphaned","UNSUPPORTED_OPERATION",{operation:"reorderedEvent(other)"}),createReorderedTransactionFilter(this,e)}}class TransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;gasPrice;maxPriorityFeePerGas;maxFeePerGas;maxFeePerBlobGas;data;value;chainId;signature;accessList;blobVersionedHashes;authorizationList;#N;constructor(e,t){this.provider=t,this.blockNumber=null!=e.blockNumber?e.blockNumber:null,this.blockHash=null!=e.blockHash?e.blockHash:null,this.hash=e.hash,this.index=e.index,this.type=e.type,this.from=e.from,this.to=e.to||null,this.gasLimit=e.gasLimit,this.nonce=e.nonce,this.data=e.data,this.value=e.value,this.gasPrice=e.gasPrice,this.maxPriorityFeePerGas=null!=e.maxPriorityFeePerGas?e.maxPriorityFeePerGas:null,this.maxFeePerGas=null!=e.maxFeePerGas?e.maxFeePerGas:null,this.maxFeePerBlobGas=null!=e.maxFeePerBlobGas?e.maxFeePerBlobGas:null,this.chainId=e.chainId,this.signature=e.signature,this.accessList=null!=e.accessList?e.accessList:null,this.blobVersionedHashes=null!=e.blobVersionedHashes?e.blobVersionedHashes:null,this.authorizationList=null!=e.authorizationList?e.authorizationList:null,this.#N=-1}toJSON(){const{blockNumber:e,blockHash:t,index:n,hash:s,type:r,to:i,from:a,nonce:o,data:l,signature:c,accessList:u,blobVersionedHashes:d}=this;return{_type:"TransactionResponse",accessList:u,blockNumber:e,blockHash:t,blobVersionedHashes:d,chainId:toJson(this.chainId),data:l,from:a,gasLimit:toJson(this.gasLimit),gasPrice:toJson(this.gasPrice),hash:s,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),maxFeePerBlobGas:toJson(this.maxFeePerBlobGas),nonce:o,signature:c,to:i,index:n,type:r,value:toJson(this.value)}}async getBlock(){let e=this.blockNumber;if(null==e){const t=await this.getTransaction();t&&(e=t.blockNumber)}if(null==e)return null;const t=this.provider.getBlock(e);if(null==t)throw new Error("TODO");return t}async getTransaction(){return this.provider.getTransaction(this.hash)}async confirmations(){if(null==this.blockNumber){const{tx:e,blockNumber:t}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber()});return null==e||null==e.blockNumber?0:t-e.blockNumber+1}return await this.provider.getBlockNumber()-this.blockNumber+1}async wait(e,t){const n=null==e?1:e,s=null==t?0:t;let r=this.#N,i=-1,a=-1===r;const o=async()=>{if(a)return null;const{blockNumber:e,nonce:t}=await resolveProperties({blockNumber:this.provider.getBlockNumber(),nonce:this.provider.getTransactionCount(this.from)});if(t<this.nonce)return void(r=e);if(a)return null;const s=await this.getTransaction();if(!s||null==s.blockNumber)for(-1===i&&(i=r-3,i<this.#N&&(i=this.#N));i<=e;){if(a)return null;const t=await this.provider.getBlock(i,!0);if(null==t)return;for(const e of t)if(e===this.hash)return;for(let s=0;s<t.length;s++){const i=await t.getTransaction(s);if(i.from===this.from&&i.nonce===this.nonce){if(a)return null;const t=await this.provider.getTransactionReceipt(i.hash);if(null==t)return;if(e-t.blockNumber+1<n)return;let s="replaced";i.data===this.data&&i.to===this.to&&i.value===this.value?s="repriced":"0x"===i.data&&i.from===i.to&&i.value===BN_0$1&&(s="cancelled"),assert(!1,"transaction was replaced","TRANSACTION_REPLACED",{cancelled:"replaced"===s||"cancelled"===s,reason:s,replacement:i.replaceableTransaction(r),hash:i.hash,receipt:t})}}i++}},l=e=>{if(null==e||0!==e.status)return e;assert(!1,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:e.to,from:e.from,data:""},receipt:e})},c=await this.provider.getTransactionReceipt(this.hash);if(0===n)return l(c);if(c){if(1===n||await c.confirmations()>=n)return l(c)}else if(await o(),0===n)return null;const u=new Promise((e,t)=>{const i=[],c=()=>{i.forEach(e=>e())};if(i.push(()=>{a=!0}),s>0){const e=setTimeout(()=>{c(),t(makeError("wait for transaction timeout","TIMEOUT"))},s);i.push(()=>{clearTimeout(e)})}const u=async s=>{if(await s.confirmations()>=n){c();try{e(l(s))}catch(r){t(r)}}};if(i.push(()=>{this.provider.off(this.hash,u)}),this.provider.on(this.hash,u),r>=0){const e=async()=>{try{await o()}catch(n){if(isError(n,"TRANSACTION_REPLACED"))return c(),void t(n)}a||this.provider.once("block",e)};i.push(()=>{this.provider.off("block",e)}),this.provider.once("block",e)}});return await u}isMined(){return null!=this.blockHash}isLegacy(){return 0===this.type}isBerlin(){return 1===this.type}isLondon(){return 2===this.type}isCancun(){return 3===this.type}removedEvent(){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createRemovedTransactionFilter(this)}reorderedEvent(e){return assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),assert(!e||e.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"}),createReorderedTransactionFilter(this,e)}replaceableTransaction(e){assertArgument(Number.isInteger(e)&&e>=0,"invalid startBlock","startBlock",e);const t=new TransactionResponse(this,this.provider);return t.#N=e,t}}function createOrphanedBlockFilter(e){return{orphan:"drop-block",hash:e.hash,number:e.number}}function createReorderedTransactionFilter(e,t){return{orphan:"reorder-transaction",tx:e,other:t}}function createRemovedTransactionFilter(e){return{orphan:"drop-transaction",tx:e}}function createRemovedLogFilter(e){return{orphan:"drop-log",log:{transactionHash:e.transactionHash,blockHash:e.blockHash,blockNumber:e.blockNumber,address:e.address,data:e.data,topics:Object.freeze(e.topics.slice()),index:e.index}}}class EventLog extends Log{interface;fragment;args;constructor(e,t,n){super(e,e.provider);defineProperties(this,{args:t.decodeEventLog(n,e.data,e.topics),fragment:n,interface:t})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class UndecodedEventLog extends Log{error;constructor(e,t){super(e,e.provider),defineProperties(this,{error:t})}}class ContractTransactionReceipt extends TransactionReceipt{#F;constructor(e,t,n){super(n,t),this.#F=e}get logs(){return super.logs.map(e=>{const t=e.topics.length?this.#F.getEvent(e.topics[0]):null;if(t)try{return new EventLog(e,this.#F,t)}catch(n){return new UndecodedEventLog(e,n)}return e})}}class ContractTransactionResponse extends TransactionResponse{#F;constructor(e,t,n){super(n,t),this.#F=e}async wait(e,t){const n=await super.wait(e,t);return null==n?null:new ContractTransactionReceipt(this.#F,this.provider,n)}}class ContractUnknownEventPayload extends EventPayload{log;constructor(e,t,n,s){super(e,t,n),defineProperties(this,{log:s})}async getBlock(){return await this.log.getBlock()}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ContractEventPayload extends ContractUnknownEventPayload{constructor(e,t,n,s,r){super(e,t,n,new EventLog(r,e.interface,s));defineProperties(this,{args:e.interface.decodeEventLog(s,this.log.data,this.log.topics),fragment:s})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const BN_0=BigInt(0);function canCall(e){return e&&"function"==typeof e.call}function canEstimate(e){return e&&"function"==typeof e.estimateGas}function canResolve(e){return e&&"function"==typeof e.resolveName}function canSend(e){return e&&"function"==typeof e.sendTransaction}function getResolver(e){if(null!=e){if(canResolve(e))return e;if(e.provider)return e.provider}}class PreparedTopicFilter{#O;fragment;constructor(e,t,n){if(defineProperties(this,{fragment:t}),t.inputs.length<n.length)throw new Error("too many arguments");const s=getRunner(e.runner,"resolveName"),r=canResolve(s)?s:null;this.#O=async function(){const s=await Promise.all(t.inputs.map((e,t)=>null==n[t]?null:e.walkAsync(n[t],(e,t)=>"address"===e?Array.isArray(t)?Promise.all(t.map(e=>resolveAddress(e,r))):resolveAddress(t,r):t)));return e.interface.encodeFilterTopics(t,s)}()}getTopicFilter(){return this.#O}}function getRunner(e,t){return null==e?null:"function"==typeof e[t]?e:e.provider&&"function"==typeof e.provider[t]?e.provider:null}function getProvider(e){return null==e?null:e.provider||null}async function copyOverrides(e,t){const n=Typed.dereference(e,"overrides");assertArgument("object"==typeof n,"invalid overrides parameter","overrides",e);const s=copyRequest(n);return assertArgument(null==s.to||(t||[]).indexOf("to")>=0,"cannot override to","overrides.to",s.to),assertArgument(null==s.data||(t||[]).indexOf("data")>=0,"cannot override data","overrides.data",s.data),s.from&&(s.from=s.from),s}async function resolveArgs(e,t,n){const s=getRunner(e,"resolveName"),r=canResolve(s)?s:null;return await Promise.all(t.map((e,t)=>e.walkAsync(n[t],(e,t)=>(t=Typed.dereference(t,e),"address"===e?resolveAddress(t,r):t))))}function buildWrappedFallback(e){const t=async function(t){const n=await copyOverrides(t,["data"]);n.to=await e.getAddress(),n.from&&(n.from=await resolveAddress(n.from,getResolver(e.runner)));const s=e.interface,r=getBigInt(n.value||BN_0,"overrides.value")===BN_0,i="0x"===(n.data||"0x");!s.fallback||s.fallback.payable||!s.receive||i||r||assertArgument(!1,"cannot send data to receive or send value to non-payable fallback","overrides",t),assertArgument(s.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data);return assertArgument(s.receive||s.fallback&&s.fallback.payable||r,"cannot send value to non-payable fallback","overrides.value",n.value),assertArgument(s.fallback||i,"cannot send data to receive-only contract","overrides.data",n.data),n},n=async function(n){const s=e.runner;assert(canSend(s),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await s.sendTransaction(await t(n)),i=getProvider(e.runner);return new ContractTransactionResponse(e.interface,i,r)},s=async e=>await n(e);return defineProperties(s,{_contract:e,estimateGas:async function(n){const s=getRunner(e.runner,"estimateGas");return assert(canEstimate(s),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await s.estimateGas(await t(n))},populateTransaction:t,send:n,staticCall:async function(n){const s=getRunner(e.runner,"call");assert(canCall(s),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const r=await t(n);try{return await s.call(r)}catch(i){if(isCallException(i)&&i.data)throw e.interface.makeError(i.data,r);throw i}}}),s}function buildWrappedMethod(e,t){const n=function(...n){const s=e.interface.getFunction(t,n);return assert(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),s},s=async function(...t){const s=n(...t);let r={};if(s.inputs.length+1===t.length&&(r=await copyOverrides(t.pop()),r.from&&(r.from=await resolveAddress(r.from,getResolver(e.runner)))),s.inputs.length!==t.length)throw new Error("internal error: fragment inputs doesn't match arguments; should not happen");const i=await resolveArgs(e.runner,s.inputs,t);return Object.assign({},r,await resolveProperties({to:e.getAddress(),data:e.interface.encodeFunctionData(s,i)}))},r=async function(...e){const t=await a(...e);return 1===t.length?t[0]:t},i=async function(...t){const n=e.runner;assert(canSend(n),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const r=await n.sendTransaction(await s(...t)),i=getProvider(e.runner);return new ContractTransactionResponse(e.interface,i,r)},a=async function(...t){const r=getRunner(e.runner,"call");assert(canCall(r),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const i=await s(...t);let a="0x";try{a=await r.call(i)}catch(l){if(isCallException(l)&&l.data)throw e.interface.makeError(l.data,i);throw l}const o=n(...t);return e.interface.decodeFunctionResult(o,a)},o=async(...e)=>n(...e).constant?await r(...e):await i(...e);return defineProperties(o,{name:e.interface.getFunctionName(t),_contract:e,_key:t,getFragment:n,estimateGas:async function(...t){const n=getRunner(e.runner,"estimateGas");return assert(canEstimate(n),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"}),await n.estimateGas(await s(...t))},populateTransaction:s,send:i,staticCall:r,staticCallResult:a}),Object.defineProperty(o,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getFunction(t);return assert(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),o}function buildWrappedEvent(e,t){const n=function(...n){const s=e.interface.getEvent(t,n);return assert(s,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t,args:n}}),s},s=function(...t){return new PreparedTopicFilter(e,n(...t),t)};return defineProperties(s,{name:e.interface.getEventName(t),_contract:e,_key:t,getFragment:n}),Object.defineProperty(s,"fragment",{configurable:!1,enumerable:!0,get:()=>{const n=e.interface.getEvent(t);return assert(n,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:t}}),n}}),s}const internal=Symbol.for("_ethersInternal_contract"),internalValues=new WeakMap;function setInternal(e,t){internalValues.set(e[internal],t)}function getInternal(e){return internalValues.get(e[internal])}function isDeferred(e){return e&&"object"==typeof e&&"getTopicFilter"in e&&"function"==typeof e.getTopicFilter&&e.fragment}async function getSubInfo(e,t){let n,s=null;if(Array.isArray(t)){const s=function(t){if(isHexString(t,32))return t;const n=e.interface.getEvent(t);return assertArgument(n,"unknown fragment","name",t),n.topicHash};n=t.map(e=>null==e?null:Array.isArray(e)?e.map(s):s(e))}else"*"===t?n=[null]:"string"==typeof t?isHexString(t,32)?n=[t]:(s=e.interface.getEvent(t),assertArgument(s,"unknown fragment","event",t),n=[s.topicHash]):isDeferred(t)?n=await t.getTopicFilter():"fragment"in t?(s=t.fragment,n=[s.topicHash]):assertArgument(!1,"unknown event name","event",t);n=n.map(e=>{if(null==e)return null;if(Array.isArray(e)){const t=Array.from(new Set(e.map(e=>e.toLowerCase())).values());return 1===t.length?t[0]:(t.sort(),t)}return e.toLowerCase()});return{fragment:s,tag:n.map(e=>null==e?"null":Array.isArray(e)?e.join("|"):e).join("&"),topics:n}}async function hasSub(e,t){const{subs:n}=getInternal(e);return n.get((await getSubInfo(e,t)).tag)||null}async function getSub(e,t,n){const s=getProvider(e.runner);assert(s,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:t});const{fragment:r,tag:i,topics:a}=await getSubInfo(e,n),{addr:o,subs:l}=getInternal(e);let c=l.get(i);if(!c){const t={address:o||e,topics:a},u=t=>{let s=r;if(null==s)try{s=e.interface.getEvent(t.topics[0])}catch(i){}if(s){const i=s,a=r?e.interface.decodeEventLog(r,t.data,t.topics):[];emit(e,n,a,s=>new ContractEventPayload(e,s,n,i,t))}else emit(e,n,[],s=>new ContractUnknownEventPayload(e,s,n,t))};let d=[];c={tag:i,listeners:[],start:()=>{d.length||d.push(s.on(t,u))},stop:async()=>{if(0==d.length)return;let e=d;d=[],await Promise.all(e),s.off(t,u)}},l.set(i,c)}return c}let lastEmit=Promise.resolve();async function _emit(e,t,n,s){await lastEmit;const r=await hasSub(e,t);if(!r)return!1;const i=r.listeners.length;return r.listeners=r.listeners.filter(({listener:t,once:r})=>{const i=Array.from(n);s&&i.push(s(r?null:t));try{t.call(e,...i)}catch(a){}return!r}),0===r.listeners.length&&(r.stop(),getInternal(e).subs.delete(r.tag)),i>0}async function emit(e,t,n,s){try{await lastEmit}catch(i){}const r=_emit(e,t,n,s);return lastEmit=r,await r}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];fallback;constructor(e,t,n,s){assertArgument("string"==typeof e||isAddressable(e),"invalid value for Contract target","target",e),null==n&&(n=null);const r=Interface.from(t);let i;defineProperties(this,{target:e,runner:n,interface:r}),Object.defineProperty(this,internal,{value:{}});let a=null,o=null;if(s){const e=getProvider(n);o=new ContractTransactionResponse(this.interface,e,s)}let l=new Map;if("string"==typeof e)if(isHexString(e))a=e,i=Promise.resolve(e);else{const t=getRunner(n,"resolveName");if(!canResolve(t))throw makeError("contract runner does not support name resolution","UNSUPPORTED_OPERATION",{operation:"resolveName"});i=t.resolveName(e).then(t=>{if(null==t)throw makeError("an ENS name used for a contract target must be correctly configured","UNCONFIGURED_NAME",{value:e});return getInternal(this).addr=t,t})}else i=e.getAddress().then(e=>{if(null==e)throw new Error("TODO");return getInternal(this).addr=e,e});setInternal(this,{addrPromise:i,addr:a,deployTx:o,subs:l});return defineProperties(this,{filters:new Proxy({},{get:(e,t,n)=>{if("symbol"==typeof t||passProperties.indexOf(t)>=0)return Reflect.get(e,t,n);try{return this.getEvent(t)}catch(s){if(!isError(s,"INVALID_ARGUMENT")||"key"!==s.argument)throw s}},has:(e,t)=>passProperties.indexOf(t)>=0?Reflect.has(e,t):Reflect.has(e,t)||this.interface.hasEvent(String(t))})}),defineProperties(this,{fallback:r.receive||r.fallback?buildWrappedFallback(this):null}),new Proxy(this,{get:(e,t,n)=>{if("symbol"==typeof t||t in e||passProperties.indexOf(t)>=0)return Reflect.get(e,t,n);try{return e.getFunction(t)}catch(s){if(!isError(s,"INVALID_ARGUMENT")||"key"!==s.argument)throw s}},has:(e,t)=>"symbol"==typeof t||t in e||passProperties.indexOf(t)>=0?Reflect.has(e,t):e.interface.hasFunction(t)})}connect(e){return new BaseContract(this.target,this.interface,e)}attach(e){return new BaseContract(e,this.interface,this.runner)}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const e=getProvider(this.runner);assert(e,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const t=await e.getCode(await this.getAddress());return"0x"===t?null:t}async waitForDeployment(){const e=this.deploymentTransaction();if(e)return await e.wait(),this;if(null!=await this.getDeployedCode())return this;const t=getProvider(this.runner);return assert(null!=t,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"}),new Promise((e,n)=>{const s=async()=>{try{if(null!=await this.getDeployedCode())return e(this);t.once("block",s)}catch(r){n(r)}};s()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(e){"string"!=typeof e&&(e=e.format());return buildWrappedMethod(this,e)}getEvent(e){return"string"!=typeof e&&(e=e.format()),buildWrappedEvent(this,e)}async queryTransaction(e){throw new Error("@TODO")}async queryFilter(e,t,n){null==t&&(t=0),null==n&&(n="latest");const{addr:s,addrPromise:r}=getInternal(this),i=s||await r,{fragment:a,topics:o}=await getSubInfo(this,e),l={address:i,topics:o,fromBlock:t,toBlock:n},c=getProvider(this.runner);return assert(c,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"}),(await c.getLogs(l)).map(e=>{let t=a;if(null==t)try{t=this.interface.getEvent(e.topics[0])}catch(n){}if(t)try{return new EventLog(e,this.interface,t)}catch(n){return new UndecodedEventLog(e,n)}return new Log(e,c)})}async on(e,t){const n=await getSub(this,"on",e);return n.listeners.push({listener:t,once:!1}),n.start(),this}async once(e,t){const n=await getSub(this,"once",e);return n.listeners.push({listener:t,once:!0}),n.start(),this}async emit(e,...t){return await emit(this,e,t,null)}async listenerCount(e){if(e){const t=await hasSub(this,e);return t?t.listeners.length:0}const{subs:t}=getInternal(this);let n=0;for(const{listeners:s}of t.values())n+=s.length;return n}async listeners(e){if(e){const t=await hasSub(this,e);return t?t.listeners.map(({listener:e})=>e):[]}const{subs:t}=getInternal(this);let n=[];for(const{listeners:s}of t.values())n=n.concat(s.map(({listener:e})=>e));return n}async off(e,t){const n=await hasSub(this,e);if(!n)return this;if(t){const e=n.listeners.map(({listener:e})=>e).indexOf(t);e>=0&&n.listeners.splice(e,1)}return null!=t&&0!==n.listeners.length||(n.stop(),getInternal(this).subs.delete(n.tag)),this}async removeAllListeners(e){if(e){const t=await hasSub(this,e);if(!t)return this;t.stop(),getInternal(this).subs.delete(t.tag)}else{const{subs:e}=getInternal(this);for(const{tag:t,stop:n}of e.values())n(),e.delete(t)}return this}async addListener(e,t){return await this.on(e,t)}async removeListener(e,t){return await this.off(e,t)}static buildClass(e){return class extends BaseContract{constructor(t,n=null){super(t,e,n)}}}static from(e,t,n){null==n&&(n=null);return new this(e,t,n)}}function _ContractBase(){return BaseContract}class Contract extends(_ContractBase()){}const ContractABIs={Splitter:SplitterABI,Managed:ManagedABI,Zoned:ZonedABI,Appreciative:AppreciativeABI,Bundle:BundleABI,Holons:HolonsABI};function formatEthNumber(e){return Number(formatEther(e))}class ContractQueries{constructor(e){this.provider=e}getContract(e,t){const n=ContractABIs[t];if(!n)throw new Error(`Unknown contract flavor: ${t}`);return new Contract(e,n,this.provider)}async detectFlavor(e){const t=new Contract(e,["function flavor() view returns (string)","function version() view returns (string)"],this.provider);try{return await t.flavor()}catch{return"Unknown"}}async getContractInfo(e,t){const n=this.getContract(e,t),[s,r,i,a,o]=await Promise.all([n.name().catch(()=>""),n.flavor().catch(()=>t),n.version().catch(()=>""),n.creator().catch(()=>ZeroAddress),n.getSize().catch(()=>0n)]);return{address:e,name:s,flavor:r,version:i,creator:a,memberCount:Number(o)}}async getMembers(e,t){const n=this.getContract(e,t),s=await n.getSize(),r=[];for(let i=0;i<s;i++){const e=await n.userIds(i);r.push(e)}return r}async getUserEthBalance(e,t,n){const s=this.getContract(e,t),r=await s.etherBalance(n);return{wei:r.toString(),eth:formatEthNumber(r)}}async getUserTokenBalance(e,t,n,s){const r=this.getContract(e,t),i=await r.tokenBalance(n,s);return{wei:i.toString(),formatted:formatEthNumber(i)}}async getTotalDeposited(e,t,n){const s=this.getContract(e,t),r=n||ZeroAddress,i=await s.totalDeposited(r);return{wei:i.toString(),formatted:formatEthNumber(i)}}async hasClaimed(e,t,n){return this.getContract(e,t).hasClaimed(n)}async getSplitterSplit(e){const t=this.getContract(e,"Splitter"),[n,s]=await Promise.all([t.internalContractSplitPercentage(),t.externalContractSplitPercentage()]);return{internalPercentage:Number(n),externalPercentage:Number(s),internalPercent:Number(n)/100,externalPercent:Number(s)/100}}async getSplitterChildren(e){const t=this.getContract(e,"Splitter"),[n,s]=await t.getContractAddresses(),r=[];for(let i=0;i<n.length;i++)r.push({key:n[i],address:s[i]});return r}async getSplitterUserPercentage(e,t){const n=this.getContract(e,"Splitter"),s=await n.percentages(t);return{basisPoints:Number(s),percent:Number(s)/100}}async getSplitterAllPercentages(e){const t=await this.getMembers(e,"Splitter"),n=this.getContract(e,"Splitter"),s=[];for(const r of t){const e=await n.percentages(r);s.push({userId:r,basisPoints:Number(e),percent:Number(e)/100})}return s}async getZonedConfig(e){const t=this.getContract(e,"Zoned"),[n,s,r,i]=await Promise.all([t.nzones(),t.a(),t.b(),t.c()]);return{numberOfZones:Number(n),rewardFunction:{a:Number(s),b:Number(r),c:Number(i)}}}async getUserZone(e,t){const n=this.getContract(e,"Zoned"),s=await n.zone(t);return Number(s)}async getZoneMembers(e,t){return this.getContract(e,"Zoned").getZoneMembers(t)}async getZonedBreakdown(e){const t=await this.getZonedConfig(e),n=this.getContract(e,"Zoned"),s=[];for(let r=1;r<=t.numberOfZones;r++){const e=await n.getZoneMembers(r);s.push({zone:r,members:e,memberCount:e.length})}return{config:t,zones:s,rewardWeights:(await n.calculateRewards()).map((e,t)=>({zone:t+1,weight:Number(e)}))}}async getManagedAppreciation(e,t){const n=this.getContract(e,"Managed"),s=await n.appreciation(t),r=await n.totalappreciation();return{userAppreciation:Number(s),totalAppreciation:Number(r),sharePercent:Number(r)>0?Number(s)/Number(r)*100:0}}async getManagedAllAppreciation(e){const t=await this.getMembers(e,"Managed"),n=this.getContract(e,"Managed"),s=await n.totalappreciation(),r=await n.maxAppreciation().catch(()=>0n),i=[];for(const a of t){const e=await n.appreciation(a);i.push({userId:a,appreciation:Number(e),sharePercent:Number(s)>0?Number(e)/Number(s)*100:0})}return{members:i,totalAppreciation:Number(s),maxAppreciation:Number(r)}}async getAppreciativePeer(e,t){const n=this.getContract(e,"Appreciative"),[s,r,i]=await Promise.all([n.appreciation(t),n.remainingappreciation(t),n.totalappreciation()]);return{received:Number(s),remainingToGive:Number(r),totalPool:Number(i),sharePercent:Number(i)>0?Number(s)/Number(i)*100:0}}async getAppreciativeAll(e){const t=await this.getMembers(e,"Appreciative"),n=this.getContract(e,"Appreciative"),s=await n.totalappreciation(),r=[];for(const i of t){const[e,t]=await Promise.all([n.appreciation(i),n.remainingappreciation(i)]);r.push({userId:i,received:Number(e),remainingToGive:Number(t),sharePercent:Number(s)>0?Number(e)/Number(s)*100:0})}return{members:r,totalAppreciation:Number(s)}}async getBundleConfig(e){const t=this.getContract(e,"Bundle"),[n,s,r,i,a]=await Promise.all([t.steepness(),t.nzones(),t.interiorPercentage(),t.exteriorPercentage(),t.electionActive()]);return{steepness:Number(n),numberOfZones:Number(s),interiorPercentage:Number(r)/100,exteriorPercentage:Number(i)/100,electionActive:a}}async getBundleSplit(e){const t=this.getContract(e,"Bundle"),[n,s]=await Promise.all([t.interiorPercentage(),t.exteriorPercentage()]);return{interiorBasisPoints:Number(n),exteriorBasisPoints:Number(s),interiorPercent:Number(n)/100,exteriorPercent:Number(s)/100}}async getBundleZoneWeights(e){const t=this.getContract(e,"Bundle");return(await t.getZoneWeights()).map((e,t)=>({zone:t+1,weight:Number(e)}))}async getBundleUserInfo(e,t){const n=this.getContract(e,"Bundle"),[s,r,i,a,o]=await Promise.all([n.zone(t),n.interiorShare(t),n.isInteriorMember(t),n.isExteriorMember(t),n.isBundleMember(t)]);return{zone:Number(s),interiorShareBasisPoints:Number(r),interiorSharePercent:Number(r)/100,isInteriorMember:i,isExteriorMember:a,isMember:o}}async getBundleInteriorMembers(e){return this.getContract(e,"Bundle").getInteriorMembers()}async getBundleZoneBreakdown(e){const t=await this.getBundleConfig(e),n=this.getContract(e,"Bundle"),s=[];for(let r=1;r<=t.numberOfZones;r++){const e=await n.getZoneMembers(r);s.push({zone:r,members:e,memberCount:e.length})}return{config:t,zones:s,zoneWeights:await this.getBundleZoneWeights(e)}}async getBundleElection(e){const t=this.getContract(e,"Bundle"),[n,s]=await Promise.all([t.electionActive(),t.getCandidates()]);if(!n)return{active:!1,candidates:[]};const r=[];for(const i of s){const e=await t.votes(i);r.push({userId:i,votes:Number(e)})}return{active:!0,candidates:r.sort((e,t)=>t.votes-e.votes)}}async getFullSnapshot(e){const t=await this.detectFlavor(e),n=await this.getContractInfo(e,t),s=await this.getMembers(e,t),r={...n,members:s,memberDetails:[]};for(const i of s){const n={userId:i,ethBalance:await this.getUserEthBalance(e,t,i),hasClaimed:await this.hasClaimed(e,t,i)};if("Splitter"===t){const t=await this.getSplitterUserPercentage(e,i);n.percentage=t}else"Zoned"===t?n.zone=await this.getUserZone(e,i):"Managed"===t?n.appreciation=await this.getManagedAppreciation(e,i):"Appreciative"===t?n.appreciation=await this.getAppreciativePeer(e,i):"Bundle"===t&&(n.bundleInfo=await this.getBundleUserInfo(e,i));r.memberDetails.push(n)}return"Splitter"===t?(r.split=await this.getSplitterSplit(e),r.children=await this.getSplitterChildren(e)):"Zoned"===t?r.zoneConfig=await this.getZonedBreakdown(e):"Managed"===t?r.appreciationSummary=await this.getManagedAllAppreciation(e):"Appreciative"===t?r.appreciationSummary=await this.getAppreciativeAll(e):"Bundle"===t&&(r.bundleConfig=await this.getBundleConfig(e),r.bundleSplit=await this.getBundleSplit(e),r.bundleZones=await this.getBundleZoneBreakdown(e),r.election=await this.getBundleElection(e)),r}}function withAIMethods(e){return class extends e{_requireAI(){if(!this._ai)throw new Error("AI services not initialized. Provide openaiKey in config.")}async summarize(e,t={}){return this._requireAI(),this._ai.llm.summarize(e,t)}async analyze(e,t,n={}){return this._requireAI(),this._ai.llm.analyze(e,t,n)}async extractKeywords(e,t={}){return this._requireAI(),this._ai.llm.extractKeywords(e,t)}async categorize(e,t,n={}){return this._requireAI(),this._ai.llm.categorize(e,t,n)}async translate(e,t,n={}){return this._requireAI(),this._ai.llm.translate(e,t,n)}async generateQuestions(e,t={}){return this._requireAI(),this._ai.llm.generateQuestions(e,t)}async extractToSchema(e,t,n={}){this._requireAI();const s=await this.getSchema(t);if(!s)throw new Error(`No schema found for lens: ${t}`);return this._ai.schemaExtractor.extractToSchema(e,s,n)}async jsonAdd(e,t,n={}){return this._requireAI(),this._ai.jsonOps.add(e,t,n)}async jsonSubtract(e,t,n={}){return this._requireAI(),this._ai.jsonOps.subtract(e,t,n)}async jsonUnion(e,t,n={}){return this._requireAI(),this._ai.jsonOps.union(e,t,n)}async jsonDifference(e,t,n={}){return this._requireAI(),this._ai.jsonOps.difference(e,t,n)}async jsonConcatenate(e,t,n={}){return this._requireAI(),this._ai.jsonOps.concatenate(e,t,n)}async embed(e){return this._requireAI(),this._ai.embeddings.embed(e)}async semanticSearch(e,t,n,s={}){return this._requireAI(),this._ai.embeddings.semanticSearch(e,t,n,s)}async storeWithEmbedding(e,t,n,s="description"){return this._requireAI(),this._ai.embeddings.storeWithEmbedding(e,t,n,s)}async askCouncil(e,t={}){return this._requireAI(),this._ai.council.ask(e,t)}async askCouncilCustom(e,t,n={}){return this._requireAI(),this._ai.council.askCustom(e,t,n)}async textToSpeech(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speak(e,t,n)}async textToSpeechBase64(e,t="nova",n={}){return this._requireAI(),this._ai.tts.speakBase64(e,t,n)}async nlQuery(e,t=null,n=null,s={}){return this._requireAI(),this._ai.nlQuery.execute(e,t,n,s)}async parseNLQuery(e){return this._requireAI(),this._ai.nlQuery.parse(e)}async classifyToLens(e,t={}){return this._requireAI(),this._ai.classifier.classifyToLens(e,t)}async autoStore(e,t,n={}){return this._requireAI(),this._ai.classifier.autoStore(e,t,n)}registerLensForClassification(e,t,n=[]){this._requireAI(),this._ai.classifier.registerLens(e,t,n)}async analyzeRegion(e,t=null,n=null,s={}){return this._requireAI(),this._ai.spatial.analyzeRegion(e,t,n,s)}async compareRegions(e,t,n=null){return this._requireAI(),this._ai.spatial.compareRegions(e,t,n)}async spatialTrends(e,t,n=null){return this._requireAI(),this._ai.spatial.spatialTrends(e,t,n)}async smartUpcast(e,t,n={}){return this._requireAI(),this._ai.aggregation.smartUpcast(e,t,n)}async generateHolonSummary(e){return this._requireAI(),this._ai.aggregation.generateHolonSummary(e)}async suggestFederations(e,t={}){return this._requireAI(),this._ai.federationAdvisor.suggestFederations(e,t)}async analyzeFederationHealth(e){return this._requireAI(),this._ai.federationAdvisor.analyzeFederationHealth(e)}async optimizeFederation(e){return this._requireAI(),this._ai.federationAdvisor.optimizeFederation(e)}async discoverRelationships(e,t=null){return this._requireAI(),this._ai.relationships.discoverRelationships(e,t)}async findSimilar(e,t,n=null,s={}){return this._requireAI(),this._ai.relationships.findSimilar(e,t,n,s)}async buildRelationshipGraph(e,t){return this._requireAI(),this._ai.relationships.buildGraph(e,t)}async suggestConnections(e,t,n){return this._requireAI(),this._ai.relationships.suggestConnections(e,t,n)}async breakdown(e,t,n,s={}){return this._requireAI(),this._ai.taskBreakdown.breakdown(e,t,n,s)}async suggestBreakdownStrategy(e){return this._requireAI(),this._ai.taskBreakdown.suggestStrategy(e)}flattenBreakdown(e){return this._requireAI(),this._ai.taskBreakdown.flatten(e)}getBreakdownDependencyOrder(e){return this._requireAI(),this._ai.taskBreakdown.getDependencyOrder(e)}async getBreakdownProgress(e,t,n){return this._requireAI(),this._ai.taskBreakdown.getProgress(e,t,n)}async suggestH3Resolution(e,t={}){return this._requireAI(),this._ai.h3ai.suggestResolution(e,t)}async analyzeH3Distribution(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeDistribution(e,t,n)}async findH3NeighborRelevance(e,t,n={}){return this._requireAI(),this._ai.h3ai.findNeighborRelevance(e,t,n)}async suggestGeographicScope(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestGeographicScope(e,t,n,s)}async analyzeH3Coverage(e,t,n={}){return this._requireAI(),this._ai.h3ai.analyzeCoverage(e,t,n)}async crossH3ResolutionInsights(e,t,n={}){return this._requireAI(),this._ai.h3ai.crossResolutionInsights(e,t,n)}async suggestH3Migration(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.suggestMigration(e,t,n,s)}async generateH3Report(e,t={}){return this._requireAI(),this._ai.h3ai.generateGeographicReport(e,t)}async findH3Clusters(e,t,n={}){return this._requireAI(),this._ai.h3ai.findGeographicClusters(e,t,n)}async analyzeH3Impact(e,t,n,s={}){return this._requireAI(),this._ai.h3ai.analyzeGeographicImpact(e,t,n,s)}}}function withContractMethods(e){return class extends e{hasContracts(){return null!==this._contracts}_requireContracts(){if(!this._contracts)throw new Error("Contracts not initialized. Call initContracts() first.");return this._contracts}async initContracts(e){const t=new ChainManager(e),n=await t.connect(e.network,e.privateKey,e.rpcUrl),s=new ContractDeployer(t),r=new HolonContracts(t,s);return this._contracts={chainManager:t,deployer:s,holonContracts:r,network:e.network},{...n,address:e.privateKey?await t.getAddress():null}}async initContractsBrowser(e){const t=new ChainManager,n=await t.connectBrowser(e),s=new ContractDeployer(t),r=new HolonContracts(t,s);return this._contracts={chainManager:t,deployer:s,holonContracts:r,network:t.networkName},n}async deployContracts(e={}){const{deployer:t}=this._requireContracts();return t.deployAll(e)}loadDeployedContracts(e){const{deployer:t}=this._requireContracts();t.loadDeployedAddresses(e)}getDeployedContracts(){const{deployer:e}=this._requireContracts();return e.getDeployedAddresses()}async deployHolonContract(e,t="Splitter",n={}){const{holonContracts:s}=this._requireContracts();return s.deploy(e,t,n)}async linkHolonContract(e,t,n="Splitter"){const{holonContracts:s}=this._requireContracts();return s.link(e,t,n)}async unlinkHolonContract(e){const{holonContracts:t}=this._requireContracts();return t.unlink(e)}getHolonContract(e){return this._contracts?this._contracts.holonContracts.getContract(e):null}getHolonContractAddress(e){return this._contracts?this._contracts.holonContracts.getAddress(e):null}hasHolonContract(e){return!!this._contracts&&this._contracts.holonContracts.hasContract(e)}listHolonContracts(){return this._contracts?this._contracts.holonContracts.listAll():[]}getHolonOperations(e){const{holonContracts:t}=this._requireContracts();return t.requireOperations(e)}async contractAddMember(e,t){return this.getHolonOperations(e).addMember(t)}async contractAddMembers(e,t){return this.getHolonOperations(e).addMembers(t)}async contractIsMember(e,t){return this.getHolonOperations(e).isMember(t)}async contractReward(e,t,n){return this.getHolonOperations(e).reward(t,n)}async contractRewardEth(e,t){return this.getHolonOperations(e).rewardEth(t)}async contractSendEth(e,t){return this.getHolonOperations(e).sendEth(t)}async contractClaim(e,t,n){return this.getHolonOperations(e).claim(t,n)}async contractGetEthBalance(e,t){return this.getHolonOperations(e).getEthBalance(t)}async contractGetTokenBalance(e,t,n){return this.getHolonOperations(e).getTokenBalance(t,n)}async contractSetSplit(e,t,n){return this.getHolonOperations(e).setContractSplit(t,n)}async contractGetSplit(e){return this.getHolonOperations(e).getContractSplit()}async contractCreateManaged(e,t,n){return this.getHolonOperations(e).createManagedContract(t,n)}async contractCreateZoned(e,t,n,s=6){return this.getHolonOperations(e).createZonedContract(t,n,s)}async contractGetChildContracts(e){return this.getHolonOperations(e).getChildContracts()}async contractSetAppreciation(e,t,n){return this.getHolonOperations(e).setAppreciation(t,n)}async contractGetAppreciation(e,t){return this.getHolonOperations(e).getAppreciation(t)}async contractGetTotalAppreciation(e){return this.getHolonOperations(e).getTotalAppreciation()}async contractAddToZone(e,t,n,s){return this.getHolonOperations(e).addToZone(t,n,s)}async contractRemoveFromZone(e,t,n){return this.getHolonOperations(e).removeFromZone(t,n)}async contractGetZone(e,t){return this.getHolonOperations(e).getZone(t)}async contractSetZoneParams(e,t,n,s,r){return this.getHolonOperations(e).setZoneParameters(t,n,s,r)}async contractAppreciate(e,t,n,s){return this.getHolonOperations(e).appreciate(t,n,s)}async contractGetAppreciationGiven(e,t){return this.getHolonOperations(e).getAppreciationGiven(t)}async contractGetAppreciationReceived(e,t){return this.getHolonOperations(e).getAppreciationReceived(t)}async contractSetSteepness(e,t){return this.getHolonOperations(e).setSteepness(t)}async contractGetSteepness(e){return this.getHolonOperations(e).getSteepness()}async contractSetInteriorSplit(e,t,n){return this.getHolonOperations(e).setInteriorSplit(t,n)}async contractStartElection(e){return this.getHolonOperations(e).startElection()}async contractNominate(e){return this.getHolonOperations(e).nominateSelf()}async contractVote(e,t){return this.getHolonOperations(e).vote(t)}async contractFinalizeElection(e){return this.getHolonOperations(e).finalizeElection()}async contractGetName(e){return this.getHolonOperations(e).getName()}async contractGetOwner(e){return this.getHolonOperations(e).getOwner()}async contractGetBotAddress(e){return this.getHolonOperations(e).getBotAddress()}async contractGetTotalDeposited(e,t){return this.getHolonOperations(e).getTotalDeposited(t)}getNetworkUtils(){return networks}getChainManager(){return this._contracts?.chainManager||null}}}const FEDERATION_REQUEST_KIND=30078,FEDERATION_ACCEPT_KIND=30079,FEDERATION_DECLINE_KIND=30080;async function sendFederationRequest(e,t,n,s={}){const{scope:r={holonId:"*",lensName:"*"},permissions:i=["read"],message:a="Federation request",expiresIn:o=2592e6}=s,l=await issueCapability$1(i,r,n,{issuerKey:e.privateKey,expiresIn:o}),c={kind:FEDERATION_REQUEST_KIND,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-request-${n.slice(0,16)}`],["p",n],["holosphere",t],["scope",JSON.stringify(r)],["permissions",i.join(",")]],content:JSON.stringify({message:a,offeredCapability:l,requestedScope:r,requestedPermissions:i})},u=await e.publish(c);return{eventId:u.id||null,targetPubKey:n,scope:r,permissions:i,offeredCapability:l,...u}}async function subscribeFederationRequests(e,t){const n={kinds:[FEDERATION_REQUEST_KIND],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content),s=e.tags.find(e=>"scope"===e[0]),r=e.tags.find(e=>"permissions"===e[0]),i=e.tags.find(e=>"holosphere"===e[0]),a={eventId:e.id,requesterPubKey:e.pubkey,appname:i?.[1],scope:s?JSON.parse(s[1]):{holonId:"*",lensName:"*"},permissions:r?r[1].split(","):["read"],message:n.message,offeredCapability:n.offeredCapability,timestamp:e.created_at};t(a)}catch(n){console.error("Failed to parse federation request:",n)}})}async function acceptFederationRequest(e,t,n,s={}){const{scope:r=n.scope,permissions:i=n.permissions,alias:a=null,expiresIn:o=2592e6}=s,l=await issueCapability$1(i,r,n.requesterPubKey,{issuerKey:e.privateKey,expiresIn:o});await addFederatedPartner(e,t,n.requesterPubKey,{alias:a,addedVia:"nostr_discovery",inboundCapabilities:[{token:n.offeredCapability,scope:n.scope,permissions:n.permissions,expires:Date.now()+o}]});const c={kind:FEDERATION_ACCEPT_KIND,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-accept-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t],["scope",JSON.stringify(r)],["permissions",i.join(",")]],content:JSON.stringify({acceptedScope:r,grantedCapability:l})},u=await e.publish(c);return{eventId:u.id||null,requesterPubKey:n.requesterPubKey,grantedCapability:l,acceptedScope:r,...u}}async function declineFederationRequest(e,t,n,s=""){const r={kind:FEDERATION_DECLINE_KIND,created_at:Math.floor(Date.now()/1e3),tags:[["d",`federation-decline-${n.requesterPubKey.slice(0,16)}`],["p",n.requesterPubKey],["e",n.eventId],["holosphere",t]],content:JSON.stringify({reason:s})},i=await e.publish(r);return{eventId:i.id||null,requesterPubKey:n.requesterPubKey,reason:s,...i}}async function subscribeFederationAcceptances(e,t,n){const s={kinds:[FEDERATION_ACCEPT_KIND],"#p":[e.publicKey]};return e.subscribe(s,async s=>{try{const r=JSON.parse(s.content),i=s.tags.find(e=>"scope"===e[0]),a=s.tags.find(e=>"permissions"===e[0]);await storeInboundCapability(e,t,s.pubkey,{token:r.grantedCapability,scope:i?JSON.parse(i[1]):r.acceptedScope,permissions:a?a[1].split(","):["read"],expires:Date.now()+2592e6}),n({accepterPubKey:s.pubkey,originalRequestId:s.tags.find(e=>"e"===e[0])?.[1],acceptedScope:r.acceptedScope,grantedCapability:r.grantedCapability,timestamp:s.created_at})}catch(r){console.error("Failed to parse federation acceptance:",r)}})}async function subscribeFederationDeclines(e,t){const n={kinds:[FEDERATION_DECLINE_KIND],"#p":[e.publicKey]};return e.subscribe(n,e=>{try{const n=JSON.parse(e.content);t({declinerPubKey:e.pubkey,originalRequestId:e.tags.find(e=>"e"===e[0])?.[1],reason:n.reason||"",timestamp:e.created_at})}catch(n){console.error("Failed to parse federation decline:",n)}})}async function getPendingFederationRequests(e,t={}){const n=t.since||Math.floor((Date.now()-2592e6)/1e3),s={kinds:[FEDERATION_REQUEST_KIND],authors:[e.publicKey],since:n},r=await e.query(s),i={kinds:[FEDERATION_ACCEPT_KIND,FEDERATION_DECLINE_KIND],"#p":[e.publicKey],since:n},a=await e.query(i),o=new Set;for(const u of a){const e=u.tags.find(e=>"e"===e[0]);e&&o.add(e[1])}const l=[];for(const u of r)if(!o.has(u.id))try{const e=JSON.parse(u.content),t=u.tags.find(e=>"p"===e[0]),n=u.tags.find(e=>"scope"===e[0]),s=u.tags.find(e=>"permissions"===e[0]);l.push({eventId:u.id,targetPubKey:t?.[1],scope:n?JSON.parse(n[1]):{holonId:"*",lensName:"*"},permissions:s?s[1].split(","):["read"],message:e.message,timestamp:u.created_at})}catch(c){console.error("Failed to parse pending request:",c)}return l}class AuthorizationError extends Error{constructor(e,t=null){super(e),this.name="AuthorizationError",this.requiredPermission=t}}class ValidationError extends Error{constructor(e){super(e),this.name="ValidationError"}}function withFederationMethods(e){return class extends e{async federate(e,t,n,s={}){const{direction:r="outbound",mode:i="reference",propagate:a=!0,capability:o=null,permissions:l=["read"],filter:c=null}=s,u=e=>"string"==typeof e&&/^[0-9a-f]{64}$/i.test(e),d="string"==typeof e?{holonId:e,authorPubKey:u(e)?e:this.client.publicKey}:{holonId:e.holonId,authorPubKey:e.authorPubKey||(u(e.holonId)?e.holonId:this.client.publicKey)},f="string"==typeof t?{holonId:t,authorPubKey:u(t)?t:this.client.publicKey}:{holonId:t.holonId,authorPubKey:t.authorPubKey||(u(t.holonId)?t.holonId:this.client.publicKey)};if(d.holonId===f.holonId&&d.authorPubKey===f.authorPubKey)throw new ValidationError("Cannot federate a holon with itself");if(!["inbound","outbound","bidirectional"].includes(r))throw new ValidationError(`Invalid direction: ${r}. Must be 'inbound', 'outbound', or 'bidirectional'`);const h=d.authorPubKey===f.authorPubKey;let p=o;if(!p){const e=h?31536e6:864e5;p=await issueCapability$1(l,{holonId:d.holonId,lensName:n,dataId:"*"},f.authorPubKey,{expiresIn:e,issuer:d.authorPubKey,issuerKey:this.client.privateKey,isSelfCapability:h}),h?await storeSelfCapability(this.client,this.config.appName,{token:p,scope:{holonId:d.holonId,lensName:n},permissions:l}):await storeInboundCapability(this.client,this.config.appName,d.authorPubKey,{token:p,scope:{holonId:d.holonId,lensName:n},permissions:l})}const y={source:d,target:f,lensName:n,direction:r,mode:i,propagate:a,capability:p,isSelfFederation:h,propagated:{outbound:0,inbound:0}};if(a&&("outbound"===r||"bidirectional"===r)){const e=await this.read(d.holonId,n,null,{resolveHolograms:!1});if(e&&Array.isArray(e))for(const t of e)c&&!c(t)||(await propagateData(this.client,this.config.appName,t,d.holonId,f.holonId,n,i,{sourceAuthorPubKey:d.authorPubKey,capability:p}),y.propagated.outbound++)}if(a&&("inbound"===r||"bidirectional"===r)){const e=await this.read(f.holonId,n,null,{resolveHolograms:!1});if(e&&Array.isArray(e))for(const t of e)c&&!c(t)||(await propagateData(this.client,this.config.appName,t,f.holonId,d.holonId,n,i,{sourceAuthorPubKey:f.authorPubKey,capability:p}),y.propagated.inbound++)}return await setupFederation(this.client,this.config.appName,d.holonId,f.holonId,n,{direction:r,mode:i}),y}async unfederate(e,t,n){const s="string"==typeof e?{holonId:e,authorPubKey:this.client.publicKey}:{holonId:e.holonId,authorPubKey:e.authorPubKey||this.client.publicKey};"string"==typeof t?this.client.publicKey:(t.holonId,t.authorPubKey||this.client.publicKey);const r=buildPath(this.config.appName,s.holonId,n,"_federation");try{await deleteData(this.client,r)}catch(i){}return!0}async addFederatedHolosphere(e,t={}){if(!e||"string"!=typeof e)throw new ValidationError("pubKey must be a valid public key string");return addFederatedPartner(this.client,this.config.appName,e,t)}async removeFederatedHolosphere(e){return removeFederatedPartner(this.client,this.config.appName,e)}async getFederatedHolospheres(){return getFederatedAuthors(this.client,this.config.appName)}async getFederationRegistry(){return getFederationRegistry(this.client,this.config.appName)}async storeInboundCapability(e,t){return storeInboundCapability(this.client,this.config.appName,e,t)}async readFromFederatedSource(e,t,n,s=null){const r=await getCapabilityForAuthor(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!r)throw new AuthorizationError("No valid capability for federated source","read");if(!(await this.verifyCapability(r.token,"read",{holonId:t,lensName:n,dataId:s})))throw new AuthorizationError("Capability verification failed","read");if(s){const r=buildPath(this.config.appName,t,n,s);return nostrGet(this.client,r,3e4,{authors:[e],includeAuthor:!0})}{const s=buildPath(this.config.appName,t,n);return nostrGetAll(this.client,s,3e4,{authors:[e],includeAuthor:!0})}}async createCrossHolosphereHologram(e,t,n,s,r,i={}){const{embedCapability:a=!0}=i,o=await getCapabilityForAuthor(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:s});if(!o)throw new AuthorizationError("No valid capability for cross-holosphere hologram","read");const l=createHologram(t,r,n,s,this.config.appName,{authorPubKey:e,capability:a?o.token:null}),c=buildPath(this.config.appName,r,n,s);return await write(this.client,c,l),l}async issueCapabilityForFederation(e,t,n,s={}){const{expiresIn:r=36e5,trackInRegistry:i=!0}=s,a=await issueCapability$1(n,t,e,{expiresIn:r,issuerKey:this.client.privateKey});if(i){await getFederatedPartner(this.client,this.config.appName,e)||await addFederatedPartner(this.client,this.config.appName,e,{addedVia:"capability_issued"}),await storeOutboundCapability(this.client,this.config.appName,e,{tokenHash:await this._hashToken(a),scope:t,permissions:n,expires:Date.now()+r})}return a}async _hashToken(e){const t=new TextEncoder;return bytesToHex$1(sha256(t.encode(e)))}async sendFederationRequest(e,t={}){return sendFederationRequest(this.client,this.config.appName,e,t)}async subscribeFederationRequests(e){return subscribeFederationRequests(this.client,e)}async acceptFederationRequest(e,t={}){return acceptFederationRequest(this.client,this.config.appName,e,t)}async declineFederationRequest(e,t=""){return declineFederationRequest(this.client,this.config.appName,e,t)}async subscribeFederationAcceptances(e){return subscribeFederationAcceptances(this.client,this.config.appName,e)}async subscribeFederationDeclines(e){return subscribeFederationDeclines(this.client,e)}async getPendingFederationRequests(e={}){return getPendingFederationRequests(this.client,e)}async receiveFederatedLens(e,t,n,s,r={}){const{filter:i=null,overwrite:a=!1}=r,o=await getCapabilityForAuthor(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:"*"});if(!o)throw new AuthorizationError(`No valid capability to access ${t}/${n} from ${e}`,"read");const l=buildPath(this.config.appName,t,n),c=await nostrGetAll(this.client,l,3e4,{authors:[e],includeAuthor:!0});if(!c||!Array.isArray(c))return{received:0,skipped:0,errors:[]};const u={received:0,skipped:0,errors:[]};for(const f of c)if(f&&f.id)if(!i||i(f)){if(!a){const e=buildPath(this.config.appName,s,n,f.id),t=await read(this.client,e);if(t&&t.hologram){u.skipped++;continue}}try{const r=await createHologramWithCapability(this.client,t,s,n,f.id,this.config.appName,{sourceAuthorPubKey:e,targetAuthorPubKey:this.client.publicKey,capability:o.token,permissions:["read"]}),i=buildPath(this.config.appName,s,n,f.id);await write(this.client,i,r),u.received++}catch(d){u.errors.push({id:f.id,error:d.message})}}else u.skipped++;return u}async subscribeFederatedLens(e,t,n,s,r={}){const{onHologram:i,onError:a,filter:o=null}=r,l=await getCapabilityForAuthor(this.client,this.config.appName,e,{holonId:t,lensName:n,dataId:"*"});if(!l)throw new AuthorizationError(`No valid capability to subscribe to ${t}/${n} from ${e}`,"read");const c=new Set,u=buildPath(this.config.appName,t,n),d=await nostrSubscribe(this.client,u,async r=>{if(r&&r.id&&!c.has(r.id)&&(c.add(r.id),!o||o(r)))try{const a=buildPath(this.config.appName,s,n,r.id),o=await read(this.client,a);if(o&&o.hologram)return;const c=await createHologramWithCapability(this.client,t,s,n,r.id,this.config.appName,{sourceAuthorPubKey:e,targetAuthorPubKey:this.client.publicKey,capability:l.token,permissions:["read"]}),u=buildPath(this.config.appName,s,n,r.id);await write(this.client,u,c),i&&i(c,r)}catch(u){a&&a(u)}},3e4);return{unsubscribe:()=>{d&&d.unsubscribe&&d.unsubscribe(),c.clear()},processedCount:()=>c.size}}async syncFederatedLenses(e,t={}){const{overwrite:n=!1}=t,s=await this.readGlobal("federation",e);if(!s)return{error:"No federation configuration found for this holon"};const r={},i=await this.getFederatedHolospheres();for(const o of i){r[o]={lenses:{},errors:[]};const t=s.lensConfig?.[o],i=t?.inbound||[];for(const s of i)try{const i=t?.holonId||e,a=await this.receiveFederatedLens(o,i,s,e,{overwrite:n});r[o].lenses[s]=a}catch(a){r[o].errors.push({lens:s,error:a.message})}}return r}async canAccess(e,t,n,s,r={}){const{actingAsHolon:i=null,capabilityToken:a=null}=r;if(n===e)return{allowed:!0,via:"owner"};if(a)try{if(await this.verifyCapability(a,s,{holonId:e,lensName:t}))return{allowed:!0,via:"capability"}}catch(l){console.log("[canAccess] Capability verification failed:",l.message)}try{const t=await this.get(e,"users");if(t&&Array.isArray(t)){if(t.some(e=>e.pubKey===n||e.id===n||e.nostrPubKey===n))return{allowed:!0,via:"membership"}}}catch(l){console.log("[canAccess] Could not read users lens:",l.message)}const o={holonId:e,lensName:t};if(i){if(!(await this.getHolonsForPubKey(n)).some(e=>e.id===i))return{allowed:!1,via:"none",reason:"Not a member of the acting holon"};const e=await findAccessGrant(this.client,this.config.appName,i,o,s,{direction:"inbound"});if(e)return{allowed:!0,via:"federation",grant:e,reason:`Acting as ${i} with ${s} grant`}}else{const e=await this.getHolonsForPubKey(n);for(const t of e){const e=await findAccessGrant(this.client,this.config.appName,t.id,o,s,{direction:"inbound"});if(e)return{allowed:!0,via:"federation",grant:e,reason:`Member of ${t.name||t.id} which has ${s} grant`,viaHolon:t.id}}}return{allowed:!1,via:"none",reason:"No access"}}async canWrite(e,t,n,s={}){const r=await this.canAccess(e,t,n,"write",s);return{canWrite:r.allowed,reason:r.reason||r.via,accessType:r.via,viaHolon:r.viaHolon,grant:r.grant}}async canRead(e,t,n,s={}){const r=await this.canAccess(e,t,n,"read",s);return{canRead:r.allowed,reason:r.reason||r.via,accessType:r.via,viaHolon:r.viaHolon,grant:r.grant}}async getHolonsForPubKey(e){const t=[];t.push({id:e,name:"Personal Holon"});try{const s=await getFederationRegistry(this.client,this.config.appName);if(s&&s.federatedWith)for(const r of s.federatedWith)try{const n=await this.get(r.pubKey,"users");if(n&&Array.isArray(n)){n.some(t=>t.pubKey===e||t.id===e||t.nostrPubKey===e)&&t.push({id:r.pubKey,name:r.alias||r.pubKey})}}catch(n){}}catch(n){console.warn("[getHolonsForPubKey] Error reading federation registry:",n.message)}return t}async grantWriteAccess(e,t,n={}){return grantWriteAccessToHolon(this.client,this.config.appName,e,t,n)}async revokeWriteAccess(e,t){return revokeWriteAccess(this.client,this.config.appName,e,t)}async getWriteGrantsForHolon(e){return getWriteGrantsForHolon(this.client,this.config.appName,e)}async getAllWriteGrants(){return getAllWriteGrants(this.client,this.config.appName)}}}function createAIServices(e,t=null,n={},s=null){const r=new LLMService(e,n.llm),i=s,a=new Embeddings(i,t);return{llm:r,openai:i,embeddings:a,schemaExtractor:new SchemaExtractor(r),jsonOps:new JSONOps(r),council:new Council(r),tts:new TTS(i),nlQuery:new NLQuery(r,t),classifier:new Classifier(r,t),spatial:new SpatialAnalysis(r,t),aggregation:new SmartAggregation(r,t),federationAdvisor:new FederationAdvisor(r,t,a),relationships:new RelationshipDiscovery(r,t,a),taskBreakdown:new TaskBreakdown(r,t),h3ai:new H3AI(r,t)}}
17
- /**
18
- * @fileoverview HoloSphere - Holonic Geospatial Communication Infrastructure
19
- *
20
- * This is the main entry point for the HoloSphere library, providing a comprehensive
21
- * distributed P2P geospatial communication system. It combines H3 hexagonal indexing
22
- * for spatial organization, Nostr protocol for distributed storage, smart contracts
23
- * for fund distribution, and AI services for intelligent data processing.
24
- *
25
- * @module holosphere
26
- * @author HoloSphere Team
27
- * @license MIT
28
- */class HoloSphereBase extends HoloSphere$1{constructor(e){super(e),this.schemas=new Map,this._cache=new Map,this.subscriptionRegistry=new SubscriptionRegistry,this._writeCache=new Map,this._pendingWrites=new Map,this._deleteCache=new Set,this._ai=null;const t=e.openaiKey||this._getEnv("OPENAI_API_KEY");if(t){const n={...e.aiOptions,model:e.aiOptions?.model||this._getEnv("HOLOSPHERE_AI_MODEL"),temperature:e.aiOptions?.temperature??this._parseFloat(this._getEnv("HOLOSPHERE_AI_TEMPERATURE"))};this._initializeAI(t,n)}this._contracts=null,this.keyStore=new LensKeyStore,this._encryptionConfig={encryptByDefault:e.encryptByDefault??!1,publicLenses:e.publicLenses||["profile","settings","public"]}}_getEnv(e){if("undefined"!=typeof process&&process.env)return process.env[e]}_parseFloat(e){if(null==e)return;const t=parseFloat(e);return isNaN(t)?void 0:t}_initializeAI(e,t={}){const n={...t.llm,model:t.model||t.llm?.model,temperature:t.temperature??t.llm?.temperature};this._ai={llm:new LLMService(e,n)};const s=new(0,require("openai").default)({apiKey:e});this._ai.openai=s,this._ai.embeddings=new Embeddings(s,this),this._ai.schemaExtractor=new SchemaExtractor(this._ai.llm),this._ai.jsonOps=new JSONOps(this._ai.llm),this._ai.council=new Council(this._ai.llm),this._ai.tts=new TTS(s),this._ai.nlQuery=new NLQuery(this._ai.llm,this),this._ai.classifier=new Classifier(this._ai.llm,this),this._ai.spatial=new SpatialAnalysis(this._ai.llm,this),this._ai.aggregation=new SmartAggregation(this._ai.llm,this),this._ai.federationAdvisor=new FederationAdvisor(this._ai.llm,this,this._ai.embeddings),this._ai.relationships=new RelationshipDiscovery(this._ai.llm,this,this._ai.embeddings),this._ai.taskBreakdown=new TaskBreakdown(this._ai.llm,this),this._ai.h3ai=new H3AI(this._ai.llm,this)}hasAI(){return null!==this._ai}getAIServices(){return this._ai}async toHolon(e,t,n){return toHolon(e,t,n)}async getParents(e,t){return getParents(e,t)}async getChildren(e){return getChildren(e)}isValidH3(e){return isValidH3(e)}async registerHolon(e,t,n={}){return registerHolon(this.client,this.config.appName,e,t,n)}async lookupHolon(e){return lookupHolon(this.client,this.config.appName,e)}async unregisterHolon(e){return unregisterHolon(this.client,this.config.appName,e)}async getRegisteredHolons(){return listRegisteredHolons(this.client,this.config.appName)}async write(e,t,n,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),!e)throw new ValidationError$1("ValidationError: holonId must be a non-empty string");if(!t)throw new ValidationError$1("ValidationError: lensName must be a non-empty string");if(!n||"object"!=typeof n)throw new ValidationError$1("ValidationError: data must be an object");const r="string"==typeof e&&/^[0-9a-f]{64}$/i.test(e);let i=this.client?.publicKey;if(s.signingKey)try{i=getPublicKey(s.signingKey)}catch(d){this._log("WARN","⚠️ Invalid signingKey provided, using client key",{error:d.message})}const a=i&&(e===i||!r),o=s.capabilityToken||s.capability,l=s.actingAs||s.actingAsHolon;if(s.externalWriter)this._log("DEBUG","✅ External writer — skipping auth",{writerPubKey:i?.slice(0,12)+"...",holonId:e?.slice(0,12)+"..."});else if(a){if(o){if(!(await this.verifyCapability(o,"write",{holonId:e,lensName:t})))throw new AuthorizationError("AuthorizationError: Invalid capability token for write operation","write")}}else if(o){if(!(await this.verifyCapability(o,"write",{holonId:e,lensName:t})))throw this._log("WARN","🚫 Write denied: Invalid capability token",{holonId:e,lensName:t}),new AuthorizationError("Invalid capability token for write operation","write");this._log("DEBUG","✅ Write authorized via capability token",{holonId:e,lensName:t})}else{const n=i;if(!n)throw this._log("WARN","🚫 Write denied: No authenticated user",{holonId:e,lensName:t}),new AuthorizationError("Authentication required for writing to federated holons","write");const s=await this.canAccess(e,t,n,"write",{actingAsHolon:l});if(!s.allowed)throw this._log("WARN","🚫 Write denied: No write access",{holonId:e,lensName:t,reason:s.reason,via:s.via,writerPubKey:n?.slice(0,12)+"..."}),new AuthorizationError(`Write access denied: ${s.reason}`,"write");this._log("DEBUG","✅ Write authorized via unified access control",{holonId:e,lensName:t,via:s.via,reason:s.reason,grant:s.grant?"yes":"no"})}n.id?n.id=String(n.id):n.id=`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,n._meta||(n._meta={}),n._meta.createdAt=n._meta.createdAt||Date.now(),n._meta.updatedAt=Date.now();const c=buildPath(this.config.appName,e,t,n.id);if(this._log("DEBUG","write",{holonId:e,lensName:t,dataId:n.id,path:c,blocking:!!s.blocking}),!1!==s.validate&&this.schemas.has(t)){const e=this.schemas.get(t),r=void 0!==s.strict?s.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&validate(n,e.schema,t,r)}this._writeCache.set(c,{data:{...n},timestamp:Date.now()}),this._deleteCache.delete(c),this._log("DEBUG","📝 CACHE WRITE",{path:c,dataId:n.id,cacheSize:this._writeCache.size,mode:s.blocking?"blocking":"optimistic"});const u=this._syncWriteToRelay(e,t,n,c,s);return s.blocking?(this._log("DEBUG","⏳ BLOCKING: Waiting for relay confirmation",{path:c}),u):(this._log("DEBUG","⚡ OPTIMISTIC: Returning immediately, sync in background",{path:c}),!0)}async _syncWriteToRelay(e,t,n,s,r){const i=Date.now();this._log("DEBUG","🔄 RELAY SYNC START",{path:s,dataId:n.id,relays:this.client?.relays?.map(e=>e.url)||["local-only"]});try{const a=await read(this.client,s);if(a&&!0===a.hologram&&a.target)return this._log("DEBUG","🔗 Syncing hologram write",{path:s,target:a.target}),this._syncHologramWrite(a,n,s,t,r);const o=this._shouldEncryptLens(t,r);let l=null;if(o&&this.client?.privateKey&&this.client?.publicKey){const n=buildLensPath(this.config.appName,e,t),s=this.keyStore.getOrCreateKey(n,this.client.privateKey,this.client.publicKey);l=s.key,s.isNew&&(this._log("DEBUG","🔑 Generated new lens key",{lensPath:n}),this._storeWrappedKey(n,s.wrappedForSelf).catch(e=>{this._log("WARN","⚠️ Failed to persist wrapped key",{lensPath:n,error:e.message})}))}const c={...r.signingKey?{signingKey:r.signingKey}:{},...l?{lensKey:l}:{},waitForRelays:!0};await write(this.client,s,n,c);const u=Date.now()-i;this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=u,this._log("DEBUG","✅ RELAY SYNC SUCCESS",{path:s,dataId:n.id,duration:`${u}ms`,totalWrites:this._metrics.writes});const{autoPropagate:d=!0}=r;return d&&!n.hologram&&(this._log("DEBUG","📤 Starting propagation",{path:s}),this.propagate(e,t,n,r.propagationOptions||{}).catch(e=>this._log("WARN","⚠️ Propagation failed",{path:s,error:e.message}))),!0}catch(a){const e=Date.now()-i;return this._log("ERROR","❌ RELAY SYNC FAILED",{path:s,dataId:n.id,duration:`${e}ms`,error:a.message,stack:a.stack?.split("\n")[1]?.trim()}),this._log("WARN","💾 Data retained in write cache for retry",{path:s,cacheSize:this._writeCache.size}),!1}}async _syncHologramWrite(e,t,n,s,r){const i=["hologram","soul","target","id","_meta"],a=Object.keys(e).filter(e=>!i.includes(e)),o={...e},l={};for(const[d,f]of Object.entries(t))i.includes(d)||"_hologram"===d||(a.includes(d)?o[d]=f:l[d]=f);if(Object.keys(l).length>0&&!1!==r.validate&&this.schemas.has(s)){const t=buildPath(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId),n={...await read(this.client,t),...l},i=this.schemas.get(s),a=void 0!==r.strict?r.strict:i.strict;i.schema&&"object"==typeof i.schema&&!i.schema.$ref&&validate(n,i.schema,s,a)}const c=Date.now();if(await write(this.client,n,o),Object.keys(l).length>0){const t=e.capability;if(!t)throw new Error("Hologram missing capability token for source update");if(!(await verifyCapability$1(t,"write",{holonId:e.target.holonId,lensName:e.target.lensName,dataId:e.target.dataId})))throw new Error("Write capability required to update source data through hologram");const n=buildPath(e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId);await update(this.client,n,l),await refreshActiveHolograms(this.client,e.target.appname||this.config.appName,e.target.holonId,e.target.lensName,e.target.dataId)}const u=Date.now();return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=u-c,!0}async _resolveHolonToPubkey(e){return resolveHolonToPubkey(this.client,this.config.appName,e)}async _getCapabilityForAuthor(e,t){return getCapabilityForAuthor(this.client,this.config.appName,e,t)}_shouldEncryptLens(e,t={}){return void 0!==t.encrypt?t.encrypt:!this._encryptionConfig.publicLenses.includes(e)&&this._encryptionConfig.encryptByDefault}async _storeWrappedKey(e,t){const n=buildPath(this.config.appName,"_keys","lens-keys",e.replace(/\//g,"_"));await write(this.client,n,{id:e.replace(/\//g,"_"),lensPath:e,wrappedKey:t,algorithm:"aes-256-gcm",keyWrap:"nip44",version:"1.0",createdAt:Date.now()})}async _loadStoredKeys(){if(!this.client?.privateKey||!this.client?.publicKey)return 0;const e=buildPath(this.config.appName,"_keys","lens-keys")+"/",t=await readAll(this.client,e);let n=0;for(const r of t)if(r&&r.lensPath&&r.wrappedKey)try{const e=unwrapKey(r.wrappedKey,this.client.privateKey,this.client.publicKey);this.keyStore.storeOwnKey(r.lensPath,e,r.wrappedKey),n++}catch(s){this._log("WARN","⚠️ Failed to restore lens key",{lensPath:r.lensPath,error:s.message})}return n>0&&this._log("DEBUG","🔑 Restored lens keys",{count:n}),n}_getLensKey(e,t){const n=buildLensPath(this.config.appName,e,t);return this.keyStore.getKey(n)}handleReceivedKeyShare(e,t){if(!this.client?.privateKey)return this._log("WARN","⚠️ Cannot receive key share: no private key"),!1;try{this.keyStore.receiveKey(e.lensPath,e.wrappedKey,this.client.privateKey,t);return this._log("DEBUG","🔑 Received and stored lens key",{lensPath:e.lensPath,from:t.slice(0,12)+"..."}),!0}catch(n){return this._log("ERROR","❌ Failed to receive key share",{lensPath:e.lensPath,error:n.message}),!1}}getEncryptionStats(){return this.keyStore.getStats()}hasLensKey(e,t){const n=buildLensPath(this.config.appName,e,t);return this.keyStore.hasKey(n)}isOwnLensKey(e,t){const n=buildLensPath(this.config.appName,e,t);return this.keyStore.isOwnKey(n)}async _resolveHolograms(e){if(!e)return e;if(Array.isArray(e)){const t=[];for(const n of e){const e=await this._resolveHolograms(n);null!==e&&t.push(e)}return t}return!0===e?.hologram&&e.target?resolveHologram(this.client,e,new Set,[],{appname:this.config.appName,deleteCircular:!1}):e}async read(e,t,n=null,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),null!=n&&(n=String(n)),!e)throw new ValidationError$1("ValidationError: holonId must be a non-empty string");if(!t)throw new ValidationError$1("ValidationError: lensName must be a non-empty string");if(n){const r=buildPath(this.config.appName,e,t,n);if(this._deleteCache.has(r))return this._log("DEBUG","🗑️ EARLY CACHE: Deleted item",{path:r}),null;const i=this._writeCache.get(r);if(i){const e=Date.now()-i.timestamp;this._log("DEBUG","⚡ EARLY CACHE HIT: Write cache",{path:r,cacheAge:`${e}ms`});const{resolveHolograms:t=!0}=s;return t&&i.data?this._resolveHolograms(i.data):i.data}}const r=s.skipResolve?null:await this._resolveHolonToPubkey(e),i=r&&r!==this.client.publicKey;this._log("DEBUG","🔍 READ: author check",{targetPubkey:r?.slice(0,12),clientPubkey:this.client?.publicKey?.slice(0,12),isOtherAuthor:i,holonId:e?.slice(0,12)});let a={};s.forceRelay&&(a.forceRelay=!0),s.timeout&&(a.timeout=s.timeout);const o=s.capabilityToken||s.capability;if(o){if(!(await this.verifyCapability(o,"read",{holonId:e,lensName:t,dataId:n})))throw new AuthorizationError("AuthorizationError: Invalid capability token for read operation","read");i&&(a.authors=[r])}else if(i){this._log("DEBUG","🔍 Looking up capability for federated author",{holonId:e,lensName:t,dataId:n||"*",targetPubkey:r?.slice(0,12)+"...",myPubkey:this.client?.publicKey?.slice(0,12)+"..."});if(!(await this._getCapabilityForAuthor(r,{holonId:e,lensName:t,dataId:n})))return this._log("WARN","❌ No capability found for federated author - returning empty",{holonId:e,lensName:t,targetPubkey:r?.slice(0,12)+"..."}),n?null:[];this._log("DEBUG","✅ Capability found for federated author",{holonId:e,lensName:t,targetPubkey:r?.slice(0,12)+"..."}),a.authors=[r]}i||(a.skipAuthorFilter=!0,this._log("DEBUG","🔍 Own holon read — skipping author filter for inclusive query",{holonId:e?.slice(0,12)}));const l=Date.now();let c;const u=this._getLensKey(e,t);if(u&&(a.lensKey=u),n){const s=buildPath(this.config.appName,e,t,n);if(this._deleteCache.has(s))this._log("DEBUG","🗑️ CACHE READ: Deleted item",{path:s,source:"delete-cache",deleteCacheSize:this._deleteCache.size}),c=null;else{const e=this._writeCache.get(s);if(e){const t=Date.now()-e.timestamp;this._log("DEBUG","⚡ CACHE HIT: Write cache",{path:s,source:"write-cache",cacheAge:`${t}ms`,writeCacheSize:this._writeCache.size}),c=e.data}else this._log("DEBUG","📖 CACHE MISS: Reading from storage",{path:s,authors:a.authors,hasKey:!!u}),c=await read(this.client,s,a),this._log("DEBUG","💾 STORAGE READ",{path:s,source:"storage",found:!!c,isHologram:!0===c?.hologram})}}else{const n=buildPath(this.config.appName,e,t);this._log("DEBUG","readAll",{holonId:e,lensName:t,path:n,authors:a.authors,hasKey:!!u});const s=await readAll(this.client,n,a);c=i?s:this._mergeWithWriteCache(s,n),this._log("DEBUG","readAll result",{count:Array.isArray(c)?c.length:0})}const{resolveHolograms:d=!0}=s;d&&c&&(this._log("DEBUG","resolving holograms",{itemCount:Array.isArray(c)?c.length:1}),c=await this._resolveHolograms(c));const f=Date.now();return this._metrics.reads++,this._metrics.totalReadTime||(this._metrics.totalReadTime=0),this._metrics.totalReadTime+=f-l,c}_mergeWithWriteCache(e,t){const n=Array.isArray(e)?[...e]:[],s=new Map(n.map(e=>[e.id,e]));for(const[r,i]of this._writeCache.entries())if(r.startsWith(t+"/")){const e=i.data;e.id&&s.set(e.id,e)}for(const r of this._deleteCache)if(r.startsWith(t+"/")){const e=r.split("/").pop();s.delete(e)}return Array.from(s.values())}async update(e,t,n,s,r={}){if(!e||"string"!=typeof e)throw new ValidationError$1("ValidationError: holonId must be a non-empty string");if(!t||"string"!=typeof t)throw new ValidationError$1("ValidationError: lensName must be a non-empty string");if(!n||"string"!=typeof n)throw new ValidationError$1("ValidationError: dataId must be a non-empty string");if(!s||"object"!=typeof s)throw new ValidationError$1("ValidationError: updates must be an object");const i="string"==typeof e&&/^[0-9a-f]{64}$/i.test(e),a=this.client&&(e===this.client.publicKey||!i),o=r.capabilityToken||r.capability;if(a){if(o){if(!(await this.verifyCapability(o,"write",{holonId:e,lensName:t,dataId:n})))throw new AuthorizationError("AuthorizationError: Invalid capability token for update operation","write")}}else{if(!o)throw this._log("WARN","🚫 Update denied: No capability token for federated holon",{holonId:e,lensName:t,dataId:n}),new AuthorizationError("Capability token required for writing to federated holons","write");if(!(await this.verifyCapability(o,"write",{holonId:e,lensName:t,dataId:n})))throw this._log("WARN","🚫 Update denied: Invalid capability token",{holonId:e,lensName:t,dataId:n}),new AuthorizationError("Invalid capability token for update operation","write")}const l=buildPath(this.config.appName,e,t,n),c=this._writeCache.get(l),u=c?c.data:await read(this.client,l),d=c?"write-cache":"storage";if(!u)return this._log("DEBUG","✏️ UPDATE: Data not found",{path:l,dataId:n}),!1;if(this._log("DEBUG","✏️ UPDATE: Found data",{path:l,dataId:n,source:d}),!0===u.hologram&&u.target)return this._log("DEBUG","🔗 Updating hologram",{path:l}),this.write(e,t,{...u,...s,id:n},r);const f={...u,...s};if(f._meta=f._meta||{},f._meta.updatedAt=Date.now(),!1!==r.validate&&this.schemas.has(t)){const e=this.schemas.get(t),n=void 0!==r.strict?r.strict:e.strict;e.schema&&"object"==typeof e.schema&&!e.schema.$ref&&validate(f,e.schema,t,n)}this._writeCache.set(l,{data:{...f},timestamp:Date.now()}),this._deleteCache.delete(l),this._log("DEBUG","✏️ CACHE UPDATE",{path:l,dataId:n,updatedFields:Object.keys(s),cacheSize:this._writeCache.size,mode:r.blocking?"blocking":"optimistic"});const h=this._syncUpdateToRelay(e,t,n,f,u,l);return!r.blocking||(this._log("DEBUG","⏳ BLOCKING: Waiting for update confirmation",{path:l}),h)}async _syncUpdateToRelay(e,t,n,s,r,i){const a=Date.now();this._log("DEBUG","🔄 UPDATE SYNC START",{path:i,dataId:n,relays:this.client?.relays?.map(e=>e.url)||["local-only"]});try{await write(this.client,i,s);const o=Date.now()-a;return this._metrics.writes++,this._metrics.totalWriteTime||(this._metrics.totalWriteTime=0),this._metrics.totalWriteTime+=o,this._log("DEBUG","✅ UPDATE SYNC SUCCESS",{path:i,dataId:n,duration:`${o}ms`,totalWrites:this._metrics.writes}),r._meta&&r._meta.activeHolograms&&(this._log("DEBUG","🔗 Refreshing active holograms",{path:i}),await refreshActiveHolograms(this.client,this.config.appName,e,t,n).catch(e=>this._log("WARN","⚠️ Hologram refresh failed",{path:i,error:e.message}))),!0}catch(o){const e=Date.now()-a;return this._log("ERROR","❌ UPDATE SYNC FAILED",{path:i,dataId:n,duration:`${e}ms`,error:o.message,stack:o.stack?.split("\n")[1]?.trim()}),this._log("WARN","💾 Data retained in write cache for retry",{path:i,cacheSize:this._writeCache.size}),!1}}async delete(e,t,n,s={}){if(null!=e&&(e=String(e)),null!=t&&(t=String(t)),null!=n&&(n=String(n)),!e)throw new ValidationError$1("ValidationError: holonId must be a non-empty string");if(!t)throw new ValidationError$1("ValidationError: lensName must be a non-empty string");if(!n)throw new ValidationError$1("ValidationError: dataId must be a non-empty string");const r="string"==typeof e&&/^[0-9a-f]{64}$/i.test(e);let i=this.client?.publicKey;if(s.signingKey)try{i=getPublicKey(s.signingKey)}catch(g){this._log("WARN","⚠️ Invalid signingKey in delete, using client key",{error:g.message})}const a=i&&(e===i||!r),o=s.capabilityToken||s.capability;if(!a&&!o)throw this._log("WARN","🚫 Delete denied: No capability token for federated holon",{holonId:e,lensName:t,dataId:n}),new AuthorizationError("Capability token required for writing to federated holons","delete");const l=buildPath(this.config.appName,e,t,n),c=this._writeCache.get(l);let u=c?c.data:null,d=c?"write-cache":null;if(!u){const e={};i&&i!==this.client?.publicKey&&(e.authors=[i]),u=await read(this.client,l,e),d=u?"storage":null}if(!u)return this._log("DEBUG","🗑️ DELETE: Data not found",{path:l}),!1;this._log("DEBUG","🗑️ DELETE: Found data",{path:l,source:d});const f=u.owner||u._creator;if(!f||f===this.client.publicKey||f===i){if(o){if(!(await this.verifyCapability(o,"delete",{holonId:e,lensName:t,dataId:n})))throw new AuthorizationError("AuthorizationError: Invalid capability token for delete operation","delete")}}else{if(!o)throw new AuthorizationError("AuthorizationError: Capability token required for delete operation","delete");if(!(await this.verifyCapability(o,"delete",{holonId:e,lensName:t,dataId:n})))throw new AuthorizationError("AuthorizationError: Invalid capability token for delete operation","delete")}if(this._writeCache.delete(l),this._deleteCache.add(l),this._log("DEBUG","🗑️ CACHE DELETE",{path:l,dataId:n,deleteCacheSize:this._deleteCache.size,writeCacheSize:this._writeCache.size,mode:s.blocking?"blocking":"optimistic"}),!0===u.hologram)return this._log("DEBUG","🔗 Deleting hologram",{path:l}),this.deleteHologram(e,t,n,s);const h=Date.now();this._log("DEBUG","🔄 DELETE SYNC START",{path:l,dataId:n});const p={};if(s.signingKey){p.signingKey=s.signingKey;try{p.authorPubkey=getPublicKey(s.signingKey)}catch(g){this._log("WARN","⚠️ Invalid signingKey in delete, using client key",{error:g.message})}}const y=deleteData(this.client,l,p).then(()=>{const e=Date.now()-h;return this._metrics.deletes++,this._deleteCache.delete(l),this._log("DEBUG","✅ DELETE SYNC SUCCESS",{path:l,dataId:n,duration:`${e}ms`,totalDeletes:this._metrics.deletes,deleteCacheSize:this._deleteCache.size}),!0}).catch(e=>{const t=Date.now()-h;return this._log("ERROR","❌ DELETE SYNC FAILED",{path:l,dataId:n,duration:`${t}ms`,error:e.message}),this._log("WARN","💾 Path retained in delete cache",{path:l,deleteCacheSize:this._deleteCache.size}),!1});return s.blocking?(this._log("DEBUG","⏳ BLOCKING: Waiting for delete confirmation",{path:l}),y):(this._log("DEBUG","⚡ OPTIMISTIC: Returning immediately, delete sync in background",{path:l}),!0)}async writeGlobal(e,t){return null!=e&&(e=String(e)),null!=t?.id&&(t.id=String(t.id)),writeGlobal(this.client,this.config.appName,e,t)}async readGlobal(e,t=null){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),readGlobal(this.client,this.config.appName,e,t)}async updateGlobal(e,t,n){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),updateGlobal(this.client,this.config.appName,e,t,n)}async deleteGlobal(e,t){return null!=e&&(e=String(e)),null!=t&&(t=String(t)),deleteGlobal(this.client,this.config.appName,e,t)}async getAllGlobal(e){return null!=e&&(e=String(e)),getAllGlobal(this.client,this.config.appName,e)}async deleteAllGlobal(e){return null!=e&&(e=String(e)),deleteAllGlobal(this.client,this.config.appName,e)}async getAll(e,t){return this.read(e,t,null)}async deleteAll(e,t,n={}){null!=e&&(e=String(e)),null!=t&&(t=String(t));const s=buildPath(this.config.appName,e,t),r={};if(n.signingKey){r.signingKey=n.signingKey;try{r.authorPubkey=getPublicKey(n.signingKey)}catch(i){this._log("WARN","⚠️ Invalid signingKey in deleteAll, using client key",{error:i.message})}}return deleteAll(this.client,s,r)}async setSchema(e,t,n=!1){if(!e||"string"!=typeof e)throw new ValidationError$1("ValidationError: lensName must be a non-empty string");if(null==t)throw new ValidationError$1("ValidationError: schema cannot be null or undefined");let s;if("string"==typeof t)s={$ref:t};else{if("object"!=typeof t)throw new ValidationError$1("ValidationError: schema must be an object or URI string");if(!(t.$ref||t.type||t.properties||t.items||t.allOf||t.anyOf||t.oneOf||t.$schema))throw new ValidationError$1("ValidationError: Invalid JSON Schema format");s=t}this.schemas.set(e,{schema:s,strict:n,timestamp:Date.now()})}async getSchema(e){const t=this.schemas.get(e);return t?t.schema:null}async clearSchema(e){this.schemas.delete(e)}async _propagateExistingData(e,t,n,s={}){const{mode:r="reference",filter:i=null,sourceAuthorPubKey:a}=s,o=await this.read(e,n,null,{resolveHolograms:!1});if(!o)return;const l=Array.isArray(o)?o:[o];for(const c of l)!0!==c.hologram&&(i&&!i(c)||await propagateData(this.client,this.config.appName,c,e,t,n,r,{sourceAuthorPubKey:a||this.client.publicKey}))}async getFederatedData(e,t,n={}){const{resolveHolograms:s=!0}=n,r=buildPath(this.config.appName,e,t),i=await readAll(this.client,r);return i&&s?this._resolveHolograms(i):i}async updateHologramOverrides(e,t,n,s){return updateHologramOverrides(this.client,this.config.appName,e,t,n,s)}async createHologram(e,t,n,s=null){const r=s||e;return createHologramWithCapability(this.client,e,r,t,n.id,this.config.appName,{sourceAuthorPubKey:this.client.publicKey,targetAuthorPubKey:this.client.publicKey,permissions:["read"]})}async getActiveHolograms(e,t,n){const s=buildPath(this.config.appName,e,t,n),r=await read(this.client,s);return r&&r._meta&&r._meta.activeHolograms?r._meta.activeHolograms:[]}async removeActiveHologram(e,t,n,s){return removeActiveHologram(this.client,this.config.appName,e,t,n,s)}async deleteHologram(e,t,n,s={}){return deleteHologram(this.client,this.config.appName,e,t,n,s)}async propagateData(e,t,n,s,r={}){const i=r.mode||"reference";return propagateData(this.client,this.config.appName,e,t,n,s,i,{sourceAuthorPubKey:r.sourceAuthorPubKey||this.client.publicKey,capability:r.capability})}async resolveHologram(e,t={}){return resolveHologram(this.client,e,new Set,[],{...t,appname:this.config.appName})}isHologram(e){return isHologram(e)}isResolvedHologram(e){return isResolvedHologram(e)}getHologramSource(e){return getHologramSource(e)}async updateHologramPlatform(e,t,n,s,r,i){return updateActiveHologramPlatform(this.client,this.config.appName,e,t,n,s,r,i)}async getActiveHolograms(e,t,n,s=null){return getActiveHolograms(this.client,this.config.appName,e,t,n,s)}async cleanupCircularHolograms(e,t,n={}){return cleanupCircularHolograms(this.client,this.config.appName,e,t,n)}async cleanupCircularHologramsByIds(e,t,n,s={}){return cleanupCircularHologramsByIds(this.client,this.config.appName,e,t,n,s)}async propagate(e,t,n,s={}){const r=await this.getFederation(e),i=r?.federated||r?.outbound||[];if(!i||0===i.length)return;const{useHolograms:a=!0,resolveExisting:o=!0}=s,l=[];for(const c of i){const s=await this.propagateData(n,e,c,t,{useHolograms:a,resolveExisting:o});l.push({parent:c,...s})}return l}async getFederation(e){if(!e)throw new Error("getFederation: Missing holon ID");const t=await this.readGlobal("federation",e);if(!t)return null;if(Array.isArray(t.inbound)||(t.inbound=[]),Array.isArray(t.outbound)||(t.outbound=[]),t.lensConfig&&"object"==typeof t.lensConfig||(t.lensConfig={}),t.partnerNames&&"object"==typeof t.partnerNames||(t.partnerNames={}),!Array.isArray(t.federated)){const e=new Set([...t.inbound,...t.outbound]);t.federated=Array.from(e)}return t}async federateHolon(e,t,n={}){const{lensConfig:s={inbound:[],outbound:[]},partnerName:r=null,skipPropagation:i=!1}=n;if(e===t)throw new Error("Cannot federate a holon with itself");let a=await this.readGlobal("federation",e)||{id:e,name:e,federated:[],inbound:[],outbound:[],lensConfig:{},partnerNames:{},timestamp:Date.now()};Array.isArray(a.federated)||(a.federated=[]),Array.isArray(a.inbound)||(a.inbound=[]),Array.isArray(a.outbound)||(a.outbound=[]),a.lensConfig&&"object"==typeof a.lensConfig||(a.lensConfig={}),a.partnerNames&&"object"==typeof a.partnerNames||(a.partnerNames={}),a.federated.includes(t)||a.federated.push(t),r&&(a.partnerNames[t]=r),s.outbound&&s.outbound.length>0?a.outbound.includes(t)||a.outbound.push(t):a.outbound=a.outbound.filter(e=>e!==t),s.inbound&&s.inbound.length>0?a.inbound.includes(t)||a.inbound.push(t):a.inbound=a.inbound.filter(e=>e!==t),a.lensConfig[t]={inbound:s.inbound||[],outbound:s.outbound||[],writeInbound:s.writeInbound||[],writeOutbound:s.writeOutbound||[],timestamp:Date.now()};const o=await this.writeGlobal("federation",a);if(this.clearCache("federation"),o&&!i){for(const n of s.inbound||[])await this.federate(t,e,n,{direction:"outbound",mode:"reference"});for(const n of s.outbound||[])await this.federate(e,t,n,{direction:"outbound",mode:"reference"})}return o}async unfederateHolon(e,t){const n=await this.readGlobal("federation",e);if(!n)return!1;const s=n.lensConfig?.[t];n.federated=(n.federated||[]).filter(e=>e!==t),n.inbound=(n.inbound||[]).filter(e=>e!==t),n.outbound=(n.outbound||[]).filter(e=>e!==t),n.lensConfig&&delete n.lensConfig[t];const r=await this.writeGlobal("federation",n);if(this.clearCache("federation"),r&&s){for(const n of s.inbound||[])await this.unfederate(t,e,n);for(const n of s.outbound||[])await this.unfederate(e,t,n)}return r}async getFederatedConfig(e,t){const n=await this.readGlobal("federation",e);return n&&n.lensConfig&&n.lensConfig[t]||null}async upcast(e,t,n,s={}){return upcast(this,e,t,n,s)}subscribe(e,t,n,s={}){if("function"!=typeof n)throw new TypeError("callback must be a function");const r=buildPath(this.config.appName,e,t),i={realtimeOnly:!0,appname:this.config.appName,...s},a=`${e}-${t}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;let o=null,l=!1;return(async()=>{try{const u="string"==typeof e&&/^[0-9a-f]{64}$/i.test(e)&&e!==this.client.publicKey;if(u){const n=s.capabilityToken||s.capability;if(n){if(!(await this.verifyCapability(n,"read",{holonId:e,lensName:t})))return void this._log("WARN","❌ Subscribe: invalid capability token - skipping",{holonId:e,lensName:t})}else{if(!(await this._getCapabilityForAuthor(e,{holonId:e,lensName:t})))return void this._log("WARN","❌ Subscribe: no capability for federated author - skipping",{holonId:e,lensName:t,targetPubkey:e?.slice(0,12)+"..."});this._log("DEBUG","✅ Subscribe: capability found for federated author",{holonId:e,lensName:t,targetPubkey:e?.slice(0,12)+"..."})}}if(l)return;i.authors=[this.client.publicKey];const d=await createSubscription(this.client,r,n,i);if(o=d,l)return void d.unsubscribe();if(this.subscriptionRegistry.register(a,d),!u)try{const e=getFederatedAuthors(this.client,this.config.appName),t=new Promise(e=>setTimeout(()=>e([]),1e3)),n=await Promise.race([e,t]);n.length>0&&this._log("DEBUG","Subscribe: federated authors found post-setup",{count:n.length})}catch(c){this._log("WARN","Failed to get federated authors for subscription",{error:c.message})}}catch(c){this._log("ERROR","Subscription setup failed",{path:r,error:c.message})}})(),this._metrics.subscriptions=(this._metrics.subscriptions||0)+1,{unsubscribe:()=>{l=!0,o&&this.subscriptionRegistry.unregister(a)}}}async subscribeGlobal(e,t,n,s={}){return subscribeGlobal(this.client,this.config.appName,e,t,n,s)}async getPublicKey(e){return getPublicKey(e)}async sign(e,t){return sign(e,t)}async verify(e,t,n){return verify(e,t,n)}async issueCapability(e,t,n,s){return issueCapability$1(e,t,n,s)}async verifyCapability(e,t,n){return verifyCapability$1(e,t,n)}async publishNostr(e,t,n="social"){validateNostrEvent(e,!0,!0);const s=signEvent({...e,tags:[...e.tags||[],["h",t],["l",n]]},this.client.privateKey),r={...s,protocol:"nostr"},i=buildPath(this.config.appName,t,n,s.id);return await write(this.client,i,r),!0}async publishActivityPub(e,t,n="social"){validateActivityPubObject(e,!0);const s=transformActivityPubObject({...e,actor:e.actor||this.client.publicKey});return this.write(t,n,s)}async querySocial(e,t={}){const n=t.lens||"social",s=await this.read(e,n);if(!s)return[];return(Array.isArray(s)?s:[s]).filter(e=>(!t.protocol||"all"===t.protocol||e.protocol===t.protocol)&&((!t.type||e.type===t.type)&&(!(t.since&&e.created_at<t.since)&&!(t.until&&e.created_at>t.until))))}async verifyNostrEvent(e){const{id:t,pubkey:n,created_at:s,kind:r,tags:i,content:a,sig:o}=e;return verifyEvent({id:t,pubkey:n,created_at:s,kind:r,tags:i,content:a,sig:o})}metrics(){const e=this._metrics.reads||0,t=this._metrics.writes||0,n=this._metrics.totalReadTime||0,s=this._metrics.totalWriteTime||0;return{reads:e,writes:t,deletes:this._metrics.deletes||0,federations:this._metrics.federations||0,subscriptions:this._metrics.subscriptions||0,avgReadTime:e>0?n/e:0,avgWriteTime:t>0?s/t:0}}getCacheStatus(){const e=Date.now(),t=[];for(const[n,s]of this._writeCache.entries())t.push({path:n,dataId:s.data?.id,age:e-s.timestamp+"ms",timestamp:new Date(s.timestamp).toISOString()});return{writeCacheSize:this._writeCache.size,deleteCacheSize:this._deleteCache.size,writeCacheEntries:t,deleteCachePaths:Array.from(this._deleteCache)}}clearCaches(){const e=this._writeCache.size,t=this._deleteCache.size;this._writeCache.clear(),this._deleteCache.clear(),this._log("WARN","🧹 CACHES CLEARED",{writeCacheCleared:e,deleteCacheCleared:t})}async put(e,t,n,s={}){return this.write(e,t,n,s)}async get(e,t,n=null,s={}){return this.read(e,t,n,s)}async remove(e,t,n,s={}){return this.delete(e,t,n,s)}async putGlobal(e,t){return this.writeGlobal(e,t)}async getGlobal(e,t=null){return this.readGlobal(e,t)}async removeGlobal(e,t){return this.deleteGlobal(e,t)}async defineSchema(e,t,n=!1){return this.setSchema(e,t,n)}async fetchSchema(e){return this.getSchema(e)}async removeSchema(e){return this.clearSchema(e)}async store(e,t,n,s={}){return this.write(e,t,n,s)}async fetch(e,t,n=null,s={}){return this.read(e,t,n,s)}async save(e,t,n,s={}){return this.write(e,t,n,s)}async load(e,t,n=null,s={}){return this.read(e,t,n,s)}clearCache(e=null){if(e)for(const t of this._cache.keys())t.includes(e)&&this._cache.delete(t);else this._cache.clear()}}const HoloSphere=withContractMethods(withFederationMethods(withAIMethods(HoloSphereBase)));exports.ABIs=ABIs,exports.AbiCoder=AbiCoder,exports.AuthorizationError=AuthorizationError,exports.BaseContract=BaseContract,exports.Block=Block,exports.ChainManager=ChainManager,exports.Classifier=Classifier,exports.ConstructorFragment=ConstructorFragment,exports.Contract=Contract,exports.ContractDeployer=ContractDeployer,exports.ContractEventPayload=ContractEventPayload,exports.ContractOperations=ContractOperations,exports.ContractQueries=ContractQueries,exports.ContractTransactionReceipt=ContractTransactionReceipt,exports.ContractTransactionResponse=ContractTransactionResponse,exports.ContractUnknownEventPayload=ContractUnknownEventPayload,exports.Council=Council,exports.Embeddings=Embeddings,exports.ErrorDescription=ErrorDescription,exports.ErrorFragment=ErrorFragment,exports.EventFragment=EventFragment,exports.EventListener=EventListener,exports.EventLog=EventLog,exports.EventPayload=EventPayload,exports.FallbackFragment=FallbackFragment,exports.FederationAdvisor=FederationAdvisor,exports.FeeData=FeeData,exports.FixedNumber=FixedNumber,exports.Fragment=Fragment,exports.FunctionFragment=FunctionFragment,exports.H3AI=H3AI,exports.Hash=Hash,exports.HoloSphere=HoloSphere,exports.HolonContracts=HolonContracts,exports.Indexed=Indexed,exports.Interface=Interface,exports.JSONOps=JSONOps,exports.LLMService=LLMService,exports.LensKeyStore=LensKeyStore,exports.Log=Log,exports.LogDescription=LogDescription,exports.MODELS=MODELS,exports.NETWORKS=NETWORKS,exports.NLQuery=NLQuery,exports.NamedFragment=NamedFragment,exports.ParamType=ParamType,exports.PersistentStorage=PersistentStorage,exports.RelationshipDiscovery=RelationshipDiscovery,exports.Result=Result,exports.SANKEY_EVENTS=SANKEY_EVENTS,exports.SchemaExtractor=SchemaExtractor,exports.SmartAggregation=SmartAggregation,exports.SpatialAnalysis=SpatialAnalysis,exports.StructFragment=StructFragment,exports.TTS=TTS,exports.TaskBreakdown=TaskBreakdown,exports.TransactionDescription=TransactionDescription,exports.TransactionReceipt=TransactionReceipt,exports.TransactionResponse=TransactionResponse,exports.Typed=Typed,exports.UndecodedEventLog=UndecodedEventLog,exports.Utf8ErrorFuncs=Utf8ErrorFuncs,exports.VOICES=VOICES,exports.ValidationError=ValidationError$1,exports.ZeroAddress=ZeroAddress,exports.accessListify=accessListify,exports.assert=assert,exports.assertArgument=assertArgument,exports.assertArgumentCount=assertArgumentCount,exports.assertNormalize=assertNormalize,exports.assertPrivate=assertPrivate,exports.asyncLoop=asyncLoop,exports.buildLensPath=buildLensPath,exports.bytes=bytes,exports.bytesToHex=bytesToHex$1,exports.capabilities=capabilities$1,exports.cardStorage=cardStorage$1,exports.checkOpts=checkOpts,exports.checkResultErrors=checkResultErrors,exports.commonjsGlobal=commonjsGlobal,exports.concat=concat,exports.concatBytes=concatBytes,exports.concatBytes$1=concatBytes$1,exports.copyOverrides=copyOverrides,exports.copyRequest=copyRequest,exports.createAIServices=createAIServices,exports.createDebug2=createDebug2,exports.createFederationCard=createFederationCard,exports.createHologram=createHologram,exports.createView=createView,exports.dataLength=dataLength,exports.dataSlice=dataSlice,exports.defineProperties=defineProperties,exports.dismissCard=dismissCard$1,exports.dismissRequest=dismissRequest,exports.dist=dist,exports.exists=exists,exports.formatEther=formatEther,exports.formatUnits=formatUnits,exports.fromTwos=fromTwos,exports.getAddress=getAddress,exports.getAddressUrl=getAddressUrl,exports.getBigInt=getBigInt,exports.getBytes=getBytes,exports.getBytesCopy=getBytesCopy,exports.getCard=getCard,exports.getDefaultExportFromCjs=getDefaultExportFromCjs,exports.getDisplayableCards=getDisplayableCards,exports.getIcapAddress=getIcapAddress,exports.getLensConfigForHandshake=getLensConfigForHandshake,exports.getNetwork=getNetwork,exports.getNetworksByType=getNetworksByType,exports.getNumber=getNumber,exports.getTxUrl=getTxUrl,exports.getUint=getUint,exports.getVisibleLenses=getVisibleLenses,exports.h3Operations=h3Operations,exports.handshake=handshake,exports.hash=hash,exports.hexToBytes=hexToBytes$1,exports.hexlify=hexlify,exports.hologram=hologram,exports.holonRegistry=holonRegistry,exports.id=id,exports.isAddress=isAddress,exports.isAddressable=isAddressable,exports.isBytesLike=isBytesLike,exports.isCallException=isCallException,exports.isError=isError,exports.isHexString=isHexString,exports.isNetworkSupported=isNetworkSupported,exports.isResponseProcessed=isResponseProcessed,exports.keccak256=keccak256,exports.lensKeys=lensKeys,exports.lib=lib,exports.lib$1=lib$1,exports.listNetworks=listNetworks,exports.makeError=makeError,exports.manager=manager,exports.markResponseProcessed=markResponseProcessed,exports.mask=mask,exports.matchScope=matchScope,exports.networks=networks,exports.nostrUtils=nostrUtils,exports.number=number,exports.output=output,exports.parseEther=parseEther,exports.parseLensPath=parseLensPath,exports.parseUnits=parseUnits,exports.randomBytes=randomBytes,exports.registry=registry,exports.requestCard=requestCard$1,exports.resolveAddress=resolveAddress,exports.resolveArgs=resolveArgs,exports.resolveProperties=resolveProperties,exports.rotr=rotr,exports.saveCard=saveCard,exports.secp256k1=secp256k1,exports.socialProtocols=socialProtocols,exports.stripZerosLeft=stripZerosLeft,exports.toBeArray=toBeArray,exports.toBeHex=toBeHex,exports.toBigInt=toBigInt,exports.toBytes=toBytes,exports.toNumber=toNumber,exports.toQuantity=toQuantity,exports.toTwos=toTwos,exports.toUtf8Bytes=toUtf8Bytes,exports.toUtf8CodePoints=toUtf8CodePoints,exports.toUtf8String=toUtf8String,exports.toggleCardExpansion=toggleCardExpansion,exports.toggleLens=toggleLens,exports.u32=u32,exports.u64=u64,exports.unifiedStorage=unifiedStorage,exports.upcast=upcast$1,exports.validator=validator,exports.version=version,exports.wrapConstructor=wrapConstructor,exports.zeroPadBytes=zeroPadBytes,exports.zeroPadValue=zeroPadValue;
29
- //# sourceMappingURL=index-CDlhzxT2.cjs.map