From f25e2409e9238949322b75763357247521405706 Mon Sep 17 00:00:00 2001 From: hzrd149 Date: Fri, 4 Oct 2024 10:32:57 -0500 Subject: [PATCH] Add screenshots for nsites --- .changeset/stupid-poems-approve.md | 5 + .gitignore | 1 + .vscode/launch.json | 3 +- Dockerfile | 2 + docker-compose.yml | 5 + package.json | 3 + pnpm-lock.yaml | 522 +++- public/components/nsite-card.js | 100 + public/index.html | 29 +- public/lib/lit.min.js | 29 + public/lib/nostr-name.js | 4034 --------------------------- public/lib/nostr-picture.js | 4050 ---------------------------- public/main.js | 75 +- public/pool.js | 4 + src/env.ts | 15 +- src/index.ts | 54 +- src/screenshots.ts | 40 + 17 files changed, 809 insertions(+), 8162 deletions(-) create mode 100644 .changeset/stupid-poems-approve.md create mode 100644 public/components/nsite-card.js create mode 100644 public/lib/lit.min.js delete mode 100644 public/lib/nostr-name.js delete mode 100644 public/lib/nostr-picture.js create mode 100644 public/pool.js create mode 100644 src/screenshots.ts diff --git a/.changeset/stupid-poems-approve.md b/.changeset/stupid-poems-approve.md new file mode 100644 index 0000000..28acb7e --- /dev/null +++ b/.changeset/stupid-poems-approve.md @@ -0,0 +1,5 @@ +--- +"nsite-ts": minor +--- + +Add screenshots for nsites diff --git a/.gitignore b/.gitignore index 34aea21..25bbe27 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ build .env data .netrc +screenshots diff --git a/.vscode/launch.json b/.vscode/launch.json index 9bb2bc8..4f2970d 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -26,8 +26,7 @@ "internalConsoleOptions": "openOnSessionStart", "outputCapture": "std", "env": { - "DEBUG": "nsite,nsite:*", - "ALL_PROXY": "pac+file://proxy.pac" + "DEBUG": "nsite,nsite:*" } } ] diff --git a/Dockerfile b/Dockerfile index 1076cd0..daa932f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -39,10 +39,12 @@ COPY ./public ./public COPY tor-and-i2p.pac proxy.pac VOLUME [ "/var/cache/nginx" ] +VOLUME [ "/screenshots" ] EXPOSE 80 3000 ENV NSITE_PORT="3000" ENV NGINX_CACHE_DIR="/var/cache/nginx" +ENV SCREENSHOTS_DIR="/screenshots" COPY docker-entrypoint.sh / RUN chmod +x /docker-entrypoint.sh diff --git a/docker-compose.yml b/docker-compose.yml index 219a8db..89bae93 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,6 @@ version: "3.7" + services: nsite: build: . @@ -8,6 +9,10 @@ services: LOOKUP_RELAYS: wss://user.kindpag.es,wss://purplepag.es SUBSCRIPTION_RELAYS: wss://nostrue.com/,wss://nos.lol/,wss://relay.damus.io/,wss://purplerelay.com/ volumes: + - type: tmpfs + target: /screenshots + tmpfs: + size: 100M - type: tmpfs target: /var/cache/nginx tmpfs: diff --git a/package.json b/package.json index b78deda..118b0d9 100644 --- a/package.json +++ b/package.json @@ -27,11 +27,13 @@ "keyv": "^5.0.1", "koa": "^2.15.3", "koa-morgan": "^1.0.1", + "koa-send": "^5.0.1", "koa-static": "^5.0.0", "mime": "^4.0.4", "nostr-tools": "^2.7.2", "pac-proxy-agent": "^7.0.2", "proxy-agent": "^6.4.0", + "puppeteer": "^23.5.0", "websocket-polyfill": "^1.0.0", "ws": "^8.18.0", "xbytes": "^1.9.1" @@ -44,6 +46,7 @@ "@types/follow-redirects": "^1.14.4", "@types/koa": "^2.14.0", "@types/koa-morgan": "^1.0.8", + "@types/koa-send": "^4.1.6", "@types/koa-static": "^4.0.4", "@types/koa__cors": "^5.0.0", "@types/koa__router": "^12.0.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2c0e9cd..91869ff 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,6 +38,9 @@ importers: koa-morgan: specifier: ^1.0.1 version: 1.0.1 + koa-send: + specifier: ^5.0.1 + version: 5.0.1 koa-static: specifier: ^5.0.0 version: 5.0.0 @@ -53,6 +56,9 @@ importers: proxy-agent: specifier: ^6.4.0 version: 6.4.0 + puppeteer: + specifier: ^23.5.0 + version: 23.5.0(typescript@5.6.2) websocket-polyfill: specifier: 1.0.0 version: 1.0.0 @@ -84,6 +90,9 @@ importers: '@types/koa-morgan': specifier: ^1.0.8 version: 1.0.8 + '@types/koa-send': + specifier: ^4.1.6 + version: 4.1.6 '@types/koa-static': specifier: ^4.0.4 version: 4.0.4 @@ -114,6 +123,18 @@ importers: packages: + '@babel/code-frame@7.25.7': + resolution: {integrity: sha512-0xZJFNE5XMpENsgfHYTw8FbX4kv53mFLn2i3XPoq69LyhYSCBJtitaHx9QnsVTrsogI4Z3+HtEfZ2/GFPOtf5g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.25.7': + resolution: {integrity: sha512-AM6TzwYqGChO45oiuPqwL2t20/HdMC1rTPAesnBCgPCSF1x3oN9MVUwQV2iyz4xqWrctwK5RNC8LV22kaQCNYg==} + engines: {node: '>=6.9.0'} + + '@babel/highlight@7.25.7': + resolution: {integrity: sha512-iYyACpW3iW8Fw+ZybQK+drQre+ns/tKpXbNESfrhNnPLIklLbXr7MYJ6gPEd0iETGLOK+SxMjVvKb/ffmk+FEw==} + engines: {node: '>=6.9.0'} + '@babel/runtime@7.25.6': resolution: {integrity: sha512-VBj9MYyDb9tuLq7yzqjgzt6Q+IBQLrGZfdjOekyEirZPHxXWoTSGUTMrpsfi58Up73d13NfYLv8HT9vmznjzhQ==} engines: {node: '>=6.9.0'} @@ -308,6 +329,11 @@ packages: cpu: [x64] os: [win32] + '@puppeteer/browsers@2.4.0': + resolution: {integrity: sha512-x8J1csfIygOwf6D6qUAZ0ASk3z63zPb7wkNeHRerCMh82qWKUrOgkuP005AJC8lDL6/evtXETGEJVcwykKT4/g==} + engines: {node: '>=18'} + hasBin: true + '@scure/base@1.1.1': resolution: {integrity: sha512-ZxOhsSyxYwLJj3pLZCefNitxsj093tb2vq90mp2txoYeBqbcjDjqFhyM8eUjq/uFm6zJ+mUuqxlS2FkuSY1MTA==} @@ -508,6 +534,9 @@ packages: '@types/ws@8.5.12': resolution: {integrity: sha512-3tPRkv1EtkDpzlgyKyI8pGsGZAGPEaXeu0DOj5DI25Ja91bdAYddYHbADRYVrZMRbfW+1l5YwXVDKohDJNQxkQ==} + '@types/yauzl@2.10.3': + resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==} + abbrev@1.1.1: resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==} @@ -539,6 +568,14 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} + ansi-styles@3.2.1: + resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==} + engines: {node: '>=4'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + anymatch@3.1.3: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} @@ -554,6 +591,9 @@ packages: argparse@1.0.10: resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==} + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + array-union@2.1.0: resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} engines: {node: '>=8'} @@ -562,9 +602,27 @@ packages: resolution: {integrity: sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==} engines: {node: '>=4'} + b4a@1.6.7: + resolution: {integrity: sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg==} + balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + bare-events@2.5.0: + resolution: {integrity: sha512-/E8dDe9dsbLyh2qrZ64PEPadOQ0F4gbl1sUJOrmph7xOiIxfY8vwab/4bFLh4Y88/Hk/ujKcrQKc+ps0mv873A==} + + bare-fs@2.3.5: + resolution: {integrity: sha512-SlE9eTxifPDJrT6YgemQ1WGFleevzwY+XAP1Xqgl56HtcrisC2CHCZ2tq6dBpcH2TnNxwUEUGhweo+lrQtYuiw==} + + bare-os@2.4.4: + resolution: {integrity: sha512-z3UiI2yi1mK0sXeRdc4O1Kk8aOa/e+FNWZcTiPB/dfTWyLypuE99LibgRaQki914Jq//yAWylcAt+mknKdixRQ==} + + bare-path@2.1.3: + resolution: {integrity: sha512-lh/eITfU8hrj9Ru5quUp0Io1kJWIk1bTjzo7JH1P5dWmQ2EL4hFUlfI8FonAhSlgIfhn63p84CDY/x+PisgcXA==} + + bare-stream@2.3.0: + resolution: {integrity: sha512-pVRWciewGUeCyKEuRxwv06M079r+fRjAQjBEK2P6OYGrO43O+Z0LrPZZEjlc4mB6C2RpZ9AxJ1s7NLEtOHO6eA==} + base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -601,6 +659,9 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + buffer-crc32@0.2.13: + resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} + buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} @@ -618,6 +679,14 @@ packages: resolution: {integrity: sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==} engines: {node: '>= 6.0.0'} + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + + chalk@2.4.2: + resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==} + engines: {node: '>=4'} + chardet@0.7.0: resolution: {integrity: sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==} @@ -632,6 +701,11 @@ packages: resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==} engines: {node: '>=10'} + chromium-bidi@0.8.0: + resolution: {integrity: sha512-uJydbGdTw0DEUjhoogGveneJVWX/9YuqkWePzMmkBYwtdAqo5d3J/ovNKFr+/2hWXYmYCr6it8mSSTIj6SS6Ug==} + peerDependencies: + devtools-protocol: '*' + ci-info@3.9.0: resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} engines: {node: '>=8'} @@ -640,6 +714,10 @@ packages: resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==} engines: {node: '>=6'} + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + cluster-key-slot@1.1.2: resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==} engines: {node: '>=0.10.0'} @@ -648,6 +726,19 @@ packages: resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==} engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'} + color-convert@1.9.3: + resolution: {integrity: sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.3: + resolution: {integrity: sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + color-support@1.1.3: resolution: {integrity: sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==} hasBin: true @@ -673,6 +764,15 @@ packages: resolution: {integrity: sha512-TG2hpqe4ELx54QER/S3HQ9SRVnQnGBtKUz5bLQWtYAQ+o6GpgMs6sYUvaiJjVxb+UXwhRhAEP3m7LbsIZ77Hmw==} engines: {node: '>= 0.8'} + cosmiconfig@9.0.0: + resolution: {integrity: sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg==} + engines: {node: '>=14'} + peerDependencies: + typescript: '>=4.9.5' + peerDependenciesMeta: + typescript: + optional: true + cross-spawn@5.1.0: resolution: {integrity: sha512-pTgQJ5KC0d2hcY8eyL1IzlBPYjTkyH72XRZPnLyKus2mBfNjQs3klqbJU2VILqZryAZUt9JOb3h/mWMy23/f5A==} @@ -747,6 +847,9 @@ packages: resolution: {integrity: sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==} engines: {node: '>=8'} + devtools-protocol@0.0.1342118: + resolution: {integrity: sha512-75fMas7PkYNDTmDyb6PRJCH7ILmHLp+BhrZGeMsa4bCh40DTxgCz2NRy5UDzII4C5KuD0oBMZ9vXKhEl6UD/3w==} + dir-glob@3.0.1: resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} engines: {node: '>=8'} @@ -782,9 +885,20 @@ packages: err-code@2.0.3: resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==} + error-ex@1.3.2: + resolution: {integrity: sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==} + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + escape-html@1.0.3: resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} + escape-string-regexp@1.0.5: + resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==} + engines: {node: '>=0.8.0'} + escodegen@2.1.0: resolution: {integrity: sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==} engines: {node: '>=6.0'} @@ -814,6 +928,14 @@ packages: resolution: {integrity: sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==} engines: {node: '>=4'} + extract-zip@2.0.1: + resolution: {integrity: sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==} + engines: {node: '>= 10.17.0'} + hasBin: true + + fast-fifo@1.3.2: + resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==} + fast-glob@3.3.2: resolution: {integrity: sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==} engines: {node: '>=8.6.0'} @@ -821,6 +943,9 @@ packages: fastq@1.17.1: resolution: {integrity: sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==} + fd-slicer@1.1.0: + resolution: {integrity: sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==} + file-uri-to-path@1.0.0: resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} @@ -877,6 +1002,14 @@ packages: engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} deprecated: This package is no longer supported. + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + get-stream@5.2.0: + resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==} + engines: {node: '>=8'} + get-uri@6.0.3: resolution: {integrity: sha512-BzUrJBS9EcUb4cFol8r4W3v1cPsSyajLSthNkz5BxbpDcHN5tIrM10E2eNvfnvBn3DaT3DUgx0OpsBKkaOpanw==} engines: {node: '>= 14'} @@ -969,6 +1102,10 @@ packages: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} + import-fresh@3.3.0: + resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==} + engines: {node: '>=6'} + import2@1.0.3: resolution: {integrity: sha512-X7KHNp1fovFaiah9Q+njdxXJKIV9/XippWGZwHL9ZdJYnQPBs+4wLd4PuCigbxz2IWNm5YvFycSjRA/1lgmdGw==} @@ -1004,6 +1141,9 @@ packages: resolution: {integrity: sha512-zHtQzGojZXTwZTHQqra+ETKd4Sn3vgi7uBmlPoXVWZqYvuKmtI0l/VZTjqGmJY9x88GGOaZ9+G9ES8hC4T4X8g==} engines: {node: '>= 12'} + is-arrayish@0.2.1: + resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} + is-binary-path@2.1.0: resolution: {integrity: sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==} engines: {node: '>=8'} @@ -1042,13 +1182,23 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + js-yaml@3.14.1: resolution: {integrity: sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==} hasBin: true + js-yaml@4.1.0: + resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} + hasBin: true + jsbn@1.1.0: resolution: {integrity: sha512-4bYVV3aAMtDTTu4+xsDYa6sy9GyJ69/amsu9sYF2zqjiEoZA5xJi3BrfX3uY+/IekIu7MwdObdbDWpoZdBv3/A==} + json-parse-even-better-errors@2.3.1: + resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} + jsonfile@4.0.0: resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} @@ -1084,6 +1234,9 @@ packages: resolution: {integrity: sha512-j/8tY9j5t+GVMLeioLaxweJiKUayFhlGqNTzf2ZGwL0ZCQijd2RLHK0SLW5Tsko8YyyqCZC2cojIb0/s62qTAg==} engines: {node: ^4.8.4 || ^6.10.1 || ^7.10.1 || >= 8.1.4} + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + locate-path@5.0.0: resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} engines: {node: '>=8'} @@ -1179,6 +1332,9 @@ packages: resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==} engines: {node: '>= 8'} + mitt@3.0.1: + resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} + mkdirp-classic@0.5.3: resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} @@ -1317,6 +1473,14 @@ packages: package-manager-detector@0.2.0: resolution: {integrity: sha512-E385OSk9qDcXhcM9LNSe4sdhx8a9mAPrZ4sMLW+tmxl5ZuGtPUcdFu+MPP2jbgiWAZ6Pfe5soGFMd+0Db5Vrog==} + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + + parse-json@5.2.0: + resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} + engines: {node: '>=8'} + parseurl@1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} @@ -1333,6 +1497,9 @@ packages: resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} engines: {node: '>=8'} + pend@1.2.0: + resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==} + picocolors@1.1.0: resolution: {integrity: sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==} @@ -1363,6 +1530,10 @@ packages: engines: {node: '>=14'} hasBin: true + progress@2.0.3: + resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} + engines: {node: '>=0.4.0'} + promise-inflight@1.0.1: resolution: {integrity: sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==} peerDependencies: @@ -1391,9 +1562,21 @@ packages: pump@3.0.2: resolution: {integrity: sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw==} + puppeteer-core@23.5.0: + resolution: {integrity: sha512-+5ed+625GuQ2emRHqYec8khT9LP14FWzv8hYl0HiM6hnnlNzdVU9uDJIPHeCPLIWxq15ost9MeF8kBk4R3eiFw==} + engines: {node: '>=18'} + + puppeteer@23.5.0: + resolution: {integrity: sha512-jnUx5M0YtFva7vXr39qqsxgB46JiwXJavuM1Hgsqbd9WWiGTEUt9klGpTxyHi+ZQf3NUgleDhNsnI10IK8Ebsg==} + engines: {node: '>=18'} + hasBin: true + queue-microtask@1.2.3: resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + queue-tick@1.0.1: + resolution: {integrity: sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==} + rc@1.2.8: resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} hasBin: true @@ -1421,6 +1604,14 @@ packages: regenerator-runtime@0.14.1: resolution: {integrity: sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==} + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + resolve-from@5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} @@ -1539,6 +1730,9 @@ packages: resolution: {integrity: sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==} engines: {node: '>= 0.6'} + streamx@2.20.1: + resolution: {integrity: sha512-uTa0mU6WUC65iUvzKH4X9hEdvSW7rbPxPtwfWiLMSj3qTdQbAiUboZTxauKfpFuGIGa1C2BYijZ7wgdUXICJhA==} + string-width@4.2.3: resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} engines: {node: '>=8'} @@ -1565,10 +1759,16 @@ packages: tar-fs@2.1.1: resolution: {integrity: sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==} + tar-fs@3.0.6: + resolution: {integrity: sha512-iokBDQQkUyeXhgPYaZxmczGPhnhXZ0CmrqI+MOb/WFGS9DW5wnfrLgtjUJBvz50vQ3qfRwJ62QVoCFu8mPVu5w==} + tar-stream@2.2.0: resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} engines: {node: '>=6'} + tar-stream@3.1.7: + resolution: {integrity: sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==} + tar@6.2.1: resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==} engines: {node: '>=10'} @@ -1577,6 +1777,12 @@ packages: resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==} engines: {node: '>=8'} + text-decoder@1.2.0: + resolution: {integrity: sha512-n1yg1mOj9DNpk3NeZOx7T6jchTbyJS3i3cucbNN6FcdPriMZx7NsgrGpWWdWZZGxD7ES1XB+3uoqHMgOKaN+fg==} + + through@2.3.8: + resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==} + tmp@0.0.33: resolution: {integrity: sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==} engines: {node: '>=0.6.0'} @@ -1610,11 +1816,17 @@ packages: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} + typed-query-selector@2.12.0: + resolution: {integrity: sha512-SbklCd1F0EiZOyPiW192rrHZzZ5sBijB6xM+cpmrwDqObvdtunOHHIk9fCGsoK5JVIYXoyEp4iEdE3upFH3PAg==} + typescript@5.6.2: resolution: {integrity: sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==} engines: {node: '>=14.17'} hasBin: true + unbzip2-stream@1.4.3: + resolution: {integrity: sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==} + undefsafe@2.0.5: resolution: {integrity: sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==} @@ -1635,6 +1847,9 @@ packages: resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==} engines: {node: '>= 10.0.0'} + urlpattern-polyfill@10.0.0: + resolution: {integrity: sha512-H/A06tKD7sS1O1X2SshBVeA5FLycRpjqiBeqGKmBwBDBy28EnRjORxTNe269KSSr5un5qyWi1iL61wLxpd+ZOg==} + util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -1657,6 +1872,10 @@ packages: wide-align@1.1.5: resolution: {integrity: sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==} + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} + engines: {node: '>=10'} + wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} @@ -1676,18 +1895,50 @@ packages: resolution: {integrity: sha512-29E0ygMFWrM5JW2W1ypmezjyR2FOS5aCszdLe620ymSJBoZzL0/RCLJKCoUFu3DfQGhZ/FWykEBp5dfEy6+hjA==} engines: {node: '>=1'} + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + yallist@2.1.2: resolution: {integrity: sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==} yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} + + yargs@17.7.2: + resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==} + engines: {node: '>=12'} + + yauzl@2.10.0: + resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==} + ylru@1.4.0: resolution: {integrity: sha512-2OQsPNEmBCvXuFlIni/a+Rn+R2pHW9INm0BxXJ4hVDA8TirqMj+J/Rp9ItLatT/5pZqWwefVrTQcHpixsxnVlA==} engines: {node: '>= 4.0.0'} + zod@3.23.8: + resolution: {integrity: sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==} + snapshots: + '@babel/code-frame@7.25.7': + dependencies: + '@babel/highlight': 7.25.7 + picocolors: 1.1.0 + + '@babel/helper-validator-identifier@7.25.7': {} + + '@babel/highlight@7.25.7': + dependencies: + '@babel/helper-validator-identifier': 7.25.7 + chalk: 2.4.2 + js-tokens: 4.0.0 + picocolors: 1.1.0 + '@babel/runtime@7.25.6': dependencies: regenerator-runtime: 0.14.1 @@ -1976,6 +2227,19 @@ snapshots: '@oxc-resolver/binding-win32-x64-msvc@1.11.0': optional: true + '@puppeteer/browsers@2.4.0': + dependencies: + debug: 4.3.7(supports-color@5.5.0) + extract-zip: 2.0.1 + progress: 2.0.3 + proxy-agent: 6.4.0 + semver: 7.6.3 + tar-fs: 3.0.6 + unbzip2-stream: 1.4.3 + yargs: 17.7.2 + transitivePeerDependencies: + - supports-color + '@scure/base@1.1.1': {} '@scure/bip32@1.3.1': @@ -2200,6 +2464,11 @@ snapshots: dependencies: '@types/node': 20.16.5 + '@types/yauzl@2.10.3': + dependencies: + '@types/node': 20.16.5 + optional: true + abbrev@1.1.1: optional: true @@ -2236,6 +2505,14 @@ snapshots: ansi-regex@5.0.1: {} + ansi-styles@3.2.1: + dependencies: + color-convert: 1.9.3 + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + anymatch@3.1.3: dependencies: normalize-path: 3.0.0 @@ -2254,14 +2531,42 @@ snapshots: dependencies: sprintf-js: 1.0.3 + argparse@2.0.1: {} + array-union@2.1.0: {} ast-types@0.13.4: dependencies: tslib: 2.7.0 + b4a@1.6.7: {} + balanced-match@1.0.2: {} + bare-events@2.5.0: + optional: true + + bare-fs@2.3.5: + dependencies: + bare-events: 2.5.0 + bare-path: 2.1.3 + bare-stream: 2.3.0 + optional: true + + bare-os@2.4.4: + optional: true + + bare-path@2.1.3: + dependencies: + bare-os: 2.4.4 + optional: true + + bare-stream@2.3.0: + dependencies: + b4a: 1.6.7 + streamx: 2.20.1 + optional: true + base64-js@1.5.1: {} basic-auth@2.0.1: @@ -2299,6 +2604,8 @@ snapshots: dependencies: fill-range: 7.1.1 + buffer-crc32@0.2.13: {} + buffer-from@1.1.2: {} buffer@5.7.1: @@ -2340,6 +2647,14 @@ snapshots: mime-types: 2.1.35 ylru: 1.4.0 + callsites@3.1.0: {} + + chalk@2.4.2: + dependencies: + ansi-styles: 3.2.1 + escape-string-regexp: 1.0.5 + supports-color: 5.5.0 + chardet@0.7.0: {} chokidar@3.6.0: @@ -2358,15 +2673,40 @@ snapshots: chownr@2.0.0: {} + chromium-bidi@0.8.0(devtools-protocol@0.0.1342118): + dependencies: + devtools-protocol: 0.0.1342118 + mitt: 3.0.1 + urlpattern-polyfill: 10.0.0 + zod: 3.23.8 + ci-info@3.9.0: {} clean-stack@2.2.0: optional: true + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + cluster-key-slot@1.1.2: {} co@4.6.0: {} + color-convert@1.9.3: + dependencies: + color-name: 1.1.3 + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.3: {} + + color-name@1.1.4: {} + color-support@1.1.3: optional: true @@ -2388,6 +2728,15 @@ snapshots: depd: 2.0.0 keygrip: 1.1.0 + cosmiconfig@9.0.0(typescript@5.6.2): + dependencies: + env-paths: 2.2.1 + import-fresh: 3.3.0 + js-yaml: 4.1.0 + parse-json: 5.2.0 + optionalDependencies: + typescript: 5.6.2 + cross-spawn@5.1.0: dependencies: lru-cache: 4.1.5 @@ -2438,6 +2787,8 @@ snapshots: detect-libc@2.0.3: {} + devtools-protocol@0.0.1342118: {} + dir-glob@3.0.1: dependencies: path-type: 4.0.0 @@ -2446,8 +2797,7 @@ snapshots: ee-first@1.1.1: {} - emoji-regex@8.0.0: - optional: true + emoji-regex@8.0.0: {} encodeurl@1.0.2: {} @@ -2465,14 +2815,21 @@ snapshots: ansi-colors: 4.1.3 strip-ansi: 6.0.1 - env-paths@2.2.1: - optional: true + env-paths@2.2.1: {} err-code@2.0.3: optional: true + error-ex@1.3.2: + dependencies: + is-arrayish: 0.2.1 + + escalade@3.2.0: {} + escape-html@1.0.3: {} + escape-string-regexp@1.0.5: {} + escodegen@2.1.0: dependencies: esprima: 4.0.1 @@ -2497,6 +2854,18 @@ snapshots: iconv-lite: 0.4.24 tmp: 0.0.33 + extract-zip@2.0.1: + dependencies: + debug: 4.3.7(supports-color@5.5.0) + get-stream: 5.2.0 + yauzl: 2.10.0 + optionalDependencies: + '@types/yauzl': 2.10.3 + transitivePeerDependencies: + - supports-color + + fast-fifo@1.3.2: {} + fast-glob@3.3.2: dependencies: '@nodelib/fs.stat': 2.0.5 @@ -2509,6 +2878,10 @@ snapshots: dependencies: reusify: 1.0.4 + fd-slicer@1.1.0: + dependencies: + pend: 1.2.0 + file-uri-to-path@1.0.0: {} fill-range@7.1.1: @@ -2566,6 +2939,12 @@ snapshots: wide-align: 1.1.5 optional: true + get-caller-file@2.0.5: {} + + get-stream@5.2.0: + dependencies: + pump: 3.0.2 + get-uri@6.0.3: dependencies: basic-ftp: 5.0.5 @@ -2689,6 +3068,11 @@ snapshots: ignore@5.3.2: {} + import-fresh@3.3.0: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + import2@1.0.3: {} imurmurhash@0.1.4: @@ -2731,14 +3115,15 @@ snapshots: jsbn: 1.1.0 sprintf-js: 1.1.3 + is-arrayish@0.2.1: {} + is-binary-path@2.1.0: dependencies: binary-extensions: 2.3.0 is-extglob@2.1.1: {} - is-fullwidth-code-point@3.0.0: - optional: true + is-fullwidth-code-point@3.0.0: {} is-generator-function@1.0.10: dependencies: @@ -2761,13 +3146,21 @@ snapshots: isexe@2.0.0: {} + js-tokens@4.0.0: {} + js-yaml@3.14.1: dependencies: argparse: 1.0.10 esprima: 4.0.1 + js-yaml@4.1.0: + dependencies: + argparse: 2.0.1 + jsbn@1.1.0: {} + json-parse-even-better-errors@2.3.1: {} + jsonfile@4.0.0: optionalDependencies: graceful-fs: 4.2.11 @@ -2842,6 +3235,8 @@ snapshots: transitivePeerDependencies: - supports-color + lines-and-columns@1.2.4: {} + locate-path@5.0.0: dependencies: p-locate: 4.1.0 @@ -2952,6 +3347,8 @@ snapshots: minipass: 3.3.6 yallist: 4.0.0 + mitt@3.0.1: {} + mkdirp-classic@0.5.3: {} mkdirp@1.0.4: {} @@ -3119,6 +3516,17 @@ snapshots: package-manager-detector@0.2.0: {} + parent-module@1.0.1: + dependencies: + callsites: 3.1.0 + + parse-json@5.2.0: + dependencies: + '@babel/code-frame': 7.25.7 + error-ex: 1.3.2 + json-parse-even-better-errors: 2.3.1 + lines-and-columns: 1.2.4 + parseurl@1.3.3: {} path-exists@4.0.0: {} @@ -3127,6 +3535,8 @@ snapshots: path-type@4.0.0: {} + pend@1.2.0: {} + picocolors@1.1.0: {} picomatch@2.3.1: {} @@ -3154,6 +3564,8 @@ snapshots: prettier@3.3.3: {} + progress@2.0.3: {} + promise-inflight@1.0.1: optional: true @@ -3187,8 +3599,37 @@ snapshots: end-of-stream: 1.4.4 once: 1.4.0 + puppeteer-core@23.5.0: + dependencies: + '@puppeteer/browsers': 2.4.0 + chromium-bidi: 0.8.0(devtools-protocol@0.0.1342118) + debug: 4.3.7(supports-color@5.5.0) + devtools-protocol: 0.0.1342118 + typed-query-selector: 2.12.0 + ws: 8.18.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + puppeteer@23.5.0(typescript@5.6.2): + dependencies: + '@puppeteer/browsers': 2.4.0 + chromium-bidi: 0.8.0(devtools-protocol@0.0.1342118) + cosmiconfig: 9.0.0(typescript@5.6.2) + devtools-protocol: 0.0.1342118 + puppeteer-core: 23.5.0 + typed-query-selector: 2.12.0 + transitivePeerDependencies: + - bufferutil + - supports-color + - typescript + - utf-8-validate + queue-microtask@1.2.3: {} + queue-tick@1.0.1: {} + rc@1.2.8: dependencies: deep-extend: 0.6.0 @@ -3221,6 +3662,10 @@ snapshots: regenerator-runtime@0.14.1: {} + require-directory@2.1.1: {} + + resolve-from@4.0.0: {} + resolve-from@5.0.0: {} resolve-path@1.4.0: @@ -3340,12 +3785,19 @@ snapshots: statuses@1.5.0: {} + streamx@2.20.1: + dependencies: + fast-fifo: 1.3.2 + queue-tick: 1.0.1 + text-decoder: 1.2.0 + optionalDependencies: + bare-events: 2.5.0 + string-width@4.2.3: dependencies: emoji-regex: 8.0.0 is-fullwidth-code-point: 3.0.0 strip-ansi: 6.0.1 - optional: true string_decoder@1.3.0: dependencies: @@ -3370,6 +3822,14 @@ snapshots: pump: 3.0.2 tar-stream: 2.2.0 + tar-fs@3.0.6: + dependencies: + pump: 3.0.2 + tar-stream: 3.1.7 + optionalDependencies: + bare-fs: 2.3.5 + bare-path: 2.1.3 + tar-stream@2.2.0: dependencies: bl: 4.1.0 @@ -3378,6 +3838,12 @@ snapshots: inherits: 2.0.4 readable-stream: 3.6.2 + tar-stream@3.1.7: + dependencies: + b4a: 1.6.7 + fast-fifo: 1.3.2 + streamx: 2.20.1 + tar@6.2.1: dependencies: chownr: 2.0.0 @@ -3389,6 +3855,12 @@ snapshots: term-size@2.2.1: {} + text-decoder@1.2.0: + dependencies: + b4a: 1.6.7 + + through@2.3.8: {} + tmp@0.0.33: dependencies: os-tmpdir: 1.0.2 @@ -3416,8 +3888,15 @@ snapshots: media-typer: 0.3.0 mime-types: 2.1.35 + typed-query-selector@2.12.0: {} + typescript@5.6.2: {} + unbzip2-stream@1.4.3: + dependencies: + buffer: 5.7.1 + through: 2.3.8 + undefsafe@2.0.5: {} undici-types@6.19.8: {} @@ -3436,6 +3915,8 @@ snapshots: universalify@2.0.1: {} + urlpattern-polyfill@10.0.0: {} + util-deprecate@1.0.2: {} vary@1.1.2: {} @@ -3463,14 +3944,41 @@ snapshots: string-width: 4.2.3 optional: true + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrappy@1.0.2: {} ws@8.18.0: {} xbytes@1.9.1: {} + y18n@5.0.8: {} + yallist@2.1.2: {} yallist@4.0.0: {} + yargs-parser@21.1.1: {} + + yargs@17.7.2: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + + yauzl@2.10.0: + dependencies: + buffer-crc32: 0.2.13 + fd-slicer: 1.1.0 + ylru@1.4.0: {} + + zod@3.23.8: {} diff --git a/public/components/nsite-card.js b/public/components/nsite-card.js new file mode 100644 index 0000000..57edd0a --- /dev/null +++ b/public/components/nsite-card.js @@ -0,0 +1,100 @@ +import { html, css, LitElement } from "lit"; +import { nip19 } from "nostr-tools"; +import { pool, relays } from "../pool.js"; + +export class NsiteCard extends LitElement { + static styles = css` + :host { + min-width: 3in; + max-width: 4in; + border: 1px solid lightslategray; + display: flex; + flex-direction: column; + padding: 0.5em; + gap: 0.3em; + border-radius: 0.5em; + } + + .title { + display: flex; + gap: 0.5em; + align-items: center; + color: initial; + text-decoration: none; + } + .title h3 { + margin: 0; + } + .avatar { + width: 3rem; + height: 3rem; + border: none; + outline: none; + border-radius: 50%; + } + + .thumb { + display: flex; + overflow: hidden; + } + + .thumb > img { + width: 100%; + border-radius: 0.5em; + } + + .about { + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + overflow: hidden; + } + + time { + margin-top: auto; + } + `; + + static properties = { + nsite: { type: Object }, + profile: { state: true, type: Object }, + }; + + constructor() { + super(); + } + + connectedCallback() { + super.connectedCallback(); + + pool.get(relays, { kinds: [0], authors: [this.nsite.pubkey] }).then((event) => { + if (event) this.profile = JSON.parse(event.content); + }); + } + + render() { + const npub = nip19.npubEncode(this.nsite.pubkey); + const url = new URL("/", `${location.protocol}//${npub}.${location.host}`); + + return html` + + + + + ${this.profile && html``} +
+ ${this.profile + ? html` +

${this.profile.display_name || this.profile.name}

+ ${this.profile.nip05} + ` + : html`

${npub.slice(0, 8)}

`} +
+
+ ${this.profile && html`

${this.profile.about}

`} + + `; + } +} + +customElements.define("nsite-card", NsiteCard); diff --git a/public/index.html b/public/index.html index 3615823..cea69c8 100644 --- a/public/index.html +++ b/public/index.html @@ -5,16 +5,13 @@ nsite - - - - - @@ -24,25 +21,9 @@ width: 100%; } + -
- -

nsite

- Source Code - -

Latest nsites:

-
-
- - - - + diff --git a/public/lib/lit.min.js b/public/lib/lit.min.js new file mode 100644 index 0000000..dd99bbe --- /dev/null +++ b/public/lib/lit.min.js @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +const t=globalThis,s=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),e=new WeakMap;class o{constructor(t,s,e){if(this._$cssResult$=!0,e!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=s}get styleSheet(){let t=this.i;const i=this.t;if(s&&void 0===t){const s=void 0!==i&&1===i.length;s&&(t=e.get(i)),void 0===t&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),s&&e.set(i,t))}return t}toString(){return this.cssText}}const h=t=>new o("string"==typeof t?t:t+"",void 0,i),r=(t,...s)=>{const e=1===t.length?t[0]:s.reduce(((s,i,e)=>s+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+t[e+1]),t[0]);return new o(e,t,i)},n=(i,e)=>{if(s)i.adoptedStyleSheets=e.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(const s of e){const e=document.createElement("style"),o=t.litNonce;void 0!==o&&e.setAttribute("nonce",o),e.textContent=s.cssText,i.appendChild(e)}},c=s?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let s="";for(const i of t.cssRules)s+=i.cssText;return h(s)})(t):t +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */,{is:a,defineProperty:l,getOwnPropertyDescriptor:u,getOwnPropertyNames:d,getOwnPropertySymbols:f,getPrototypeOf:p}=Object,v=globalThis,m=v.trustedTypes,y=m?m.emptyScript:"",g=v.reactiveElementPolyfillSupport,_=(t,s)=>t,b={toAttribute(t,s){switch(s){case Boolean:t=t?y:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},S=(t,s)=>!a(t,s),w={attribute:!0,type:String,converter:b,reflect:!1,hasChanged:S};Symbol.metadata??=Symbol("metadata"),v.litPropertyMetadata??=new WeakMap;class $ extends HTMLElement{static addInitializer(t){this.o(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this.u&&[...this.u.keys()]}static createProperty(t,s=w){if(s.state&&(s.attribute=!1),this.o(),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),e=this.getPropertyDescriptor(t,i,s);void 0!==e&&l(this.prototype,t,e)}}static getPropertyDescriptor(t,s,i){const{get:e,set:o}=u(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get(){return e?.call(this)},set(s){const h=e?.call(this);o.call(this,s),this.requestUpdate(t,h,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??w}static o(){if(this.hasOwnProperty(_("elementProperties")))return;const t=p(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(_("finalized")))return;if(this.finalized=!0,this.o(),this.hasOwnProperty(_("properties"))){const t=this.properties,s=[...d(t),...f(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this.u=new Map;for(const[t,s]of this.elementProperties){const i=this.p(t,s);void 0!==i&&this.u.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const s=[];if(Array.isArray(t)){const i=new Set(t.flat(1/0).reverse());for(const t of i)s.unshift(c(t))}else void 0!==t&&s.push(c(t));return s}static p(t,s){const i=s.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this.v=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this.m=null,this._()}_(){this.S=new Promise((t=>this.enableUpdating=t)),this._$AL=new Map,this.$(),this.requestUpdate(),this.constructor.l?.forEach((t=>t(this)))}addController(t){(this.P??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this.P?.delete(t)}$(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this.v=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return n(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this.P?.forEach((t=>t.hostConnected?.()))}enableUpdating(t){}disconnectedCallback(){this.P?.forEach((t=>t.hostDisconnected?.()))}attributeChangedCallback(t,s,i){this._$AK(t,i)}C(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor.p(t,i);if(void 0!==e&&!0===i.reflect){const o=(void 0!==i.converter?.toAttribute?i.converter:b).toAttribute(s,i.type);this.m=t,null==o?this.removeAttribute(e):this.setAttribute(e,o),this.m=null}}_$AK(t,s){const i=this.constructor,e=i.u.get(t);if(void 0!==e&&this.m!==e){const t=i.getPropertyOptions(e),o="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:b;this.m=e,this[e]=o.fromAttribute(s,t.type),this.m=null}}requestUpdate(t,s,i){if(void 0!==t){if(i??=this.constructor.getPropertyOptions(t),!(i.hasChanged??S)(this[t],s))return;this.T(t,s,i)}!1===this.isUpdatePending&&(this.S=this.A())}T(t,s,i){this._$AL.has(t)||this._$AL.set(t,s),!0===i.reflect&&this.m!==t&&(this.M??=new Set).add(t)}async A(){this.isUpdatePending=!0;try{await this.S}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this.v){for(const[t,s]of this.v)this[t]=s;this.v=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t)!0!==i.wrapped||this._$AL.has(s)||void 0===this[s]||this.T(s,this[s],i)}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this.P?.forEach((t=>t.hostUpdate?.())),this.update(s)):this.k()}catch(s){throw t=!1,this.k(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this.P?.forEach((t=>t.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}k(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this.S}shouldUpdate(t){return!0}update(t){this.M&&=this.M.forEach((t=>this.C(t,this[t]))),this.k()}updated(t){}firstUpdated(t){}}$.elementStyles=[],$.shadowRootOptions={mode:"open"},$[_("elementProperties")]=new Map,$[_("finalized")]=new Map,g?.({ReactiveElement:$}),(v.reactiveElementVersions??=[]).push("2.0.4"); +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +const P=globalThis,C=P.trustedTypes,T=C?C.createPolicy("lit-html",{createHTML:t=>t}):void 0,x="$lit$",A=`lit$${Math.random().toFixed(9).slice(2)}$`,M="?"+A,k=`<${M}>`,E=document,U=()=>E.createComment(""),N=t=>null===t||"object"!=typeof t&&"function"!=typeof t,O=Array.isArray,R=t=>O(t)||"function"==typeof t?.[Symbol.iterator],z="[ \t\n\f\r]",V=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,L=/-->/g,I=/>/g,j=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),D=/'/g,H=/"/g,B=/^(?:script|style|textarea|title)$/i,W=t=>(s,...i)=>({_$litType$:t,strings:s,values:i}),q=W(1),J=W(2),Z=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),G=new WeakMap,K=E.createTreeWalker(E,129);function Q(t,s){if(!Array.isArray(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==T?T.createHTML(s):s}const X=(t,s)=>{const i=t.length-1,e=[];let o,h=2===s?"":"",r=V;for(let s=0;s"===c[0]?(r=o??V,a=-1):void 0===c[1]?a=-2:(a=r.lastIndex-c[2].length,n=c[1],r=void 0===c[3]?j:'"'===c[3]?H:D):r===H||r===D?r=j:r===L||r===I?r=V:(r=j,o=void 0);const u=r===j&&t[s+1].startsWith("/>")?" ":"";h+=r===V?i+k:a>=0?(e.push(n),i.slice(0,a)+x+i.slice(a)+A+u):i+A+(-2===a?s:u)}return[Q(t,h+(t[i]||"")+(2===s?"":"")),e]};class Y{constructor({strings:t,_$litType$:s},i){let e;this.parts=[];let o=0,h=0;const r=t.length-1,n=this.parts,[c,a]=X(t,s);if(this.el=Y.createElement(c,i),K.currentNode=this.el.content,2===s){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(e=K.nextNode())&&n.length0){e.textContent=C?C.emptyScript:"";for(let i=0;i2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=F}_$AI(t,s=this,i,e){const o=this.strings;let h=!1;if(void 0===o)t=tt(this,t,s,0),h=!N(t)||t!==this._$AH&&t!==Z,h&&(this._$AH=t);else{const e=t;let r,n;for(t=o[0],r=0;r{const e=i?.renderBefore??s;let o=e._$litPart$;if(void 0===o){const t=i?.renderBefore??null;e._$litPart$=o=new it(s.insertBefore(U(),t),t,void 0,i??{})}return o._$AI(t),o}; +/** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */class ut extends ${constructor(){super(...arguments),this.renderOptions={host:this},this.ht=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const s=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this.ht=lt(s,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.ht?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.ht?.setConnected(!1)}render(){return Z}}ut._$litElement$=!0,ut[("finalized","finalized")]=!0,globalThis.litElementHydrateSupport?.({LitElement:ut});const dt=globalThis.litElementPolyfillSupport;dt?.({LitElement:ut});const ft={_$AK:(t,s,i)=>{t._$AK(s,i)},_$AL:t=>t._$AL};(globalThis.litElementVersions??=[]).push("4.0.5"); +/** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + */ +const pt=!1;export{o as CSSResult,ut as LitElement,$ as ReactiveElement,ft as _$LE,ct as _$LH,n as adoptStyles,r as css,b as defaultConverter,c as getCompatibleStyle,q as html,pt as isServer,Z as noChange,S as notEqual,F as nothing,lt as render,s as supportsAdoptingStyleSheets,J as svg,h as unsafeCSS}; +//# sourceMappingURL=lit-core.min.js.map diff --git a/public/lib/nostr-name.js b/public/lib/nostr-name.js deleted file mode 100644 index 8573999..0000000 --- a/public/lib/nostr-name.js +++ /dev/null @@ -1,4034 +0,0 @@ -"use strict"; -(() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __commonJS = (cb, mod2) => function __require() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; - }; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 - )); - var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; - }; - - // node_modules/obliterator/iterator.js - var require_iterator = __commonJS({ - "node_modules/obliterator/iterator.js"(exports, module) { - function Iterator(next) { - if (typeof next !== "function") - throw new Error("obliterator/iterator: expecting a function!"); - this.next = next; - } - if (typeof Symbol !== "undefined") - Iterator.prototype[Symbol.iterator] = function() { - return this; - }; - Iterator.of = function() { - var args = arguments, l = args.length, i2 = 0; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - return { done: false, value: args[i2++] }; - }); - }; - Iterator.empty = function() { - var iterator = new Iterator(function() { - return { done: true }; - }); - return iterator; - }; - Iterator.fromSequence = function(sequence) { - var i2 = 0, l = sequence.length; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - return { done: false, value: sequence[i2++] }; - }); - }; - Iterator.is = function(value) { - if (value instanceof Iterator) - return true; - return typeof value === "object" && value !== null && typeof value.next === "function"; - }; - module.exports = Iterator; - } - }); - - // node_modules/obliterator/support.js - var require_support = __commonJS({ - "node_modules/obliterator/support.js"(exports) { - exports.ARRAY_BUFFER_SUPPORT = typeof ArrayBuffer !== "undefined"; - exports.SYMBOL_SUPPORT = typeof Symbol !== "undefined"; - } - }); - - // node_modules/obliterator/foreach.js - var require_foreach = __commonJS({ - "node_modules/obliterator/foreach.js"(exports, module) { - var support = require_support(); - var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT; - var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT; - module.exports = function forEach(iterable, callback) { - var iterator, k, i2, l, s; - if (!iterable) - throw new Error("obliterator/forEach: invalid iterable."); - if (typeof callback !== "function") - throw new Error("obliterator/forEach: expecting a callback."); - if (Array.isArray(iterable) || ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable) || typeof iterable === "string" || iterable.toString() === "[object Arguments]") { - for (i2 = 0, l = iterable.length; i2 < l; i2++) - callback(iterable[i2], i2); - return; - } - if (typeof iterable.forEach === "function") { - iterable.forEach(callback); - return; - } - if (SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== "function") { - iterable = iterable[Symbol.iterator](); - } - if (typeof iterable.next === "function") { - iterator = iterable; - i2 = 0; - while (s = iterator.next(), s.done !== true) { - callback(s.value, i2); - i2++; - } - return; - } - for (k in iterable) { - if (iterable.hasOwnProperty(k)) { - callback(iterable[k], k); - } - } - return; - }; - } - }); - - // node_modules/mnemonist/utils/typed-arrays.js - var require_typed_arrays = __commonJS({ - "node_modules/mnemonist/utils/typed-arrays.js"(exports) { - var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1; - var MAX_16BIT_INTEGER = Math.pow(2, 16) - 1; - var MAX_32BIT_INTEGER = Math.pow(2, 32) - 1; - var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1; - var MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1; - var MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1; - exports.getPointerArray = function(size) { - var maxIndex = size - 1; - if (maxIndex <= MAX_8BIT_INTEGER) - return Uint8Array; - if (maxIndex <= MAX_16BIT_INTEGER) - return Uint16Array; - if (maxIndex <= MAX_32BIT_INTEGER) - return Uint32Array; - throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported."); - }; - exports.getSignedPointerArray = function(size) { - var maxIndex = size - 1; - if (maxIndex <= MAX_SIGNED_8BIT_INTEGER) - return Int8Array; - if (maxIndex <= MAX_SIGNED_16BIT_INTEGER) - return Int16Array; - if (maxIndex <= MAX_SIGNED_32BIT_INTEGER) - return Int32Array; - return Float64Array; - }; - exports.getNumberType = function(value) { - if (value === (value | 0)) { - if (Math.sign(value) === -1) { - if (value <= 127 && value >= -128) - return Int8Array; - if (value <= 32767 && value >= -32768) - return Int16Array; - return Int32Array; - } else { - if (value <= 255) - return Uint8Array; - if (value <= 65535) - return Uint16Array; - return Uint32Array; - } - } - return Float64Array; - }; - var TYPE_PRIORITY = { - Uint8Array: 1, - Int8Array: 2, - Uint16Array: 3, - Int16Array: 4, - Uint32Array: 5, - Int32Array: 6, - Float32Array: 7, - Float64Array: 8 - }; - exports.getMinimalRepresentation = function(array, getter) { - var maxType = null, maxPriority = 0, p, t, v, i2, l; - for (i2 = 0, l = array.length; i2 < l; i2++) { - v = getter ? getter(array[i2]) : array[i2]; - t = exports.getNumberType(v); - p = TYPE_PRIORITY[t.name]; - if (p > maxPriority) { - maxPriority = p; - maxType = t; - } - } - return maxType; - }; - exports.isTypedArray = function(value) { - return typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(value); - }; - exports.concat = function() { - var length = 0, i2, o, l; - for (i2 = 0, l = arguments.length; i2 < l; i2++) - length += arguments[i2].length; - var array = new arguments[0].constructor(length); - for (i2 = 0, o = 0; i2 < l; i2++) { - array.set(arguments[i2], o); - o += arguments[i2].length; - } - return array; - }; - exports.indices = function(length) { - var PointerArray = exports.getPointerArray(length); - var array = new PointerArray(length); - for (var i2 = 0; i2 < length; i2++) - array[i2] = i2; - return array; - }; - } - }); - - // node_modules/mnemonist/utils/iterables.js - var require_iterables = __commonJS({ - "node_modules/mnemonist/utils/iterables.js"(exports) { - var forEach = require_foreach(); - var typed = require_typed_arrays(); - function isArrayLike(target) { - return Array.isArray(target) || typed.isTypedArray(target); - } - function guessLength(target) { - if (typeof target.length === "number") - return target.length; - if (typeof target.size === "number") - return target.size; - return; - } - function toArray(target) { - var l = guessLength(target); - var array = typeof l === "number" ? new Array(l) : []; - var i2 = 0; - forEach(target, function(value) { - array[i2++] = value; - }); - return array; - } - function toArrayWithIndices(target) { - var l = guessLength(target); - var IndexArray = typeof l === "number" ? typed.getPointerArray(l) : Array; - var array = typeof l === "number" ? new Array(l) : []; - var indices = typeof l === "number" ? new IndexArray(l) : []; - var i2 = 0; - forEach(target, function(value) { - array[i2] = value; - indices[i2] = i2++; - }); - return [array, indices]; - } - exports.isArrayLike = isArrayLike; - exports.guessLength = guessLength; - exports.toArray = toArray; - exports.toArrayWithIndices = toArrayWithIndices; - } - }); - - // node_modules/mnemonist/lru-cache.js - var require_lru_cache = __commonJS({ - "node_modules/mnemonist/lru-cache.js"(exports, module) { - var Iterator = require_iterator(); - var forEach = require_foreach(); - var typed = require_typed_arrays(); - var iterables = require_iterables(); - function LRUCache2(Keys, Values, capacity) { - if (arguments.length < 2) { - capacity = Keys; - Keys = null; - Values = null; - } - this.capacity = capacity; - if (typeof this.capacity !== "number" || this.capacity <= 0) - throw new Error("mnemonist/lru-cache: capacity should be positive number."); - else if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity) - throw new Error("mnemonist/lru-cache: capacity should be a finite positive integer."); - var PointerArray = typed.getPointerArray(capacity); - this.forward = new PointerArray(capacity); - this.backward = new PointerArray(capacity); - this.K = typeof Keys === "function" ? new Keys(capacity) : new Array(capacity); - this.V = typeof Values === "function" ? new Values(capacity) : new Array(capacity); - this.size = 0; - this.head = 0; - this.tail = 0; - this.items = {}; - } - LRUCache2.prototype.clear = function() { - this.size = 0; - this.head = 0; - this.tail = 0; - this.items = {}; - }; - LRUCache2.prototype.splayOnTop = function(pointer) { - var oldHead = this.head; - if (this.head === pointer) - return this; - var previous = this.backward[pointer], next = this.forward[pointer]; - if (this.tail === pointer) { - this.tail = previous; - } else { - this.backward[next] = previous; - } - this.forward[previous] = next; - this.backward[oldHead] = pointer; - this.head = pointer; - this.forward[pointer] = oldHead; - return this; - }; - LRUCache2.prototype.set = function(key, value) { - var pointer = this.items[key]; - if (typeof pointer !== "undefined") { - this.splayOnTop(pointer); - this.V[pointer] = value; - return; - } - if (this.size < this.capacity) { - pointer = this.size++; - } else { - pointer = this.tail; - this.tail = this.backward[pointer]; - delete this.items[this.K[pointer]]; - } - this.items[key] = pointer; - this.K[pointer] = key; - this.V[pointer] = value; - this.forward[pointer] = this.head; - this.backward[this.head] = pointer; - this.head = pointer; - }; - LRUCache2.prototype.setpop = function(key, value) { - var oldValue = null; - var oldKey = null; - var pointer = this.items[key]; - if (typeof pointer !== "undefined") { - this.splayOnTop(pointer); - oldValue = this.V[pointer]; - this.V[pointer] = value; - return { evicted: false, key, value: oldValue }; - } - if (this.size < this.capacity) { - pointer = this.size++; - } else { - pointer = this.tail; - this.tail = this.backward[pointer]; - oldValue = this.V[pointer]; - oldKey = this.K[pointer]; - delete this.items[oldKey]; - } - this.items[key] = pointer; - this.K[pointer] = key; - this.V[pointer] = value; - this.forward[pointer] = this.head; - this.backward[this.head] = pointer; - this.head = pointer; - if (oldKey) { - return { evicted: true, key: oldKey, value: oldValue }; - } else { - return null; - } - }; - LRUCache2.prototype.has = function(key) { - return key in this.items; - }; - LRUCache2.prototype.get = function(key) { - var pointer = this.items[key]; - if (typeof pointer === "undefined") - return; - this.splayOnTop(pointer); - return this.V[pointer]; - }; - LRUCache2.prototype.peek = function(key) { - var pointer = this.items[key]; - if (typeof pointer === "undefined") - return; - return this.V[pointer]; - }; - LRUCache2.prototype.forEach = function(callback, scope) { - scope = arguments.length > 1 ? scope : this; - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, values = this.V, forward = this.forward; - while (i2 < l) { - callback.call(scope, values[pointer], keys[pointer], this); - pointer = forward[pointer]; - i2++; - } - }; - LRUCache2.prototype.keys = function() { - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var key = keys[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value: key - }; - }); - }; - LRUCache2.prototype.values = function() { - var i2 = 0, l = this.size; - var pointer = this.head, values = this.V, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var value = values[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value - }; - }); - }; - LRUCache2.prototype.entries = function() { - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, values = this.V, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var key = keys[pointer], value = values[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value: [key, value] - }; - }); - }; - if (typeof Symbol !== "undefined") - LRUCache2.prototype[Symbol.iterator] = LRUCache2.prototype.entries; - LRUCache2.prototype.inspect = function() { - var proxy = /* @__PURE__ */ new Map(); - var iterator = this.entries(), step; - while (step = iterator.next(), !step.done) - proxy.set(step.value[0], step.value[1]); - Object.defineProperty(proxy, "constructor", { - value: LRUCache2, - enumerable: false - }); - return proxy; - }; - if (typeof Symbol !== "undefined") - LRUCache2.prototype[Symbol.for("nodejs.util.inspect.custom")] = LRUCache2.prototype.inspect; - LRUCache2.from = function(iterable, Keys, Values, capacity) { - if (arguments.length < 2) { - capacity = iterables.guessLength(iterable); - if (typeof capacity !== "number") - throw new Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument."); - } else if (arguments.length === 2) { - capacity = Keys; - Keys = null; - Values = null; - } - var cache = new LRUCache2(Keys, Values, capacity); - forEach(iterable, function(value, key) { - cache.set(key, value); - }); - return cache; - }; - module.exports = LRUCache2; - } - }); - - // node_modules/debounce/index.js - var require_debounce = __commonJS({ - "node_modules/debounce/index.js"(exports, module) { - function debounce2(function_, wait = 100, options = {}) { - if (typeof function_ !== "function") { - throw new TypeError(`Expected the first parameter to be a function, got \`${typeof function_}\`.`); - } - if (wait < 0) { - throw new RangeError("`wait` must not be negative."); - } - const { immediate } = typeof options === "boolean" ? { immediate: options } : options; - let storedContext; - let storedArguments; - let timeoutId; - let timestamp; - let result; - function run() { - const callContext = storedContext; - const callArguments = storedArguments; - storedContext = void 0; - storedArguments = void 0; - result = function_.apply(callContext, callArguments); - return result; - } - function later() { - const last = Date.now() - timestamp; - if (last < wait && last >= 0) { - timeoutId = setTimeout(later, wait - last); - } else { - timeoutId = void 0; - if (!immediate) { - result = run(); - } - } - } - const debounced = function(...arguments_) { - if (storedContext && this !== storedContext) { - throw new Error("Debounced method called with different contexts."); - } - storedContext = this; - storedArguments = arguments_; - timestamp = Date.now(); - const callNow = immediate && !timeoutId; - if (!timeoutId) { - timeoutId = setTimeout(later, wait); - } - if (callNow) { - result = run(); - } - return result; - }; - debounced.clear = () => { - if (!timeoutId) { - return; - } - clearTimeout(timeoutId); - timeoutId = void 0; - }; - debounced.flush = () => { - if (!timeoutId) { - return; - } - debounced.trigger(); - }; - debounced.trigger = () => { - result = run(); - debounced.clear(); - }; - return debounced; - } - module.exports.debounce = debounce2; - module.exports = debounce2; - } - }); - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js - function number(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number(hash3.outputLen); - number(hash3.blockLen); - } - function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js - var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js - var u8a = (a) => a instanceof Uint8Array; - var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr = (word, shift) => word << 32 - shift | word >>> shift; - var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE) - throw new Error("Non little-endian hardware is not supported"); - function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - if (!u8a(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - function concatBytes(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - var Hash = class { - clone() { - return this._cloneInto(); - } - }; - var toStr = {}.toString; - function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - function randomBytes(bytesLength = 32) { - if (crypto && typeof crypto.getRandomValues === "function") { - return crypto.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js - function setBigUint64(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl, isLE3); - } - var SHA2 = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - exists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - exists(this); - output(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer[i2] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE3); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - }; - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js - var Chi = (a, b, c) => a & b ^ ~a & c; - var Maj = (a, b, c) => a & b ^ a & c ^ b & c; - var SHA256_K = /* @__PURE__ */ 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 - ]); - var IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - var SHA256_W = /* @__PURE__ */ new Uint32Array(64); - var SHA256 = class extends SHA2 { - constructor() { - super(64, 32, 8, false); - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W[i2 - 15]; - const W2 = SHA256_W[i2 - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - }; - var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); - - // node_modules/@noble/curves/esm/abstract/utils.js - var utils_exports = {}; - __export(utils_exports, { - bitGet: () => bitGet, - bitLen: () => bitLen, - bitMask: () => bitMask, - bitSet: () => bitSet, - bytesToHex: () => bytesToHex, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes2, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes, - hexToNumber: () => hexToNumber, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes2, - validateObject: () => validateObject - }); - var _0n = BigInt(0); - var _1n = BigInt(1); - var _2n = BigInt(2); - var u8a2 = (a) => a instanceof Uint8Array; - var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); - function bytesToHex(bytes3) { - if (!u8a2(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i2 = 0; i2 < bytes3.length; i2++) { - hex2 += hexes[bytes3[i2]]; - } - return hex2; - } - function numberToHexUnpadded(num) { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - } - function hexToNumber(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - return BigInt(hex2 === "" ? "0" : `0x${hex2}`); - } - function hexToBytes(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; - } - function bytesToNumberBE(bytes3) { - return hexToNumber(bytesToHex(bytes3)); - } - function bytesToNumberLE(bytes3) { - if (!u8a2(bytes3)) - throw new Error("Uint8Array expected"); - return hexToNumber(bytesToHex(Uint8Array.from(bytes3).reverse())); - } - function numberToBytesBE(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, "0")); - } - function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); - } - function numberToVarBytesBE(n) { - return hexToBytes(numberToHexUnpadded(n)); - } - function ensureBytes(title, hex2, expectedLength) { - let res; - if (typeof hex2 === "string") { - try { - res = hexToBytes(hex2); - } catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`); - } - } else if (u8a2(hex2)) { - res = Uint8Array.from(hex2); - } else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; - } - function concatBytes2(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a2(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - function equalBytes(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i2 = 0; i2 < b1.length; i2++) - if (b1[i2] !== b2[i2]) - return false; - return true; - } - function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function bitLen(n) { - let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; - return len; - } - function bitGet(n, pos) { - return n >> BigInt(pos) & _1n; - } - var bitSet = (n, pos, value) => { - return n | (value ? _1n : _0n) << BigInt(pos); - }; - var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; - var u8n = (data) => new Uint8Array(data); - var u8fr = (arr) => Uint8Array.from(arr); - function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i2 = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i2 = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n()) => { - k = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8fr([1]), seed); - v = h(); - }; - const gen = () => { - if (i2++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes2(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; - } - var validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) - }; - function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error(`Invalid validator "${type}", expected function`); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; - } - - // node_modules/@noble/curves/esm/abstract/modular.js - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n2 = BigInt(2); - var _3n = BigInt(3); - var _4n = BigInt(4); - var _5n = BigInt(5); - var _8n = BigInt(8); - var _9n = BigInt(9); - var _16n = BigInt(16); - function mod(a, b) { - const result = a % b; - return result >= _0n2 ? result : b + result; - } - function pow(num, power, modulo) { - if (modulo <= _0n2 || power < _0n2) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n2) - return _0n2; - let res = _1n2; - while (power > _0n2) { - if (power & _1n2) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n2; - } - return res; - } - function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; - } - function invert(number3, modulo) { - if (number3 === _0n2 || modulo <= _0n2) { - throw new Error(`invert: expected positive integers, got n=${number3} mod=${modulo}`); - } - let a = mod(number3, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd2 = b; - if (gcd2 !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); - } - function tonelliShanks(P) { - const legendreC = (P - _1n2) / _2n2; - let Q, S, Z; - for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) - ; - if (S === 1) { - const p1div4 = (P + _1n2) / _4n; - return function tonelliFast(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - const Q1div2 = (Q + _1n2) / _2n2; - return function tonelliSlow(Fp2, n) { - if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); - let x = Fp2.pow(n, Q1div2); - let b = Fp2.pow(n, Q); - while (!Fp2.eql(b, Fp2.ONE)) { - if (Fp2.eql(b, Fp2.ZERO)) - return Fp2.ZERO; - let m = 1; - for (let t2 = Fp2.sqr(b); m < r; m++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); - g = Fp2.sqr(ge2); - x = Fp2.mul(x, ge2); - b = Fp2.mul(b, g); - r = m; - } - return x; - }; - } - function FpSqrt(P) { - if (P % _4n === _3n) { - const p1div4 = (P + _1n2) / _4n; - return function sqrt3mod4(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _8n === _5n) { - const c1 = (P - _5n) / _8n; - return function sqrt5mod8(Fp2, n) { - const n2 = Fp2.mul(n, _2n2); - const v = Fp2.pow(n2, c1); - const nv = Fp2.mul(n, v); - const i2 = Fp2.mul(Fp2.mul(nv, _2n2), v); - const root = Fp2.mul(nv, Fp2.sub(i2, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _16n === _9n) { - } - return tonelliShanks(P); - } - var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; - function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); - } - function FpPow(f, num, power) { - if (power < _0n2) - throw new Error("Expected power > 0"); - if (power === _0n2) - return f.ONE; - if (power === _1n2) - return num; - let p = f.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n2; - } - return p; - } - function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = acc; - return f.mul(acc, num); - }, f.ONE); - const inverted = f.inv(lastMultiplied); - nums.reduceRight((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = f.mul(acc, tmp[i2]); - return f.mul(acc, num); - }, inverted); - return tmp; - } - function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; - } - function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { - if (ORDER <= _0n2) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt(ORDER); - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n2, - ONE: _1n2, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n2 <= num && num < ORDER; - }, - is0: (num) => num === _0n2, - isOdd: (num) => (num & _1n2) === _1n2, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f, n)), - invertBatch: (lst) => FpInvertBatch(f, lst), - cmov: (a, b, c) => c ? b : a, - toBytes: (num) => isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes3) => { - if (bytes3.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes3.length}`); - return isLE3 ? bytesToNumberLE(bytes3) : bytesToNumberBE(bytes3); - } - }); - return Object.freeze(f); - } - function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); - } - function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); - } - function mapHashToField(key, fieldOrder, isLE3 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE3 ? bytesToNumberBE(key) : bytesToNumberLE(key); - const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); - } - - // node_modules/@noble/curves/esm/abstract/curve.js - var _0n3 = BigInt(0); - var _1n3 = BigInt(1); - function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; - const windowSize = 2 ** (W - 1); - return { windows, windowSize }; - }; - return { - constTimeNegate, - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - }, - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window2 = 0; window2 < windows; window2++) { - base = p; - points.push(base); - for (let i2 = 1; i2 < windowSize; i2++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - wNAF(W, precomputes, n) { - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window2 = 0; window2 < windows; window2++) { - const offset = window2 * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window2 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f }; - }, - wNAFCached(P, precomputesMap, n, transform) { - const W = P._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - } - }; - } - function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); - } - - // node_modules/@noble/curves/esm/abstract/weierstrass.js - function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a } = opts; - if (endo) { - if (!Fp2.eql(a, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); - } - } - return Object.freeze({ ...opts }); - } - var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; - var DER = { - Err: class DERErr extends Error { - constructor(m = "") { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 2) - throw new E("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E("Invalid signature integer: unnecessary leading zero"); - return { d: b2n(res), l: data.subarray(len + 2) }; - }, - toSig(hex2) { - const { Err: E } = DER; - const data = typeof hex2 === "string" ? h2b(hex2) : hex2; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); - let l = data.length; - if (l < 2 || data[0] != 48) - throw new E("Invalid signature tag"); - if (data[1] !== l - 2) - throw new E("Invalid signature: incorrect length"); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E("Invalid signature: left bytes after parsing"); - return { r, s }; - }, - hexFromSig(sig) { - const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; - const h = (num) => { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - } - }; - var _0n4 = BigInt(0); - var _1n4 = BigInt(1); - var _2n3 = BigInt(2); - var _3n2 = BigInt(3); - var _4n2 = BigInt(4); - function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes3) => { - const tail = bytes3.subarray(1); - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp2.sqr(x); - const x3 = Fp2.mul(x2, x); - return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); - } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n4 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; - try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); - assertGE(num); - return num; - } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ProjectivePoint expected"); - } - class Point2 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp2.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point2) - throw new Error("projective point not allowed"); - const is0 = (i2) => Fp2.eql(i2, Fp2.ZERO); - if (is0(x) && is0(y)) - return Point2.ZERO; - return new Point2(x, y, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p) => p.pz)); - return points.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - } - static fromHex(hex2) { - const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); - P.assertValidity(); - return P; - } - static fromPrivateKey(privateKey) { - return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = this.toAffine(); - if (!Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y); - const right = weierstrassEquation(x); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U1 && U2; - } - negate() { - return new Point2(this.px, Fp2.neg(this.py), this.pz); - } - double() { - const { a, b } = CURVE; - const b3 = Fp2.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point2(X3, Y3, Z3); - } - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point2(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point2.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - }); - } - multiplyUnsafe(n) { - const I = Point2.ZERO; - if (n === _0n4) - return I; - assertGE(n); - if (n === _1n4) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n4 || k2 > _0n4) { - if (k1 & _1n4) - k1p = k1p.add(d); - if (k2 & _1n4) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n4; - k2 >>= _1n4; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(n); - point = p; - fake = f; - } - return Point2.normalizeZ([point, fake])[0]; - } - multiplyAndAddUnsafe(Q, a, b) { - const G = Point2.BASE; - const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? void 0 : sum; - } - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z); - const ax = Fp2.mul(x, iz); - const ay = Fp2.mul(y, iz); - const zz = Fp2.mul(z, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes3(Point2, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex(this.toRawBytes(isCompressed)); - } - } - Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point2, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; - } - function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); - } - function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n4 < num && num < Fp2.ORDER; - } - function modN2(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp2.toBytes(a.x); - const cat = concatBytes2; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); - } - }, - fromBytes(bytes3) { - const len = bytes3.length; - const head = bytes3[0]; - const tail = bytes3.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y = Fp2.sqrt(y2); - const isYOdd = (y & _1n4) === _1n4; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp2.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - } - }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number3) { - const HALF = CURVE_ORDER >> _1n4; - return number3 > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; - } - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - static fromCompact(hex2) { - const l = CURVE.nByteLength; - hex2 = ensureBytes("compactSignature", hex2, l * 2); - return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l)); - } - static fromDER(hex2) { - const { r, s } = DER.toSig(ensureBytes("DER", hex2)); - return new Signature(r, s); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point2.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN2(-h * ir); - const u2 = modN2(s * ir); - const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - toDERRawBytes() { - return hexToBytes(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - precompute(windowSize = 8, point = Point2.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey2(privateKey, isCompressed = true) { - return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b = Point2.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes3) { - const num = bytesToNumberBE(bytes3); - const delta = bytes3.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes3) { - return modN2(bits2int(bytes3)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n4 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE(num, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash3, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null) { - const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); - } - const seed = concatBytes2(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point2.BASE.multiply(k).toAffine(); - const r = modN2(q.x); - if (r === _0n4) - return; - const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point2.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig = void 0; - let P; - try { - if (typeof sg === "string" || sg instanceof Uint8Array) { - try { - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { - const { r: r2, s: s2 } = sg; - _sig = new Signature(r2, s2); - } else { - throw new Error("PARSE"); - } - P = Point2.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN2(h * is); - const u2 = modN2(r * is); - const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); - if (!R) - return false; - const v = modN2(R.x); - return v === r; - } - return { - CURVE, - getPublicKey: getPublicKey2, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point2, - Signature, - utils - }; - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js - var HMAC = class extends Hash { - constructor(hash3, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash(hash3); - const key = toBytes(_key); - this.iHash = hash3.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash3.create().update(key).digest() : key); - for (let i2 = 0; i2 < pad.length; i2++) - pad[i2] ^= 54; - this.iHash.update(pad); - this.oHash = hash3.create(); - for (let i2 = 0; i2 < pad.length; i2++) - pad[i2] ^= 54 ^ 92; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest(); - hmac.create = (hash3, key) => new HMAC(hash3, key); - - // node_modules/@noble/curves/esm/_shortw_utils.js - function getHash(hash3) { - return { - hash: hash3, - hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)), - randomBytes - }; - } - function createCurve(curveDef, defHash) { - const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); - return Object.freeze({ ...create(defHash), create }); - } - - // node_modules/@noble/curves/esm/secp256k1.js - var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - var _1n5 = BigInt(1); - var _2n4 = BigInt(2); - var divNearest = (a, b) => (a + b / _2n4) / b; - function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; - } - var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); - var secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } - }, sha256); - var _0n5 = BigInt(0); - var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; - var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; - var TAGGED_HASH_PREFIXES = {}; - function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes2(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes2(tagP, ...messages)); - } - var pointToBytes = (point) => point.toRawBytes(true).slice(1); - var numTo32b = (n) => numberToBytesBE(n, 32); - var modP = (x) => mod(x, secp256k1P); - var modN = (x) => mod(x, secp256k1N); - var Point = secp256k1.ProjectivePoint; - var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); - function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; - } - function lift_x(x) { - if (!fe(x)) - throw new Error("bad x: need 0 < x < p"); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); - const p = new Point(x, y, _1n5); - p.assertValidity(); - return p; - } - function challenge(...args) { - return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); - } - function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; - } - function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(bytesToNumberBE(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; - } - function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); - const r = bytesToNumberBE(sig.subarray(0, 32)); - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; - } - } - var schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } - }))(); - - // node_modules/@noble/hashes/esm/crypto.js - var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - - // node_modules/@noble/hashes/esm/utils.js - var u8a3 = (a) => a instanceof Uint8Array; - var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr2 = (word, shift) => word << 32 - shift | word >>> shift; - var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE2) - throw new Error("Non little-endian hardware is not supported"); - var hexes2 = Array.from({ length: 256 }, (v, i2) => i2.toString(16).padStart(2, "0")); - function bytesToHex2(bytes3) { - if (!u8a3(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i2 = 0; i2 < bytes3.length; i2++) { - hex2 += hexes2[bytes3[i2]]; - } - return hex2; - } - function hexToBytes2(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; - } - function utf8ToBytes3(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes3(data); - if (!u8a3(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - var Hash2 = class { - clone() { - return this._cloneInto(); - } - }; - function wrapConstructor2(hashCons) { - const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - - // node_modules/@noble/hashes/esm/_assert.js - function number2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bool(b) { - if (typeof b !== "boolean") - throw new Error(`Expected boolean, not ${b}`); - } - function bytes2(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash2(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number2(hash3.outputLen); - number2(hash3.blockLen); - } - function exists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output2(out, instance) { - bytes2(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - var assert = { - number: number2, - bool, - bytes: bytes2, - hash: hash2, - exists: exists2, - output: output2 - }; - var assert_default = assert; - - // node_modules/@noble/hashes/esm/_sha2.js - function setBigUint642(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl, isLE3); - } - var SHA22 = class extends Hash2 { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView2(this.buffer); - } - update(data) { - assert_default.exists(this); - const { view, buffer, blockLen } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView2(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.output(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer[i2] = 0; - setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView2(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE3); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - }; - - // node_modules/@noble/hashes/esm/sha256.js - var Chi2 = (a, b, c) => a & b ^ ~a & c; - var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c; - var SHA256_K2 = 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 - ]); - var IV2 = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - var SHA256_W2 = new Uint32Array(64); - var SHA2562 = class extends SHA22 { - constructor() { - super(64, 32, 8, false); - this.A = IV2[0] | 0; - this.B = IV2[1] | 0; - this.C = IV2[2] | 0; - this.D = IV2[3] | 0; - this.E = IV2[4] | 0; - this.F = IV2[5] | 0; - this.G = IV2[6] | 0; - this.H = IV2[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W2[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W2[i2 - 15]; - const W2 = SHA256_W2[i2 - 2]; - const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; - const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; - SHA256_W2[i2] = s1 + SHA256_W2[i2 - 7] + s0 + SHA256_W2[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); - const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i2] + SHA256_W2[i2] | 0; - const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); - const T2 = sigma0 + Maj2(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W2.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - }; - var SHA224 = class extends SHA2562 { - constructor() { - super(); - this.A = 3238371032 | 0; - this.B = 914150663 | 0; - this.C = 812702999 | 0; - this.D = 4144912697 | 0; - this.E = 4290775857 | 0; - this.F = 1750603025 | 0; - this.G = 1694076839 | 0; - this.H = 3204075428 | 0; - this.outputLen = 28; - } - }; - var sha2562 = wrapConstructor2(() => new SHA2562()); - var sha224 = wrapConstructor2(() => new SHA224()); - - // node_modules/nostr-tools/lib/esm/pool.js - var verifiedSymbol = Symbol("verified"); - var isRecord = (obj) => obj instanceof Object; - function validateEvent(event) { - if (!isRecord(event)) - return false; - if (typeof event.kind !== "number") - return false; - if (typeof event.content !== "string") - return false; - if (typeof event.created_at !== "number") - return false; - if (typeof event.pubkey !== "string") - return false; - if (!event.pubkey.match(/^[a-f0-9]{64}$/)) - return false; - if (!Array.isArray(event.tags)) - return false; - for (let i2 = 0; i2 < event.tags.length; i2++) { - let tag = event.tags[i2]; - if (!Array.isArray(tag)) - return false; - for (let j = 0; j < tag.length; j++) { - if (typeof tag[j] === "object") - return false; - } - } - return true; - } - var utf8Decoder = new TextDecoder("utf-8"); - var utf8Encoder = new TextEncoder(); - function normalizeURL(url) { - if (url.indexOf("://") === -1) - url = "wss://" + url; - let p = new URL(url); - p.pathname = p.pathname.replace(/\/+/g, "/"); - if (p.pathname.endsWith("/")) - p.pathname = p.pathname.slice(0, -1); - if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") - p.port = ""; - p.searchParams.sort(); - p.hash = ""; - return p.toString(); - } - var QueueNode = class { - value; - next = null; - prev = null; - constructor(message) { - this.value = message; - } - }; - var Queue = class { - first; - last; - constructor() { - this.first = null; - this.last = null; - } - enqueue(value) { - const newNode = new QueueNode(value); - if (!this.last) { - this.first = newNode; - this.last = newNode; - } else if (this.last === this.first) { - this.last = newNode; - this.last.prev = this.first; - this.first.next = newNode; - } else { - newNode.prev = this.last; - this.last.next = newNode; - this.last = newNode; - } - return true; - } - dequeue() { - if (!this.first) - return null; - if (this.first === this.last) { - const target2 = this.first; - this.first = null; - this.last = null; - return target2.value; - } - const target = this.first; - this.first = target.next; - return target.value; - } - }; - var JS = class { - generateSecretKey() { - return schnorr.utils.randomPrivateKey(); - } - getPublicKey(secretKey) { - return bytesToHex2(schnorr.getPublicKey(secretKey)); - } - finalizeEvent(t, secretKey) { - const event = t; - event.pubkey = bytesToHex2(schnorr.getPublicKey(secretKey)); - event.id = getEventHash(event); - event.sig = bytesToHex2(schnorr.sign(getEventHash(event), secretKey)); - event[verifiedSymbol] = true; - return event; - } - verifyEvent(event) { - if (typeof event[verifiedSymbol] === "boolean") - return event[verifiedSymbol]; - const hash3 = getEventHash(event); - if (hash3 !== event.id) { - event[verifiedSymbol] = false; - return false; - } - try { - const valid = schnorr.verify(event.sig, hash3, event.pubkey); - event[verifiedSymbol] = valid; - return valid; - } catch (err) { - event[verifiedSymbol] = false; - return false; - } - } - }; - function serializeEvent(evt) { - if (!validateEvent(evt)) - throw new Error("can't serialize event with wrong or missing properties"); - return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); - } - function getEventHash(event) { - let eventHash = sha2562(utf8Encoder.encode(serializeEvent(event))); - return bytesToHex2(eventHash); - } - var i = new JS(); - var generateSecretKey = i.generateSecretKey; - var getPublicKey = i.getPublicKey; - var finalizeEvent = i.finalizeEvent; - var verifyEvent = i.verifyEvent; - var ClientAuth = 22242; - function matchFilter(filter, event) { - if (filter.ids && filter.ids.indexOf(event.id) === -1) { - return false; - } - if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { - return false; - } - if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { - return false; - } - for (let f in filter) { - if (f[0] === "#") { - let tagName = f.slice(1); - let values = filter[`#${tagName}`]; - if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) - return false; - } - } - if (filter.since && event.created_at < filter.since) - return false; - if (filter.until && event.created_at > filter.until) - return false; - return true; - } - function matchFilters(filters, event) { - for (let i2 = 0; i2 < filters.length; i2++) { - if (matchFilter(filters[i2], event)) { - return true; - } - } - return false; - } - function getHex64(json, field) { - let len = field.length + 3; - let idx = json.indexOf(`"${field}":`) + len; - let s = json.slice(idx).indexOf(`"`) + idx + 1; - return json.slice(s, s + 64); - } - function getSubscriptionId(json) { - let idx = json.slice(0, 22).indexOf(`"EVENT"`); - if (idx === -1) - return null; - let pstart = json.slice(idx + 7 + 1).indexOf(`"`); - if (pstart === -1) - return null; - let start = idx + 7 + 1 + pstart; - let pend = json.slice(start + 1, 80).indexOf(`"`); - if (pend === -1) - return null; - let end = start + 1 + pend; - return json.slice(start + 1, end); - } - function makeAuthEvent(relayURL, challenge2) { - return { - kind: ClientAuth, - created_at: Math.floor(Date.now() / 1e3), - tags: [ - ["relay", relayURL], - ["challenge", challenge2] - ], - content: "" - }; - } - async function yieldThread() { - return new Promise((resolve) => { - const ch = new MessageChannel(); - const handler = () => { - ch.port1.removeEventListener("message", handler); - resolve(); - }; - ch.port1.addEventListener("message", handler); - ch.port2.postMessage(0); - ch.port1.start(); - }); - } - var alwaysTrue = (t) => { - t[verifiedSymbol] = true; - return true; - }; - var AbstractRelay = class { - url; - _connected = false; - onclose = null; - onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); - _onauth = null; - baseEoseTimeout = 4400; - connectionTimeout = 4400; - openSubs = /* @__PURE__ */ new Map(); - connectionTimeoutHandle; - connectionPromise; - openCountRequests = /* @__PURE__ */ new Map(); - openEventPublishes = /* @__PURE__ */ new Map(); - ws; - incomingMessageQueue = new Queue(); - queueRunning = false; - challenge; - serial = 0; - verifyEvent; - _WebSocket; - constructor(url, opts) { - this.url = normalizeURL(url); - this.verifyEvent = opts.verifyEvent; - this._WebSocket = opts.websocketImplementation || WebSocket; - } - static async connect(url, opts) { - const relay = new AbstractRelay(url, opts); - await relay.connect(); - return relay; - } - closeAllSubscriptions(reason) { - for (let [_, sub] of this.openSubs) { - sub.close(reason); - } - this.openSubs.clear(); - for (let [_, ep] of this.openEventPublishes) { - ep.reject(new Error(reason)); - } - this.openEventPublishes.clear(); - for (let [_, cr] of this.openCountRequests) { - cr.reject(new Error(reason)); - } - this.openCountRequests.clear(); - } - get connected() { - return this._connected; - } - async connect() { - if (this.connectionPromise) - return this.connectionPromise; - this.challenge = void 0; - this.connectionPromise = new Promise((resolve, reject) => { - this.connectionTimeoutHandle = setTimeout(() => { - reject("connection timed out"); - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection timed out"); - }, this.connectionTimeout); - try { - this.ws = new this._WebSocket(this.url); - } catch (err) { - reject(err); - return; - } - this.ws.onopen = () => { - clearTimeout(this.connectionTimeoutHandle); - this._connected = true; - resolve(); - }; - this.ws.onerror = (ev) => { - reject(ev.message || "websocket error"); - if (this._connected) { - this._connected = false; - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection errored"); - } - }; - this.ws.onclose = async () => { - if (this._connected) { - this._connected = false; - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection closed"); - } - }; - this.ws.onmessage = this._onmessage.bind(this); - }); - return this.connectionPromise; - } - async runQueue() { - this.queueRunning = true; - while (true) { - if (false === this.handleNext()) { - break; - } - await yieldThread(); - } - this.queueRunning = false; - } - handleNext() { - const json = this.incomingMessageQueue.dequeue(); - if (!json) { - return false; - } - const subid = getSubscriptionId(json); - if (subid) { - const so = this.openSubs.get(subid); - if (!so) { - return; - } - const id = getHex64(json, "id"); - const alreadyHave = so.alreadyHaveEvent?.(id); - so.receivedEvent?.(this, id); - if (alreadyHave) { - return; - } - } - try { - let data = JSON.parse(json); - switch (data[0]) { - case "EVENT": { - const so = this.openSubs.get(data[1]); - const event = data[2]; - if (this.verifyEvent(event) && matchFilters(so.filters, event)) { - so.onevent(event); - } - return; - } - case "COUNT": { - const id = data[1]; - const payload = data[2]; - const cr = this.openCountRequests.get(id); - if (cr) { - cr.resolve(payload.count); - this.openCountRequests.delete(id); - } - return; - } - case "EOSE": { - const so = this.openSubs.get(data[1]); - if (!so) - return; - so.receivedEose(); - return; - } - case "OK": { - const id = data[1]; - const ok = data[2]; - const reason = data[3]; - const ep = this.openEventPublishes.get(id); - if (ok) - ep.resolve(reason); - else - ep.reject(new Error(reason)); - this.openEventPublishes.delete(id); - return; - } - case "CLOSED": { - const id = data[1]; - const so = this.openSubs.get(id); - if (!so) - return; - so.closed = true; - so.close(data[2]); - return; - } - case "NOTICE": - this.onnotice(data[1]); - return; - case "AUTH": { - this.challenge = data[1]; - this._onauth?.(data[1]); - return; - } - } - } catch (err) { - return; - } - } - async send(message) { - if (!this.connectionPromise) - throw new Error("sending on closed connection"); - this.connectionPromise.then(() => { - this.ws?.send(message); - }); - } - async auth(signAuthEvent) { - if (!this.challenge) - throw new Error("can't perform auth, no challenge was received"); - const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge)); - const ret = new Promise((resolve, reject) => { - this.openEventPublishes.set(evt.id, { resolve, reject }); - }); - this.send('["AUTH",' + JSON.stringify(evt) + "]"); - return ret; - } - async publish(event) { - const ret = new Promise((resolve, reject) => { - this.openEventPublishes.set(event.id, { resolve, reject }); - }); - this.send('["EVENT",' + JSON.stringify(event) + "]"); - return ret; - } - async count(filters, params) { - this.serial++; - const id = params?.id || "count:" + this.serial; - const ret = new Promise((resolve, reject) => { - this.openCountRequests.set(id, { resolve, reject }); - }); - this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); - return ret; - } - subscribe(filters, params) { - const subscription = this.prepareSubscription(filters, params); - subscription.fire(); - return subscription; - } - prepareSubscription(filters, params) { - this.serial++; - const id = params.id || "sub:" + this.serial; - const subscription = new Subscription(this, id, filters, params); - this.openSubs.set(id, subscription); - return subscription; - } - close() { - this.closeAllSubscriptions("relay connection closed by us"); - this._connected = false; - this.ws?.close(); - } - _onmessage(ev) { - this.incomingMessageQueue.enqueue(ev.data); - if (!this.queueRunning) { - this.runQueue(); - } - } - }; - var Subscription = class { - relay; - id; - closed = false; - eosed = false; - filters; - alreadyHaveEvent; - receivedEvent; - onevent; - oneose; - onclose; - eoseTimeout; - eoseTimeoutHandle; - constructor(relay, id, filters, params) { - this.relay = relay; - this.filters = filters; - this.id = id; - this.alreadyHaveEvent = params.alreadyHaveEvent; - this.receivedEvent = params.receivedEvent; - this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; - this.oneose = params.oneose; - this.onclose = params.onclose; - this.onevent = params.onevent || ((event) => { - console.warn( - `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, - event - ); - }); - } - fire() { - this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); - this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); - } - receivedEose() { - if (this.eosed) - return; - clearTimeout(this.eoseTimeoutHandle); - this.eosed = true; - this.oneose?.(); - } - close(reason = "closed by caller") { - if (!this.closed && this.relay.connected) { - this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); - this.closed = true; - } - this.relay.openSubs.delete(this.id); - this.onclose?.(reason); - } - }; - var AbstractSimplePool = class { - relays = /* @__PURE__ */ new Map(); - seenOn = /* @__PURE__ */ new Map(); - trackRelays = false; - verifyEvent; - trustedRelayURLs = /* @__PURE__ */ new Set(); - _WebSocket; - constructor(opts) { - this.verifyEvent = opts.verifyEvent; - this._WebSocket = opts.websocketImplementation; - } - async ensureRelay(url, params) { - url = normalizeURL(url); - let relay = this.relays.get(url); - if (!relay) { - relay = new AbstractRelay(url, { - verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, - websocketImplementation: this._WebSocket - }); - if (params?.connectionTimeout) - relay.connectionTimeout = params.connectionTimeout; - this.relays.set(url, relay); - } - await relay.connect(); - return relay; - } - close(relays) { - relays.map(normalizeURL).forEach((url) => { - this.relays.get(url)?.close(); - }); - } - subscribeMany(relays, filters, params) { - return this.subscribeManyMap(Object.fromEntries(relays.map((url) => [url, filters])), params); - } - subscribeManyMap(requests, params) { - if (this.trackRelays) { - params.receivedEvent = (relay, id) => { - let set = this.seenOn.get(id); - if (!set) { - set = /* @__PURE__ */ new Set(); - this.seenOn.set(id, set); - } - set.add(relay); - }; - } - const _knownIds = /* @__PURE__ */ new Set(); - const subs = []; - const relaysLength = Object.keys(requests).length; - const eosesReceived = []; - let handleEose = (i2) => { - eosesReceived[i2] = true; - if (eosesReceived.filter((a) => a).length === relaysLength) { - params.oneose?.(); - handleEose = () => { - }; - } - }; - const closesReceived = []; - let handleClose = (i2, reason) => { - handleEose(i2); - closesReceived[i2] = reason; - if (closesReceived.filter((a) => a).length === relaysLength) { - params.onclose?.(closesReceived); - handleClose = () => { - }; - } - }; - const localAlreadyHaveEventHandler = (id) => { - if (params.alreadyHaveEvent?.(id)) { - return true; - } - const have = _knownIds.has(id); - _knownIds.add(id); - return have; - }; - const allOpened = Promise.all( - Object.entries(requests).map(async (req, i2, arr) => { - if (arr.indexOf(req) !== i2) { - handleClose(i2, "duplicate url"); - return; - } - let [url, filters] = req; - url = normalizeURL(url); - let relay; - try { - relay = await this.ensureRelay(url, { - connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 - }); - } catch (err) { - handleClose(i2, err?.message || String(err)); - return; - } - let subscription = relay.subscribe(filters, { - ...params, - oneose: () => handleEose(i2), - onclose: (reason) => handleClose(i2, reason), - alreadyHaveEvent: localAlreadyHaveEventHandler, - eoseTimeout: params.maxWait - }); - subs.push(subscription); - }) - ); - return { - async close() { - await allOpened; - subs.forEach((sub) => { - sub.close(); - }); - } - }; - } - subscribeManyEose(relays, filters, params) { - const subcloser = this.subscribeMany(relays, filters, { - ...params, - oneose() { - subcloser.close(); - } - }); - return subcloser; - } - async querySync(relays, filter, params) { - return new Promise(async (resolve) => { - const events = []; - this.subscribeManyEose(relays, [filter], { - ...params, - onevent(event) { - events.push(event); - }, - onclose(_) { - resolve(events); - } - }); - }); - } - async get(relays, filter, params) { - filter.limit = 1; - const events = await this.querySync(relays, filter, params); - events.sort((a, b) => b.created_at - a.created_at); - return events[0] || null; - } - publish(relays, event) { - return relays.map(normalizeURL).map(async (url, i2, arr) => { - if (arr.indexOf(url) !== i2) { - return Promise.reject("duplicate url"); - } - let r = await this.ensureRelay(url); - return r.publish(event); - }); - } - }; - var _WebSocket; - try { - _WebSocket = WebSocket; - } catch { - } - var SimplePool = class extends AbstractSimplePool { - constructor() { - super({ verifyEvent, websocketImplementation: _WebSocket }); - } - }; - - // node_modules/@scure/base/lib/esm/index.js - function assertNumber(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`Wrong integer: ${n}`); - } - function chain(...args) { - const wrap = (a, b) => (c) => a(b(c)); - const encode = Array.from(args).reverse().reduce((acc, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0); - const decode2 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0); - return { encode, decode: decode2 }; - } - function alphabet(alphabet2) { - return { - encode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("alphabet.encode input should be an array of numbers"); - return digits.map((i2) => { - assertNumber(i2); - if (i2 < 0 || i2 >= alphabet2.length) - throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet2.length})`); - return alphabet2[i2]; - }); - }, - decode: (input) => { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("alphabet.decode input should be array of strings"); - return input.map((letter) => { - if (typeof letter !== "string") - throw new Error(`alphabet.decode: not string element=${letter}`); - const index = alphabet2.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`); - return index; - }); - } - }; - } - function join(separator = "") { - if (typeof separator !== "string") - throw new Error("join separator should be string"); - return { - encode: (from) => { - if (!Array.isArray(from) || from.length && typeof from[0] !== "string") - throw new Error("join.encode input should be array of strings"); - for (let i2 of from) - if (typeof i2 !== "string") - throw new Error(`join.encode: non-string input=${i2}`); - return from.join(separator); - }, - decode: (to) => { - if (typeof to !== "string") - throw new Error("join.decode input should be string"); - return to.split(separator); - } - }; - } - function padding(bits, chr = "=") { - assertNumber(bits); - if (typeof chr !== "string") - throw new Error("padding chr should be string"); - return { - encode(data) { - if (!Array.isArray(data) || data.length && typeof data[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i2 of data) - if (typeof i2 !== "string") - throw new Error(`padding.encode: non-string input=${i2}`); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i2 of input) - if (typeof i2 !== "string") - throw new Error(`padding.decode: non-string input=${i2}`); - let end = input.length; - if (end * bits % 8) - throw new Error("Invalid padding: string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - if (!((end - 1) * bits % 8)) - throw new Error("Invalid padding: string has too much padding"); - } - return input.slice(0, end); - } - }; - } - function normalize(fn) { - if (typeof fn !== "function") - throw new Error("normalize fn should be function"); - return { encode: (from) => from, decode: (to) => fn(to) }; - } - function convertRadix(data, from, to) { - if (from < 2) - throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); - if (!Array.isArray(data)) - throw new Error("convertRadix: data should be array"); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data); - digits.forEach((d) => { - assertNumber(d); - if (d < 0 || d >= from) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i2 = pos; i2 < digits.length; i2++) { - const digit = digits[i2]; - const digitBase = from * carry + digit; - if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) { - throw new Error("convertRadix: carry overflow"); - } - carry = digitBase % to; - digits[i2] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!digits[i2]) - pos = i2; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) - res.push(0); - return res.reverse(); - } - var gcd = (a, b) => !b ? a : gcd(b, a % b); - var radix2carry = (from, to) => from + (to - gcd(from, to)); - function convertRadix2(data, from, to, padding2) { - if (!Array.isArray(data)) - throw new Error("convertRadix2: data should be array"); - if (from <= 0 || from > 32) - throw new Error(`convertRadix2: wrong from=${from}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry(from, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber(n); - if (n >= 2 ** from) - throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); - carry = carry << from | n; - if (pos + from > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); - pos += from; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = carry << to - pos & mask; - if (!padding2 && pos >= from) - throw new Error("Excess padding"); - if (!padding2 && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding2 && pos > 0) - res.push(carry >>> 0); - return res; - } - function radix(num) { - assertNumber(num); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes3), 2 ** 8, num); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix.decode input should be array of strings"); - return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); - } - }; - } - function radix2(bits, revPadding = false) { - assertNumber(bits); - if (bits <= 0 || bits > 32) - throw new Error("radix2: bits should be in (0..32]"); - if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) - throw new Error("radix2: carry overflow"); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes3), 8, bits, !revPadding); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix2.decode input should be array of strings"); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - } - }; - } - function unsafeWrapper(fn) { - if (typeof fn !== "function") - throw new Error("unsafeWrapper fn should be function"); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; - } - var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); - var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join("")); - var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join("")); - var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); - var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join("")); - var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join("")); - var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); - var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; - var base58xmr = { - encode(data) { - let res = ""; - for (let i2 = 0; i2 < data.length; i2 += 8) { - const block = data.subarray(i2, i2 + 8); - res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i2 = 0; i2 < str.length; i2 += 11) { - const slice = str.slice(i2, i2 + 11); - const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); - const block = base58.decode(slice); - for (let j = 0; j < block.length - blockLen; j++) { - if (block[j] !== 0) - throw new Error("base58xmr: wrong padding"); - } - res = res.concat(Array.from(block.slice(block.length - blockLen))); - } - return Uint8Array.from(res); - } - }; - var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join("")); - var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; - function bech32Polymod(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) { - if ((b >> i2 & 1) === 1) - chk ^= POLYMOD_GENERATORS[i2]; - } - return chk; - } - function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i2 = 0; i2 < len; i2++) { - const c = prefix.charCodeAt(i2); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ c >> 5; - } - chk = bech32Polymod(chk); - for (let i2 = 0; i2 < len; i2++) - chk = bech32Polymod(chk) ^ prefix.charCodeAt(i2) & 31; - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i2 = 0; i2 < 6; i2++) - chk = bech32Polymod(chk); - chk ^= encodingConst; - return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); - } - function genBech32(encoding) { - const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; - const _words = radix2(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper(fromWords); - function encode(prefix, words, limit = 90) { - if (typeof prefix !== "string") - throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); - if (!Array.isArray(words) || words.length && typeof words[0] !== "number") - throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); - const actualLength = prefix.length + 7 + words.length; - if (limit !== false && actualLength > limit) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; - } - function decode2(str, limit = 90) { - if (typeof str !== "string") - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || limit !== false && str.length > limit) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - str = lowered; - const sepIndex = str.lastIndexOf("1"); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = str.slice(0, sepIndex); - const _words2 = str.slice(sepIndex + 1); - if (_words2.length < 6) - throw new Error("Data must be at least 6 characters long"); - const words = BECH_ALPHABET.decode(_words2).slice(0, -6); - const sum = bechChecksum(prefix, words, ENCODING_CONST); - if (!_words2.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper(decode2); - function decodeToBytes(str) { - const { prefix, words } = decode2(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; - } - var bech32 = genBech32("bech32"); - var bech32m = genBech32("bech32m"); - var utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str) - }; - var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => { - if (typeof s !== "string" || s.length % 2) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); - })); - var CODERS = { - utf8, - hex, - base16, - base32, - base64, - base64url, - base58, - base58xmr - }; - var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; - - // node_modules/nostr-tools/lib/esm/nip19.js - var utf8Decoder2 = new TextDecoder("utf-8"); - var utf8Encoder2 = new TextEncoder(); - var Bech32MaxSize = 5e3; - function decode(nip19) { - let { prefix, words } = bech32.decode(nip19, Bech32MaxSize); - let data = new Uint8Array(bech32.fromWords(words)); - switch (prefix) { - case "nprofile": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nprofile"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - return { - type: "nprofile", - data: { - pubkey: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [] - } - }; - } - case "nevent": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nevent"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - if (tlv[2] && tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (tlv[3] && tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "nevent", - data: { - id: bytesToHex2(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [], - author: tlv[2]?.[0] ? bytesToHex2(tlv[2][0]) : void 0, - kind: tlv[3]?.[0] ? parseInt(bytesToHex2(tlv[3][0]), 16) : void 0 - } - }; - } - case "naddr": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for naddr"); - if (!tlv[2]?.[0]) - throw new Error("missing TLV 2 for naddr"); - if (tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (!tlv[3]?.[0]) - throw new Error("missing TLV 3 for naddr"); - if (tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "naddr", - data: { - identifier: utf8Decoder2.decode(tlv[0][0]), - pubkey: bytesToHex2(tlv[2][0]), - kind: parseInt(bytesToHex2(tlv[3][0]), 16), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder2.decode(d)) : [] - } - }; - } - case "nrelay": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nrelay"); - return { - type: "nrelay", - data: utf8Decoder2.decode(tlv[0][0]) - }; - } - case "nsec": - return { type: prefix, data }; - case "npub": - case "note": - return { type: prefix, data: bytesToHex2(data) }; - default: - throw new Error(`unknown prefix ${prefix}`); - } - } - function parseTLV(data) { - let result = {}; - let rest = data; - while (rest.length > 0) { - let t = rest[0]; - let l = rest[1]; - let v = rest.slice(2, 2 + l); - rest = rest.slice(2 + l); - if (v.length < l) - throw new Error(`not enough data to read on TLV ${t}`); - result[t] = result[t] || []; - result[t].push(v); - } - return result; - } - function npubEncode(hex2) { - return encodeBytes("npub", hexToBytes2(hex2)); - } - function encodeBech32(prefix, data) { - let words = bech32.toWords(data); - return bech32.encode(prefix, words, Bech32MaxSize); - } - function encodeBytes(prefix, bytes3) { - return encodeBech32(prefix, bytes3); - } - - // node_modules/nostr-tools/lib/esm/nip05.js - var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; - var _fetch; - try { - _fetch = fetch; - } catch { - } - async function queryProfile(fullname) { - const match = fullname.match(NIP05_REGEX); - if (!match) - return null; - const [_, name = "_", domain] = match; - try { - const url = `https://${domain}/.well-known/nostr.json?name=${name}`; - const res = await (await _fetch(url, { redirect: "error" })).json(); - let pubkey = res.names[name]; - return pubkey ? { pubkey, relays: res.relays?.[pubkey] } : null; - } catch (_e) { - return null; - } - } - - // metadata.ts - var import_lru_cache = __toESM(require_lru_cache(), 1); - var pool = window.nostrSharedPool || new SimplePool(); - var metadataCache = window.nostrMetadataCache || new import_lru_cache.default(2e3); - function fetchMetadata(pubkey, hints) { - let metadata = metadataCache.get(pubkey); - if (metadata) - return metadata; - const relays = ["wss://purplepag.es", "wss://user.kindpag.es", "wss://relay.nos.social"]; - relays.push(...hints); - let promise = new Promise( - (resolve, reject) => pool.subscribeManyEose( - relays, - [ - { - kinds: [0], - authors: [pubkey] - } - ], - { - onevent(evt) { - try { - resolve(JSON.parse(evt.content)); - } catch (err) { - } - }, - onclose: reject - } - ) - ); - metadataCache.set(pubkey, promise); - return promise; - } - async function inputToPubkey(input) { - try { - const { type, data } = decode(input); - if (type === "nprofile") { - return [data.pubkey, data.relays || []]; - } else if (type === "npub") { - return [data, []]; - } - } catch (err) { - if (input.match(/[0-9a-f]{64}/)) { - return [input, []]; - } else if (input.match(".")) { - let res = await queryProfile(input); - if (!res) - return [void 0]; - return [res.pubkey, res.relays || []]; - } - } - return [void 0]; - } - function getShortName(pubkey, metadata) { - let name = metadata.name || metadata.display_name; - if (name) - return name; - let npub = npubEncode(pubkey); - return shortenNpub(npub); - } - function shortenNpub(npub) { - return npub.substring(0, 7) + "\u2026" + npub.substring(57); - } - - // nostr-name.ts - var import_debounce = __toESM(require_debounce(), 1); - var NostrName = class extends HTMLElement { - constructor() { - super(); - this.set(); - } - connectedCallback() { - this.set(); - } - attributeChangedCallback() { - this.set(); - } - set = (0, import_debounce.default)(async () => { - let input = this.getAttribute("pubkey"); - if (input) { - let [pubkey, hints] = await inputToPubkey(input); - if (pubkey) { - let metadata = await fetchMetadata(pubkey, hints || []); - this.textContent = getShortName(pubkey, metadata); - } - } - }, 200); - }; - __publicField(NostrName, "observedAttributes", ["pubkey"]); - window.customElements.define("nostr-name", NostrName); -})(); diff --git a/public/lib/nostr-picture.js b/public/lib/nostr-picture.js deleted file mode 100644 index 3590e41..0000000 --- a/public/lib/nostr-picture.js +++ /dev/null @@ -1,4050 +0,0 @@ -"use strict"; -(() => { - var __create = Object.create; - var __defProp = Object.defineProperty; - var __getOwnPropDesc = Object.getOwnPropertyDescriptor; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __getProtoOf = Object.getPrototypeOf; - var __hasOwnProp = Object.prototype.hasOwnProperty; - var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; - var __commonJS = (cb, mod2) => function __require() { - return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; - }; - var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; - }; - var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( - isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, - mod2 - )); - var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; - }; - - // node_modules/obliterator/iterator.js - var require_iterator = __commonJS({ - "node_modules/obliterator/iterator.js"(exports, module) { - function Iterator(next) { - if (typeof next !== "function") - throw new Error("obliterator/iterator: expecting a function!"); - this.next = next; - } - if (typeof Symbol !== "undefined") - Iterator.prototype[Symbol.iterator] = function() { - return this; - }; - Iterator.of = function() { - var args = arguments, l = args.length, i2 = 0; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - return { done: false, value: args[i2++] }; - }); - }; - Iterator.empty = function() { - var iterator = new Iterator(function() { - return { done: true }; - }); - return iterator; - }; - Iterator.fromSequence = function(sequence) { - var i2 = 0, l = sequence.length; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - return { done: false, value: sequence[i2++] }; - }); - }; - Iterator.is = function(value) { - if (value instanceof Iterator) - return true; - return typeof value === "object" && value !== null && typeof value.next === "function"; - }; - module.exports = Iterator; - } - }); - - // node_modules/obliterator/support.js - var require_support = __commonJS({ - "node_modules/obliterator/support.js"(exports) { - exports.ARRAY_BUFFER_SUPPORT = typeof ArrayBuffer !== "undefined"; - exports.SYMBOL_SUPPORT = typeof Symbol !== "undefined"; - } - }); - - // node_modules/obliterator/foreach.js - var require_foreach = __commonJS({ - "node_modules/obliterator/foreach.js"(exports, module) { - var support = require_support(); - var ARRAY_BUFFER_SUPPORT = support.ARRAY_BUFFER_SUPPORT; - var SYMBOL_SUPPORT = support.SYMBOL_SUPPORT; - module.exports = function forEach(iterable, callback) { - var iterator, k, i2, l, s; - if (!iterable) - throw new Error("obliterator/forEach: invalid iterable."); - if (typeof callback !== "function") - throw new Error("obliterator/forEach: expecting a callback."); - if (Array.isArray(iterable) || ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable) || typeof iterable === "string" || iterable.toString() === "[object Arguments]") { - for (i2 = 0, l = iterable.length; i2 < l; i2++) - callback(iterable[i2], i2); - return; - } - if (typeof iterable.forEach === "function") { - iterable.forEach(callback); - return; - } - if (SYMBOL_SUPPORT && Symbol.iterator in iterable && typeof iterable.next !== "function") { - iterable = iterable[Symbol.iterator](); - } - if (typeof iterable.next === "function") { - iterator = iterable; - i2 = 0; - while (s = iterator.next(), s.done !== true) { - callback(s.value, i2); - i2++; - } - return; - } - for (k in iterable) { - if (iterable.hasOwnProperty(k)) { - callback(iterable[k], k); - } - } - return; - }; - } - }); - - // node_modules/mnemonist/utils/typed-arrays.js - var require_typed_arrays = __commonJS({ - "node_modules/mnemonist/utils/typed-arrays.js"(exports) { - var MAX_8BIT_INTEGER = Math.pow(2, 8) - 1; - var MAX_16BIT_INTEGER = Math.pow(2, 16) - 1; - var MAX_32BIT_INTEGER = Math.pow(2, 32) - 1; - var MAX_SIGNED_8BIT_INTEGER = Math.pow(2, 7) - 1; - var MAX_SIGNED_16BIT_INTEGER = Math.pow(2, 15) - 1; - var MAX_SIGNED_32BIT_INTEGER = Math.pow(2, 31) - 1; - exports.getPointerArray = function(size) { - var maxIndex = size - 1; - if (maxIndex <= MAX_8BIT_INTEGER) - return Uint8Array; - if (maxIndex <= MAX_16BIT_INTEGER) - return Uint16Array; - if (maxIndex <= MAX_32BIT_INTEGER) - return Uint32Array; - throw new Error("mnemonist: Pointer Array of size > 4294967295 is not supported."); - }; - exports.getSignedPointerArray = function(size) { - var maxIndex = size - 1; - if (maxIndex <= MAX_SIGNED_8BIT_INTEGER) - return Int8Array; - if (maxIndex <= MAX_SIGNED_16BIT_INTEGER) - return Int16Array; - if (maxIndex <= MAX_SIGNED_32BIT_INTEGER) - return Int32Array; - return Float64Array; - }; - exports.getNumberType = function(value) { - if (value === (value | 0)) { - if (Math.sign(value) === -1) { - if (value <= 127 && value >= -128) - return Int8Array; - if (value <= 32767 && value >= -32768) - return Int16Array; - return Int32Array; - } else { - if (value <= 255) - return Uint8Array; - if (value <= 65535) - return Uint16Array; - return Uint32Array; - } - } - return Float64Array; - }; - var TYPE_PRIORITY = { - Uint8Array: 1, - Int8Array: 2, - Uint16Array: 3, - Int16Array: 4, - Uint32Array: 5, - Int32Array: 6, - Float32Array: 7, - Float64Array: 8 - }; - exports.getMinimalRepresentation = function(array, getter) { - var maxType = null, maxPriority = 0, p, t, v, i2, l; - for (i2 = 0, l = array.length; i2 < l; i2++) { - v = getter ? getter(array[i2]) : array[i2]; - t = exports.getNumberType(v); - p = TYPE_PRIORITY[t.name]; - if (p > maxPriority) { - maxPriority = p; - maxType = t; - } - } - return maxType; - }; - exports.isTypedArray = function(value) { - return typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(value); - }; - exports.concat = function() { - var length = 0, i2, o, l; - for (i2 = 0, l = arguments.length; i2 < l; i2++) - length += arguments[i2].length; - var array = new arguments[0].constructor(length); - for (i2 = 0, o = 0; i2 < l; i2++) { - array.set(arguments[i2], o); - o += arguments[i2].length; - } - return array; - }; - exports.indices = function(length) { - var PointerArray = exports.getPointerArray(length); - var array = new PointerArray(length); - for (var i2 = 0; i2 < length; i2++) - array[i2] = i2; - return array; - }; - } - }); - - // node_modules/mnemonist/utils/iterables.js - var require_iterables = __commonJS({ - "node_modules/mnemonist/utils/iterables.js"(exports) { - var forEach = require_foreach(); - var typed = require_typed_arrays(); - function isArrayLike(target) { - return Array.isArray(target) || typed.isTypedArray(target); - } - function guessLength(target) { - if (typeof target.length === "number") - return target.length; - if (typeof target.size === "number") - return target.size; - return; - } - function toArray(target) { - var l = guessLength(target); - var array = typeof l === "number" ? new Array(l) : []; - var i2 = 0; - forEach(target, function(value) { - array[i2++] = value; - }); - return array; - } - function toArrayWithIndices(target) { - var l = guessLength(target); - var IndexArray = typeof l === "number" ? typed.getPointerArray(l) : Array; - var array = typeof l === "number" ? new Array(l) : []; - var indices = typeof l === "number" ? new IndexArray(l) : []; - var i2 = 0; - forEach(target, function(value) { - array[i2] = value; - indices[i2] = i2++; - }); - return [array, indices]; - } - exports.isArrayLike = isArrayLike; - exports.guessLength = guessLength; - exports.toArray = toArray; - exports.toArrayWithIndices = toArrayWithIndices; - } - }); - - // node_modules/mnemonist/lru-cache.js - var require_lru_cache = __commonJS({ - "node_modules/mnemonist/lru-cache.js"(exports, module) { - var Iterator = require_iterator(); - var forEach = require_foreach(); - var typed = require_typed_arrays(); - var iterables = require_iterables(); - function LRUCache2(Keys, Values, capacity) { - if (arguments.length < 2) { - capacity = Keys; - Keys = null; - Values = null; - } - this.capacity = capacity; - if (typeof this.capacity !== "number" || this.capacity <= 0) - throw new Error("mnemonist/lru-cache: capacity should be positive number."); - else if (!isFinite(this.capacity) || Math.floor(this.capacity) !== this.capacity) - throw new Error("mnemonist/lru-cache: capacity should be a finite positive integer."); - var PointerArray = typed.getPointerArray(capacity); - this.forward = new PointerArray(capacity); - this.backward = new PointerArray(capacity); - this.K = typeof Keys === "function" ? new Keys(capacity) : new Array(capacity); - this.V = typeof Values === "function" ? new Values(capacity) : new Array(capacity); - this.size = 0; - this.head = 0; - this.tail = 0; - this.items = {}; - } - LRUCache2.prototype.clear = function() { - this.size = 0; - this.head = 0; - this.tail = 0; - this.items = {}; - }; - LRUCache2.prototype.splayOnTop = function(pointer) { - var oldHead = this.head; - if (this.head === pointer) - return this; - var previous = this.backward[pointer], next = this.forward[pointer]; - if (this.tail === pointer) { - this.tail = previous; - } else { - this.backward[next] = previous; - } - this.forward[previous] = next; - this.backward[oldHead] = pointer; - this.head = pointer; - this.forward[pointer] = oldHead; - return this; - }; - LRUCache2.prototype.set = function(key, value) { - var pointer = this.items[key]; - if (typeof pointer !== "undefined") { - this.splayOnTop(pointer); - this.V[pointer] = value; - return; - } - if (this.size < this.capacity) { - pointer = this.size++; - } else { - pointer = this.tail; - this.tail = this.backward[pointer]; - delete this.items[this.K[pointer]]; - } - this.items[key] = pointer; - this.K[pointer] = key; - this.V[pointer] = value; - this.forward[pointer] = this.head; - this.backward[this.head] = pointer; - this.head = pointer; - }; - LRUCache2.prototype.setpop = function(key, value) { - var oldValue = null; - var oldKey = null; - var pointer = this.items[key]; - if (typeof pointer !== "undefined") { - this.splayOnTop(pointer); - oldValue = this.V[pointer]; - this.V[pointer] = value; - return { evicted: false, key, value: oldValue }; - } - if (this.size < this.capacity) { - pointer = this.size++; - } else { - pointer = this.tail; - this.tail = this.backward[pointer]; - oldValue = this.V[pointer]; - oldKey = this.K[pointer]; - delete this.items[oldKey]; - } - this.items[key] = pointer; - this.K[pointer] = key; - this.V[pointer] = value; - this.forward[pointer] = this.head; - this.backward[this.head] = pointer; - this.head = pointer; - if (oldKey) { - return { evicted: true, key: oldKey, value: oldValue }; - } else { - return null; - } - }; - LRUCache2.prototype.has = function(key) { - return key in this.items; - }; - LRUCache2.prototype.get = function(key) { - var pointer = this.items[key]; - if (typeof pointer === "undefined") - return; - this.splayOnTop(pointer); - return this.V[pointer]; - }; - LRUCache2.prototype.peek = function(key) { - var pointer = this.items[key]; - if (typeof pointer === "undefined") - return; - return this.V[pointer]; - }; - LRUCache2.prototype.forEach = function(callback, scope) { - scope = arguments.length > 1 ? scope : this; - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, values = this.V, forward = this.forward; - while (i2 < l) { - callback.call(scope, values[pointer], keys[pointer], this); - pointer = forward[pointer]; - i2++; - } - }; - LRUCache2.prototype.keys = function() { - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var key = keys[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value: key - }; - }); - }; - LRUCache2.prototype.values = function() { - var i2 = 0, l = this.size; - var pointer = this.head, values = this.V, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var value = values[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value - }; - }); - }; - LRUCache2.prototype.entries = function() { - var i2 = 0, l = this.size; - var pointer = this.head, keys = this.K, values = this.V, forward = this.forward; - return new Iterator(function() { - if (i2 >= l) - return { done: true }; - var key = keys[pointer], value = values[pointer]; - i2++; - if (i2 < l) - pointer = forward[pointer]; - return { - done: false, - value: [key, value] - }; - }); - }; - if (typeof Symbol !== "undefined") - LRUCache2.prototype[Symbol.iterator] = LRUCache2.prototype.entries; - LRUCache2.prototype.inspect = function() { - var proxy = /* @__PURE__ */ new Map(); - var iterator = this.entries(), step; - while (step = iterator.next(), !step.done) - proxy.set(step.value[0], step.value[1]); - Object.defineProperty(proxy, "constructor", { - value: LRUCache2, - enumerable: false - }); - return proxy; - }; - if (typeof Symbol !== "undefined") - LRUCache2.prototype[Symbol.for("nodejs.util.inspect.custom")] = LRUCache2.prototype.inspect; - LRUCache2.from = function(iterable, Keys, Values, capacity) { - if (arguments.length < 2) { - capacity = iterables.guessLength(iterable); - if (typeof capacity !== "number") - throw new Error("mnemonist/lru-cache.from: could not guess iterable length. Please provide desired capacity as last argument."); - } else if (arguments.length === 2) { - capacity = Keys; - Keys = null; - Values = null; - } - var cache = new LRUCache2(Keys, Values, capacity); - forEach(iterable, function(value, key) { - cache.set(key, value); - }); - return cache; - }; - module.exports = LRUCache2; - } - }); - - // node_modules/debounce/index.js - var require_debounce = __commonJS({ - "node_modules/debounce/index.js"(exports, module) { - function debounce2(function_, wait = 100, options = {}) { - if (typeof function_ !== "function") { - throw new TypeError(`Expected the first parameter to be a function, got \`${typeof function_}\`.`); - } - if (wait < 0) { - throw new RangeError("`wait` must not be negative."); - } - const { immediate } = typeof options === "boolean" ? { immediate: options } : options; - let storedContext; - let storedArguments; - let timeoutId; - let timestamp; - let result; - function run() { - const callContext = storedContext; - const callArguments = storedArguments; - storedContext = void 0; - storedArguments = void 0; - result = function_.apply(callContext, callArguments); - return result; - } - function later() { - const last = Date.now() - timestamp; - if (last < wait && last >= 0) { - timeoutId = setTimeout(later, wait - last); - } else { - timeoutId = void 0; - if (!immediate) { - result = run(); - } - } - } - const debounced = function(...arguments_) { - if (storedContext && this !== storedContext) { - throw new Error("Debounced method called with different contexts."); - } - storedContext = this; - storedArguments = arguments_; - timestamp = Date.now(); - const callNow = immediate && !timeoutId; - if (!timeoutId) { - timeoutId = setTimeout(later, wait); - } - if (callNow) { - result = run(); - } - return result; - }; - debounced.clear = () => { - if (!timeoutId) { - return; - } - clearTimeout(timeoutId); - timeoutId = void 0; - }; - debounced.flush = () => { - if (!timeoutId) { - return; - } - debounced.trigger(); - }; - debounced.trigger = () => { - result = run(); - debounced.clear(); - }; - return debounced; - } - module.exports.debounce = debounce2; - module.exports = debounce2; - } - }); - - // node_modules/@noble/hashes/esm/crypto.js - var crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - - // node_modules/@noble/hashes/esm/utils.js - var u8a = (a) => a instanceof Uint8Array; - var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr = (word, shift) => word << 32 - shift | word >>> shift; - var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE) - throw new Error("Non little-endian hardware is not supported"); - var hexes = Array.from({ length: 256 }, (v, i2) => i2.toString(16).padStart(2, "0")); - function bytesToHex(bytes3) { - if (!u8a(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i2 = 0; i2 < bytes3.length; i2++) { - hex2 += hexes[bytes3[i2]]; - } - return hex2; - } - function hexToBytes(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; - } - function utf8ToBytes(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes(data) { - if (typeof data === "string") - data = utf8ToBytes(data); - if (!u8a(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - var Hash = class { - clone() { - return this._cloneInto(); - } - }; - function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - - // node_modules/@scure/base/lib/esm/index.js - function assertNumber(n) { - if (!Number.isSafeInteger(n)) - throw new Error(`Wrong integer: ${n}`); - } - function chain(...args) { - const wrap = (a, b) => (c) => a(b(c)); - const encode = Array.from(args).reverse().reduce((acc, i2) => acc ? wrap(acc, i2.encode) : i2.encode, void 0); - const decode2 = args.reduce((acc, i2) => acc ? wrap(acc, i2.decode) : i2.decode, void 0); - return { encode, decode: decode2 }; - } - function alphabet(alphabet2) { - return { - encode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("alphabet.encode input should be an array of numbers"); - return digits.map((i2) => { - assertNumber(i2); - if (i2 < 0 || i2 >= alphabet2.length) - throw new Error(`Digit index outside alphabet: ${i2} (alphabet: ${alphabet2.length})`); - return alphabet2[i2]; - }); - }, - decode: (input) => { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("alphabet.decode input should be array of strings"); - return input.map((letter) => { - if (typeof letter !== "string") - throw new Error(`alphabet.decode: not string element=${letter}`); - const index = alphabet2.indexOf(letter); - if (index === -1) - throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`); - return index; - }); - } - }; - } - function join(separator = "") { - if (typeof separator !== "string") - throw new Error("join separator should be string"); - return { - encode: (from) => { - if (!Array.isArray(from) || from.length && typeof from[0] !== "string") - throw new Error("join.encode input should be array of strings"); - for (let i2 of from) - if (typeof i2 !== "string") - throw new Error(`join.encode: non-string input=${i2}`); - return from.join(separator); - }, - decode: (to) => { - if (typeof to !== "string") - throw new Error("join.decode input should be string"); - return to.split(separator); - } - }; - } - function padding(bits, chr = "=") { - assertNumber(bits); - if (typeof chr !== "string") - throw new Error("padding chr should be string"); - return { - encode(data) { - if (!Array.isArray(data) || data.length && typeof data[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i2 of data) - if (typeof i2 !== "string") - throw new Error(`padding.encode: non-string input=${i2}`); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - if (!Array.isArray(input) || input.length && typeof input[0] !== "string") - throw new Error("padding.encode input should be array of strings"); - for (let i2 of input) - if (typeof i2 !== "string") - throw new Error(`padding.decode: non-string input=${i2}`); - let end = input.length; - if (end * bits % 8) - throw new Error("Invalid padding: string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - if (!((end - 1) * bits % 8)) - throw new Error("Invalid padding: string has too much padding"); - } - return input.slice(0, end); - } - }; - } - function normalize(fn) { - if (typeof fn !== "function") - throw new Error("normalize fn should be function"); - return { encode: (from) => from, decode: (to) => fn(to) }; - } - function convertRadix(data, from, to) { - if (from < 2) - throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`); - if (to < 2) - throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`); - if (!Array.isArray(data)) - throw new Error("convertRadix: data should be array"); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data); - digits.forEach((d) => { - assertNumber(d); - if (d < 0 || d >= from) - throw new Error(`Wrong integer: ${d}`); - }); - while (true) { - let carry = 0; - let done = true; - for (let i2 = pos; i2 < digits.length; i2++) { - const digit = digits[i2]; - const digitBase = from * carry + digit; - if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) { - throw new Error("convertRadix: carry overflow"); - } - carry = digitBase % to; - digits[i2] = Math.floor(digitBase / to); - if (!Number.isSafeInteger(digits[i2]) || digits[i2] * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!digits[i2]) - pos = i2; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i2 = 0; i2 < data.length - 1 && data[i2] === 0; i2++) - res.push(0); - return res.reverse(); - } - var gcd = (a, b) => !b ? a : gcd(b, a % b); - var radix2carry = (from, to) => from + (to - gcd(from, to)); - function convertRadix2(data, from, to, padding2) { - if (!Array.isArray(data)) - throw new Error("convertRadix2: data should be array"); - if (from <= 0 || from > 32) - throw new Error(`convertRadix2: wrong from=${from}`); - if (to <= 0 || to > 32) - throw new Error(`convertRadix2: wrong to=${to}`); - if (radix2carry(from, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); - } - let carry = 0; - let pos = 0; - const mask = 2 ** to - 1; - const res = []; - for (const n of data) { - assertNumber(n); - if (n >= 2 ** from) - throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); - carry = carry << from | n; - if (pos + from > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); - pos += from; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - carry &= 2 ** pos - 1; - } - carry = carry << to - pos & mask; - if (!padding2 && pos >= from) - throw new Error("Excess padding"); - if (!padding2 && carry) - throw new Error(`Non-zero padding: ${carry}`); - if (padding2 && pos > 0) - res.push(carry >>> 0); - return res; - } - function radix(num) { - assertNumber(num); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes3), 2 ** 8, num); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix.decode input should be array of strings"); - return Uint8Array.from(convertRadix(digits, num, 2 ** 8)); - } - }; - } - function radix2(bits, revPadding = false) { - assertNumber(bits); - if (bits <= 0 || bits > 32) - throw new Error("radix2: bits should be in (0..32]"); - if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) - throw new Error("radix2: carry overflow"); - return { - encode: (bytes3) => { - if (!(bytes3 instanceof Uint8Array)) - throw new Error("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes3), 8, bits, !revPadding); - }, - decode: (digits) => { - if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number") - throw new Error("radix2.decode input should be array of strings"); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - } - }; - } - function unsafeWrapper(fn) { - if (typeof fn !== "function") - throw new Error("unsafeWrapper fn should be function"); - return function(...args) { - try { - return fn.apply(null, args); - } catch (e) { - } - }; - } - var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join("")); - var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join("")); - var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join("")); - var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1"))); - var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join("")); - var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join("")); - var genBase58 = (abc) => chain(radix(58), alphabet(abc), join("")); - var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); - var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"); - var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"); - var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; - var base58xmr = { - encode(data) { - let res = ""; - for (let i2 = 0; i2 < data.length; i2 += 8) { - const block = data.subarray(i2, i2 + 8); - res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1"); - } - return res; - }, - decode(str) { - let res = []; - for (let i2 = 0; i2 < str.length; i2 += 11) { - const slice = str.slice(i2, i2 + 11); - const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); - const block = base58.decode(slice); - for (let j = 0; j < block.length - blockLen; j++) { - if (block[j] !== 0) - throw new Error("base58xmr: wrong padding"); - } - res = res.concat(Array.from(block.slice(block.length - blockLen))); - } - return Uint8Array.from(res); - } - }; - var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join("")); - var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059]; - function bech32Polymod(pre) { - const b = pre >> 25; - let chk = (pre & 33554431) << 5; - for (let i2 = 0; i2 < POLYMOD_GENERATORS.length; i2++) { - if ((b >> i2 & 1) === 1) - chk ^= POLYMOD_GENERATORS[i2]; - } - return chk; - } - function bechChecksum(prefix, words, encodingConst = 1) { - const len = prefix.length; - let chk = 1; - for (let i2 = 0; i2 < len; i2++) { - const c = prefix.charCodeAt(i2); - if (c < 33 || c > 126) - throw new Error(`Invalid prefix (${prefix})`); - chk = bech32Polymod(chk) ^ c >> 5; - } - chk = bech32Polymod(chk); - for (let i2 = 0; i2 < len; i2++) - chk = bech32Polymod(chk) ^ prefix.charCodeAt(i2) & 31; - for (let v of words) - chk = bech32Polymod(chk) ^ v; - for (let i2 = 0; i2 < 6; i2++) - chk = bech32Polymod(chk); - chk ^= encodingConst; - return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false)); - } - function genBech32(encoding) { - const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939; - const _words = radix2(5); - const fromWords = _words.decode; - const toWords = _words.encode; - const fromWordsUnsafe = unsafeWrapper(fromWords); - function encode(prefix, words, limit = 90) { - if (typeof prefix !== "string") - throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`); - if (!Array.isArray(words) || words.length && typeof words[0] !== "number") - throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`); - const actualLength = prefix.length + 7 + words.length; - if (limit !== false && actualLength > limit) - throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); - prefix = prefix.toLowerCase(); - return `${prefix}1${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`; - } - function decode2(str, limit = 90) { - if (typeof str !== "string") - throw new Error(`bech32.decode input should be string, not ${typeof str}`); - if (str.length < 8 || limit !== false && str.length > limit) - throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`); - const lowered = str.toLowerCase(); - if (str !== lowered && str !== str.toUpperCase()) - throw new Error(`String must be lowercase or uppercase`); - str = lowered; - const sepIndex = str.lastIndexOf("1"); - if (sepIndex === 0 || sepIndex === -1) - throw new Error(`Letter "1" must be present between prefix and data only`); - const prefix = str.slice(0, sepIndex); - const _words2 = str.slice(sepIndex + 1); - if (_words2.length < 6) - throw new Error("Data must be at least 6 characters long"); - const words = BECH_ALPHABET.decode(_words2).slice(0, -6); - const sum = bechChecksum(prefix, words, ENCODING_CONST); - if (!_words2.endsWith(sum)) - throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); - return { prefix, words }; - } - const decodeUnsafe = unsafeWrapper(decode2); - function decodeToBytes(str) { - const { prefix, words } = decode2(str, false); - return { prefix, words, bytes: fromWords(words) }; - } - return { encode, decode: decode2, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords }; - } - var bech32 = genBech32("bech32"); - var bech32m = genBech32("bech32m"); - var utf8 = { - encode: (data) => new TextDecoder().decode(data), - decode: (str) => new TextEncoder().encode(str) - }; - var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s) => { - if (typeof s !== "string" || s.length % 2) - throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); - return s.toLowerCase(); - })); - var CODERS = { - utf8, - hex, - base16, - base32, - base64, - base64url, - base58, - base58xmr - }; - var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`; - - // node_modules/nostr-tools/lib/esm/nip19.js - var utf8Decoder = new TextDecoder("utf-8"); - var utf8Encoder = new TextEncoder(); - var Bech32MaxSize = 5e3; - function decode(nip19) { - let { prefix, words } = bech32.decode(nip19, Bech32MaxSize); - let data = new Uint8Array(bech32.fromWords(words)); - switch (prefix) { - case "nprofile": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nprofile"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - return { - type: "nprofile", - data: { - pubkey: bytesToHex(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] - } - }; - } - case "nevent": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nevent"); - if (tlv[0][0].length !== 32) - throw new Error("TLV 0 should be 32 bytes"); - if (tlv[2] && tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (tlv[3] && tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "nevent", - data: { - id: bytesToHex(tlv[0][0]), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [], - author: tlv[2]?.[0] ? bytesToHex(tlv[2][0]) : void 0, - kind: tlv[3]?.[0] ? parseInt(bytesToHex(tlv[3][0]), 16) : void 0 - } - }; - } - case "naddr": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for naddr"); - if (!tlv[2]?.[0]) - throw new Error("missing TLV 2 for naddr"); - if (tlv[2][0].length !== 32) - throw new Error("TLV 2 should be 32 bytes"); - if (!tlv[3]?.[0]) - throw new Error("missing TLV 3 for naddr"); - if (tlv[3][0].length !== 4) - throw new Error("TLV 3 should be 4 bytes"); - return { - type: "naddr", - data: { - identifier: utf8Decoder.decode(tlv[0][0]), - pubkey: bytesToHex(tlv[2][0]), - kind: parseInt(bytesToHex(tlv[3][0]), 16), - relays: tlv[1] ? tlv[1].map((d) => utf8Decoder.decode(d)) : [] - } - }; - } - case "nrelay": { - let tlv = parseTLV(data); - if (!tlv[0]?.[0]) - throw new Error("missing TLV 0 for nrelay"); - return { - type: "nrelay", - data: utf8Decoder.decode(tlv[0][0]) - }; - } - case "nsec": - return { type: prefix, data }; - case "npub": - case "note": - return { type: prefix, data: bytesToHex(data) }; - default: - throw new Error(`unknown prefix ${prefix}`); - } - } - function parseTLV(data) { - let result = {}; - let rest = data; - while (rest.length > 0) { - let t = rest[0]; - let l = rest[1]; - let v = rest.slice(2, 2 + l); - rest = rest.slice(2 + l); - if (v.length < l) - throw new Error(`not enough data to read on TLV ${t}`); - result[t] = result[t] || []; - result[t].push(v); - } - return result; - } - function npubEncode(hex2) { - return encodeBytes("npub", hexToBytes(hex2)); - } - function encodeBech32(prefix, data) { - let words = bech32.toWords(data); - return bech32.encode(prefix, words, Bech32MaxSize); - } - function encodeBytes(prefix, bytes3) { - return encodeBech32(prefix, bytes3); - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_assert.js - function number(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number(hash3.outputLen); - number(hash3.blockLen); - } - function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/crypto.js - var crypto2 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/utils.js - var u8a2 = (a) => a instanceof Uint8Array; - var createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - var rotr2 = (word, shift) => word << 32 - shift | word >>> shift; - var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; - if (!isLE2) - throw new Error("Non little-endian hardware is not supported"); - function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function toBytes2(data) { - if (typeof data === "string") - data = utf8ToBytes2(data); - if (!u8a2(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - function concatBytes2(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a2(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - var Hash2 = class { - clone() { - return this._cloneInto(); - } - }; - var toStr = {}.toString; - function wrapConstructor2(hashCons) { - const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - function randomBytes(bytesLength = 32) { - if (crypto2 && typeof crypto2.getRandomValues === "function") { - return crypto2.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error("crypto.getRandomValues must be defined"); - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/_sha2.js - function setBigUint64(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl, isLE3); - } - var SHA2 = class extends Hash2 { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView2(this.buffer); - } - update(data) { - exists(this); - const { view, buffer, blockLen } = this; - data = toBytes2(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView2(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - exists(this); - output(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer[i2] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView2(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE3); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - }; - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/sha256.js - var Chi = (a, b, c) => a & b ^ ~a & c; - var Maj = (a, b, c) => a & b ^ a & c ^ b & c; - var SHA256_K = /* @__PURE__ */ 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 - ]); - var IV = /* @__PURE__ */ new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - var SHA256_W = /* @__PURE__ */ new Uint32Array(64); - var SHA256 = class extends SHA2 { - constructor() { - super(64, 32, 8, false); - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W[i2 - 15]; - const W2 = SHA256_W[i2 - 2]; - const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3; - const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10; - SHA256_W[i2] = s1 + SHA256_W[i2 - 7] + s0 + SHA256_W[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i2] + SHA256_W[i2] | 0; - const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - }; - var sha256 = /* @__PURE__ */ wrapConstructor2(() => new SHA256()); - - // node_modules/@noble/curves/esm/abstract/utils.js - var utils_exports = {}; - __export(utils_exports, { - bitGet: () => bitGet, - bitLen: () => bitLen, - bitMask: () => bitMask, - bitSet: () => bitSet, - bytesToHex: () => bytesToHex2, - bytesToNumberBE: () => bytesToNumberBE, - bytesToNumberLE: () => bytesToNumberLE, - concatBytes: () => concatBytes3, - createHmacDrbg: () => createHmacDrbg, - ensureBytes: () => ensureBytes, - equalBytes: () => equalBytes, - hexToBytes: () => hexToBytes2, - hexToNumber: () => hexToNumber, - numberToBytesBE: () => numberToBytesBE, - numberToBytesLE: () => numberToBytesLE, - numberToHexUnpadded: () => numberToHexUnpadded, - numberToVarBytesBE: () => numberToVarBytesBE, - utf8ToBytes: () => utf8ToBytes3, - validateObject: () => validateObject - }); - var _0n = BigInt(0); - var _1n = BigInt(1); - var _2n = BigInt(2); - var u8a3 = (a) => a instanceof Uint8Array; - var hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i2) => i2.toString(16).padStart(2, "0")); - function bytesToHex2(bytes3) { - if (!u8a3(bytes3)) - throw new Error("Uint8Array expected"); - let hex2 = ""; - for (let i2 = 0; i2 < bytes3.length; i2++) { - hex2 += hexes2[bytes3[i2]]; - } - return hex2; - } - function numberToHexUnpadded(num) { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - } - function hexToNumber(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - return BigInt(hex2 === "" ? "0" : `0x${hex2}`); - } - function hexToBytes2(hex2) { - if (typeof hex2 !== "string") - throw new Error("hex string expected, got " + typeof hex2); - const len = hex2.length; - if (len % 2) - throw new Error("padded hex string expected, got unpadded hex of length " + len); - const array = new Uint8Array(len / 2); - for (let i2 = 0; i2 < array.length; i2++) { - const j = i2 * 2; - const hexByte = hex2.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error("Invalid byte sequence"); - array[i2] = byte; - } - return array; - } - function bytesToNumberBE(bytes3) { - return hexToNumber(bytesToHex2(bytes3)); - } - function bytesToNumberLE(bytes3) { - if (!u8a3(bytes3)) - throw new Error("Uint8Array expected"); - return hexToNumber(bytesToHex2(Uint8Array.from(bytes3).reverse())); - } - function numberToBytesBE(n, len) { - return hexToBytes2(n.toString(16).padStart(len * 2, "0")); - } - function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); - } - function numberToVarBytesBE(n) { - return hexToBytes2(numberToHexUnpadded(n)); - } - function ensureBytes(title, hex2, expectedLength) { - let res; - if (typeof hex2 === "string") { - try { - res = hexToBytes2(hex2); - } catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`); - } - } else if (u8a3(hex2)) { - res = Uint8Array.from(hex2); - } else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; - } - function concatBytes3(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; - arrays.forEach((a) => { - if (!u8a3(a)) - throw new Error("Uint8Array expected"); - r.set(a, pad); - pad += a.length; - }); - return r; - } - function equalBytes(b1, b2) { - if (b1.length !== b2.length) - return false; - for (let i2 = 0; i2 < b1.length; i2++) - if (b1[i2] !== b2[i2]) - return false; - return true; - } - function utf8ToBytes3(str) { - if (typeof str !== "string") - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); - } - function bitLen(n) { - let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; - return len; - } - function bitGet(n, pos) { - return n >> BigInt(pos) & _1n; - } - var bitSet = (n, pos, value) => { - return n | (value ? _1n : _0n) << BigInt(pos); - }; - var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; - var u8n = (data) => new Uint8Array(data); - var u8fr = (arr) => Uint8Array.from(arr); - function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i2 = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i2 = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n()) => { - k = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8fr([1]), seed); - v = h(); - }; - const gen = () => { - if (i2++ >= 1e3) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes3(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; - } - var validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || val instanceof Uint8Array, - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) - }; - function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error(`Invalid validator "${type}", expected function`); - const val = object[fieldName]; - if (isOptional && val === void 0) - return; - if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; - } - - // node_modules/@noble/curves/esm/abstract/modular.js - var _0n2 = BigInt(0); - var _1n2 = BigInt(1); - var _2n2 = BigInt(2); - var _3n = BigInt(3); - var _4n = BigInt(4); - var _5n = BigInt(5); - var _8n = BigInt(8); - var _9n = BigInt(9); - var _16n = BigInt(16); - function mod(a, b) { - const result = a % b; - return result >= _0n2 ? result : b + result; - } - function pow(num, power, modulo) { - if (modulo <= _0n2 || power < _0n2) - throw new Error("Expected power/modulo > 0"); - if (modulo === _1n2) - return _0n2; - let res = _1n2; - while (power > _0n2) { - if (power & _1n2) - res = res * num % modulo; - num = num * num % modulo; - power >>= _1n2; - } - return res; - } - function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; - } - function invert(number3, modulo) { - if (number3 === _0n2 || modulo <= _0n2) { - throw new Error(`invert: expected positive integers, got n=${number3} mod=${modulo}`); - } - let a = mod(number3, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd2 = b; - if (gcd2 !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); - } - function tonelliShanks(P) { - const legendreC = (P - _1n2) / _2n2; - let Q, S, Z; - for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) - ; - for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++) - ; - if (S === 1) { - const p1div4 = (P + _1n2) / _4n; - return function tonelliFast(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - const Q1div2 = (Q + _1n2) / _2n2; - return function tonelliSlow(Fp2, n) { - if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) - throw new Error("Cannot find square root"); - let r = S; - let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); - let x = Fp2.pow(n, Q1div2); - let b = Fp2.pow(n, Q); - while (!Fp2.eql(b, Fp2.ONE)) { - if (Fp2.eql(b, Fp2.ZERO)) - return Fp2.ZERO; - let m = 1; - for (let t2 = Fp2.sqr(b); m < r; m++) { - if (Fp2.eql(t2, Fp2.ONE)) - break; - t2 = Fp2.sqr(t2); - } - const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); - g = Fp2.sqr(ge2); - x = Fp2.mul(x, ge2); - b = Fp2.mul(b, g); - r = m; - } - return x; - }; - } - function FpSqrt(P) { - if (P % _4n === _3n) { - const p1div4 = (P + _1n2) / _4n; - return function sqrt3mod4(Fp2, n) { - const root = Fp2.pow(n, p1div4); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _8n === _5n) { - const c1 = (P - _5n) / _8n; - return function sqrt5mod8(Fp2, n) { - const n2 = Fp2.mul(n, _2n2); - const v = Fp2.pow(n2, c1); - const nv = Fp2.mul(n, v); - const i2 = Fp2.mul(Fp2.mul(nv, _2n2), v); - const root = Fp2.mul(nv, Fp2.sub(i2, Fp2.ONE)); - if (!Fp2.eql(Fp2.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; - }; - } - if (P % _16n === _9n) { - } - return tonelliShanks(P); - } - var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; - function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); - } - function FpPow(f, num, power) { - if (power < _0n2) - throw new Error("Expected power > 0"); - if (power === _0n2) - return f.ONE; - if (power === _1n2) - return num; - let p = f.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n2; - } - return p; - } - function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - const lastMultiplied = nums.reduce((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = acc; - return f.mul(acc, num); - }, f.ONE); - const inverted = f.inv(lastMultiplied); - nums.reduceRight((acc, num, i2) => { - if (f.is0(num)) - return acc; - tmp[i2] = f.mul(acc, tmp[i2]); - return f.mul(acc, num); - }, inverted); - return tmp; - } - function nLength(n, nBitLength) { - const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; - } - function Field(ORDER, bitLen2, isLE3 = false, redef = {}) { - if (ORDER <= _0n2) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("Field lengths over 2048 bytes are not supported"); - const sqrtP = FpSqrt(ORDER); - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n2, - ONE: _1n2, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n2 <= num && num < ORDER; - }, - is0: (num) => num === _0n2, - isOdd: (num) => (num & _1n2) === _1n2, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f, n)), - invertBatch: (lst) => FpInvertBatch(f, lst), - cmov: (a, b, c) => c ? b : a, - toBytes: (num) => isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes3) => { - if (bytes3.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes3.length}`); - return isLE3 ? bytesToNumberLE(bytes3) : bytesToNumberBE(bytes3); - } - }); - return Object.freeze(f); - } - function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); - } - function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); - } - function mapHashToField(key, fieldOrder, isLE3 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE3 ? bytesToNumberBE(key) : bytesToNumberLE(key); - const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); - } - - // node_modules/@noble/curves/esm/abstract/curve.js - var _0n3 = BigInt(0); - var _1n3 = BigInt(1); - function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; - const windowSize = 2 ** (W - 1); - return { windows, windowSize }; - }; - return { - constTimeNegate, - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - }, - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window2 = 0; window2 < windows; window2++) { - base = p; - points.push(base); - for (let i2 = 1; i2 < windowSize; i2++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - wNAF(W, precomputes, n) { - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window2 = 0; window2 < windows; window2++) { - const offset = window2 * windowSize; - let wbits = Number(n & mask); - n >>= shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n3; - } - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; - const cond1 = window2 % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - return { p, f }; - }, - wNAFCached(P, precomputesMap, n, transform) { - const W = P._WINDOW_SIZE || 1; - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - } - }; - } - function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); - } - - // node_modules/@noble/curves/esm/abstract/weierstrass.js - function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowedPrivateKeyLengths: "array", - wrapPrivateKey: "boolean", - isTorsionFree: "function", - clearCofactor: "function", - allowInfinityPoint: "boolean", - fromBytes: "function", - toBytes: "function" - }); - const { endo, Fp: Fp2, a } = opts; - if (endo) { - if (!Fp2.eql(a, Fp2.ZERO)) { - throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); - } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); - } - } - return Object.freeze({ ...opts }); - } - var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; - var DER = { - Err: class DERErr extends Error { - constructor(m = "") { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 2) - throw new E("Invalid signature integer tag"); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E("Invalid signature integer: wrong length"); - if (res[0] & 128) - throw new E("Invalid signature integer: negative"); - if (res[0] === 0 && !(res[1] & 128)) - throw new E("Invalid signature integer: unnecessary leading zero"); - return { d: b2n(res), l: data.subarray(len + 2) }; - }, - toSig(hex2) { - const { Err: E } = DER; - const data = typeof hex2 === "string" ? h2b(hex2) : hex2; - if (!(data instanceof Uint8Array)) - throw new Error("ui8a expected"); - let l = data.length; - if (l < 2 || data[0] != 48) - throw new E("Invalid signature tag"); - if (data[1] !== l - 2) - throw new E("Invalid signature: incorrect length"); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E("Invalid signature: left bytes after parsing"); - return { r, s }; - }, - hexFromSig(sig) { - const slice = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; - const h = (num) => { - const hex2 = num.toString(16); - return hex2.length & 1 ? `0${hex2}` : hex2; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - } - }; - var _0n4 = BigInt(0); - var _1n4 = BigInt(1); - var _2n3 = BigInt(2); - var _3n2 = BigInt(3); - var _4n2 = BigInt(4); - function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp: Fp2 } = CURVE; - const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || ((bytes3) => { - const tail = bytes3.subarray(1); - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp2.sqr(x); - const x3 = Fp2.mul(x2, x); - return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); - } - if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error("bad generator point: equation left != right"); - function isWithinCurveOrder(num) { - return typeof num === "bigint" && _0n4 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error("Expected valid bigint: 0 < bigint < curve.n"); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== "bigint") { - if (key instanceof Uint8Array) - key = bytesToHex2(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("Invalid key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; - try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); - assertGE(num); - return num; - } - const pointPrecomputes = /* @__PURE__ */ new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point2)) - throw new Error("ProjectivePoint expected"); - } - class Point2 { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp2.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp2.isValid(py)) - throw new Error("y required"); - if (pz == null || !Fp2.isValid(pz)) - throw new Error("z required"); - } - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point2) - throw new Error("projective point not allowed"); - const is0 = (i2) => Fp2.eql(i2, Fp2.ZERO); - if (is0(x) && is0(y)) - return Point2.ZERO; - return new Point2(x, y, Fp2.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - static normalizeZ(points) { - const toInv = Fp2.invertBatch(points.map((p) => p.pz)); - return points.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - } - static fromHex(hex2) { - const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex2))); - P.assertValidity(); - return P; - } - static fromPrivateKey(privateKey) { - return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - assertValidity() { - if (this.is0()) { - if (CURVE.allowInfinityPoint && !Fp2.is0(this.py)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = this.toAffine(); - if (!Fp2.isValid(x) || !Fp2.isValid(y)) - throw new Error("bad point: x or y not FE"); - const left = Fp2.sqr(y); - const right = weierstrassEquation(x); - if (!Fp2.eql(left, right)) - throw new Error("bad point: equation left != right"); - if (!this.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp2.isOdd) - return !Fp2.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); - const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); - return U1 && U2; - } - negate() { - return new Point2(this.px, Fp2.neg(this.py), this.pz); - } - double() { - const { a, b } = CURVE; - const b3 = Fp2.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - let t0 = Fp2.mul(X1, X1); - let t1 = Fp2.mul(Y1, Y1); - let t2 = Fp2.mul(Z1, Z1); - let t3 = Fp2.mul(X1, Y1); - t3 = Fp2.add(t3, t3); - Z3 = Fp2.mul(X1, Z1); - Z3 = Fp2.add(Z3, Z3); - X3 = Fp2.mul(a, Z3); - Y3 = Fp2.mul(b3, t2); - Y3 = Fp2.add(X3, Y3); - X3 = Fp2.sub(t1, Y3); - Y3 = Fp2.add(t1, Y3); - Y3 = Fp2.mul(X3, Y3); - X3 = Fp2.mul(t3, X3); - Z3 = Fp2.mul(b3, Z3); - t2 = Fp2.mul(a, t2); - t3 = Fp2.sub(t0, t2); - t3 = Fp2.mul(a, t3); - t3 = Fp2.add(t3, Z3); - Z3 = Fp2.add(t0, t0); - t0 = Fp2.add(Z3, t0); - t0 = Fp2.add(t0, t2); - t0 = Fp2.mul(t0, t3); - Y3 = Fp2.add(Y3, t0); - t2 = Fp2.mul(Y1, Z1); - t2 = Fp2.add(t2, t2); - t0 = Fp2.mul(t2, t3); - X3 = Fp2.sub(X3, t0); - Z3 = Fp2.mul(t2, t1); - Z3 = Fp2.add(Z3, Z3); - Z3 = Fp2.add(Z3, Z3); - return new Point2(X3, Y3, Z3); - } - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; - const a = CURVE.a; - const b3 = Fp2.mul(CURVE.b, _3n2); - let t0 = Fp2.mul(X1, X2); - let t1 = Fp2.mul(Y1, Y2); - let t2 = Fp2.mul(Z1, Z2); - let t3 = Fp2.add(X1, Y1); - let t4 = Fp2.add(X2, Y2); - t3 = Fp2.mul(t3, t4); - t4 = Fp2.add(t0, t1); - t3 = Fp2.sub(t3, t4); - t4 = Fp2.add(X1, Z1); - let t5 = Fp2.add(X2, Z2); - t4 = Fp2.mul(t4, t5); - t5 = Fp2.add(t0, t2); - t4 = Fp2.sub(t4, t5); - t5 = Fp2.add(Y1, Z1); - X3 = Fp2.add(Y2, Z2); - t5 = Fp2.mul(t5, X3); - X3 = Fp2.add(t1, t2); - t5 = Fp2.sub(t5, X3); - Z3 = Fp2.mul(a, t4); - X3 = Fp2.mul(b3, t2); - Z3 = Fp2.add(X3, Z3); - X3 = Fp2.sub(t1, Z3); - Z3 = Fp2.add(t1, Z3); - Y3 = Fp2.mul(X3, Z3); - t1 = Fp2.add(t0, t0); - t1 = Fp2.add(t1, t0); - t2 = Fp2.mul(a, t2); - t4 = Fp2.mul(b3, t4); - t1 = Fp2.add(t1, t2); - t2 = Fp2.sub(t0, t2); - t2 = Fp2.mul(a, t2); - t4 = Fp2.add(t4, t2); - t0 = Fp2.mul(t1, t4); - Y3 = Fp2.add(Y3, t0); - t0 = Fp2.mul(t5, t4); - X3 = Fp2.mul(t3, X3); - X3 = Fp2.sub(X3, t0); - t0 = Fp2.mul(t3, t1); - Z3 = Fp2.mul(t5, Z3); - Z3 = Fp2.add(Z3, t0); - return new Point2(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point2.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i2) => p.toAffine(toInv[i2])).map(Point2.fromAffine); - }); - } - multiplyUnsafe(n) { - const I = Point2.ZERO; - if (n === _0n4) - return I; - assertGE(n); - if (n === _1n4) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n4 || k2 > _0n4) { - if (k1 & _1n4) - k1p = k1p.add(d); - if (k2 & _1n4) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n4; - k2 >>= _1n4; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(n); - point = p; - fake = f; - } - return Point2.normalizeZ([point, fake])[0]; - } - multiplyAndAddUnsafe(Q, a, b) { - const G = Point2.BASE; - const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? void 0 : sum; - } - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - if (iz == null) - iz = is0 ? Fp2.ONE : Fp2.inv(z); - const ax = Fp2.mul(x, iz); - const ay = Fp2.mul(y, iz); - const zz = Fp2.mul(z, iz); - if (is0) - return { x: Fp2.ZERO, y: Fp2.ZERO }; - if (!Fp2.eql(zz, Fp2.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(Point2, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(Point2, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes3(Point2, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex2(this.toRawBytes(isCompressed)); - } - } - Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); - Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - return { - CURVE, - ProjectivePoint: Point2, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder - }; - } - function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" - }); - return Object.freeze({ lowS: true, ...opts }); - } - function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp: Fp2, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp2.BYTES + 1; - const uncompressedLen = 2 * Fp2.BYTES + 1; - function isValidFieldElement(num) { - return _0n4 < num && num < Fp2.ORDER; - } - function modN2(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp2.toBytes(a.x); - const cat = concatBytes3; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); - } - }, - fromBytes(bytes3) { - const len = bytes3.length; - const head = bytes3[0]; - const tail = bytes3.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y = Fp2.sqrt(y2); - const isYOdd = (y & _1n4) === _1n4; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp2.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); - const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); - return { x, y }; - } else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - } - }); - const numToNByteStr = (num) => bytesToHex2(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number3) { - const HALF = CURVE_ORDER >> _1n4; - return number3 > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN2(-s) : s; - } - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - static fromCompact(hex2) { - const l = CURVE.nByteLength; - hex2 = ensureBytes("compactSignature", hex2, l * 2); - return new Signature(slcNum(hex2, 0, l), slcNum(hex2, l, 2 * l)); - } - static fromDER(hex2) { - const { r, s } = DER.toSig(ensureBytes("DER", hex2)); - return new Signature(r, s); - } - assertValidity() { - if (!isWithinCurveOrder(this.r)) - throw new Error("r must be 0 < r < CURVE.n"); - if (!isWithinCurveOrder(this.s)) - throw new Error("s must be 0 < s < CURVE.n"); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp2.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point2.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); - const u1 = modN2(-h * ir); - const u2 = modN2(s * ir); - const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; - } - toDERRawBytes() { - return hexToBytes2(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - toCompactRawBytes() { - return hexToBytes2(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - precompute(windowSize = 8, point = Point2.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey2(privateKey, isCompressed = true) { - return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === "string"; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point2) - return true; - return false; - } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error("first arg must be private key"); - if (!isProbPub(publicB)) - throw new Error("second arg must be public key"); - const b = Point2.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes3) { - const num = bytesToNumberBE(bytes3); - const delta = bytes3.length * 8 - CURVE.nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes3) { - return modN2(bits2int(bytes3)); - }; - const ORDER_MASK = bitMask(CURVE.nBitLength); - function int2octets(num) { - if (typeof num !== "bigint") - throw new Error("bigint expected"); - if (!(_0n4 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - return numberToBytesBE(num, CURVE.nByteLength); - } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => k in opts)) - throw new Error("sign() legacy options not supported"); - const { hash: hash3, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash3(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null) { - const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); - } - const seed = concatBytes3(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point2.BASE.multiply(k).toAffine(); - const r = modN2(q.x); - if (r === _0n4) - return; - const s = modN2(ik * modN2(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; - } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point2.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - const { lowS, prehash } = opts; - let _sig = void 0; - let P; - try { - if (typeof sg === "string" || sg instanceof Uint8Array) { - try { - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { - const { r: r2, s: s2 } = sg; - _sig = new Signature(r2, s2); - } else { - throw new Error("PARSE"); - } - P = Point2.fromHex(publicKey); - } catch (error) { - if (error.message === "PARSE") - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN2(h * is); - const u2 = modN2(r * is); - const R = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); - if (!R) - return false; - const v = modN2(R.x); - return v === r; - } - return { - CURVE, - getPublicKey: getPublicKey2, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point2, - Signature, - utils - }; - } - - // node_modules/@noble/curves/node_modules/@noble/hashes/esm/hmac.js - var HMAC = class extends Hash2 { - constructor(hash3, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash(hash3); - const key = toBytes2(_key); - this.iHash = hash3.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash3.create().update(key).digest() : key); - for (let i2 = 0; i2 < pad.length; i2++) - pad[i2] ^= 54; - this.iHash.update(pad); - this.oHash = hash3.create(); - for (let i2 = 0; i2 < pad.length; i2++) - pad[i2] ^= 54 ^ 92; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - var hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest(); - hmac.create = (hash3, key) => new HMAC(hash3, key); - - // node_modules/@noble/curves/esm/_shortw_utils.js - function getHash(hash3) { - return { - hash: hash3, - hmac: (key, ...msgs) => hmac(hash3, key, concatBytes2(...msgs)), - randomBytes - }; - } - function createCurve(curveDef, defHash) { - const create = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) }); - return Object.freeze({ ...create(defHash), create }); - } - - // node_modules/@noble/curves/esm/secp256k1.js - var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - var _1n5 = BigInt(1); - var _2n4 = BigInt(2); - var divNearest = (a, b) => (a + b / _2n4) / b; - function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; - } - var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); - var secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; - } - } - }, sha256); - var _0n5 = BigInt(0); - var fe = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1P; - var ge = (x) => typeof x === "bigint" && _0n5 < x && x < secp256k1N; - var TAGGED_HASH_PREFIXES = {}; - function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === void 0) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes3(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes3(tagP, ...messages)); - } - var pointToBytes = (point) => point.toRawBytes(true).slice(1); - var numTo32b = (n) => numberToBytesBE(n, 32); - var modP = (x) => mod(x, secp256k1P); - var modN = (x) => mod(x, secp256k1N); - var Point = secp256k1.ProjectivePoint; - var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); - function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; - } - function lift_x(x) { - if (!fe(x)) - throw new Error("bad x: need 0 < x < p"); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n5) - y = modP(-y); - const p = new Point(x, y, _1n5); - p.assertValidity(); - return p; - } - function challenge(...args) { - return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args))); - } - function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; - } - function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(bytesToNumberBE(rand)); - if (k_ === _0n5) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; - } - function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); - const r = bytesToNumberBE(sig.subarray(0, 32)); - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; - } - } - var schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } - }))(); - - // node_modules/@noble/hashes/esm/_assert.js - function number2(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bool(b) { - if (typeof b !== "boolean") - throw new Error(`Expected boolean, not ${b}`); - } - function bytes2(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error("Expected Uint8Array"); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash2(hash3) { - if (typeof hash3 !== "function" || typeof hash3.create !== "function") - throw new Error("Hash should be wrapped by utils.wrapConstructor"); - number2(hash3.outputLen); - number2(hash3.blockLen); - } - function exists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); - } - function output2(out, instance) { - bytes2(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - var assert = { - number: number2, - bool, - bytes: bytes2, - hash: hash2, - exists: exists2, - output: output2 - }; - var assert_default = assert; - - // node_modules/@noble/hashes/esm/_sha2.js - function setBigUint642(view, byteOffset, value, isLE3) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE3); - const _32n = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE3 ? 4 : 0; - const l = isLE3 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE3); - view.setUint32(byteOffset + l, wl, isLE3); - } - var SHA22 = class extends Hash { - constructor(blockLen, outputLen, padOffset, isLE3) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE3; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - assert_default.exists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - assert_default.exists(this); - assert_default.output(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE3 } = this; - let { pos } = this; - buffer[pos++] = 128; - this.buffer.subarray(pos).fill(0); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i2 = pos; i2 < blockLen; i2++) - buffer[i2] = 0; - setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE3); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i2 = 0; i2 < outLen; i2++) - oview.setUint32(4 * i2, state[i2], isLE3); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - }; - - // node_modules/@noble/hashes/esm/sha256.js - var Chi2 = (a, b, c) => a & b ^ ~a & c; - var Maj2 = (a, b, c) => a & b ^ a & c ^ b & c; - var SHA256_K2 = 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 - ]); - var IV2 = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - var SHA256_W2 = new Uint32Array(64); - var SHA2562 = class extends SHA22 { - constructor() { - super(64, 32, 8, false); - this.A = IV2[0] | 0; - this.B = IV2[1] | 0; - this.C = IV2[2] | 0; - this.D = IV2[3] | 0; - this.E = IV2[4] | 0; - this.F = IV2[5] | 0; - this.G = IV2[6] | 0; - this.H = IV2[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i2 = 0; i2 < 16; i2++, offset += 4) - SHA256_W2[i2] = view.getUint32(offset, false); - for (let i2 = 16; i2 < 64; i2++) { - const W15 = SHA256_W2[i2 - 15]; - const W2 = SHA256_W2[i2 - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W2[i2] = s1 + SHA256_W2[i2 - 7] + s0 + SHA256_W2[i2 - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i2 = 0; i2 < 64; i2++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i2] + SHA256_W2[i2] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj2(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W2.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - }; - var SHA224 = class extends SHA2562 { - constructor() { - super(); - this.A = 3238371032 | 0; - this.B = 914150663 | 0; - this.C = 812702999 | 0; - this.D = 4144912697 | 0; - this.E = 4290775857 | 0; - this.F = 1750603025 | 0; - this.G = 1694076839 | 0; - this.H = 3204075428 | 0; - this.outputLen = 28; - } - }; - var sha2562 = wrapConstructor(() => new SHA2562()); - var sha224 = wrapConstructor(() => new SHA224()); - - // node_modules/nostr-tools/lib/esm/pool.js - var verifiedSymbol = Symbol("verified"); - var isRecord = (obj) => obj instanceof Object; - function validateEvent(event) { - if (!isRecord(event)) - return false; - if (typeof event.kind !== "number") - return false; - if (typeof event.content !== "string") - return false; - if (typeof event.created_at !== "number") - return false; - if (typeof event.pubkey !== "string") - return false; - if (!event.pubkey.match(/^[a-f0-9]{64}$/)) - return false; - if (!Array.isArray(event.tags)) - return false; - for (let i2 = 0; i2 < event.tags.length; i2++) { - let tag = event.tags[i2]; - if (!Array.isArray(tag)) - return false; - for (let j = 0; j < tag.length; j++) { - if (typeof tag[j] === "object") - return false; - } - } - return true; - } - var utf8Decoder2 = new TextDecoder("utf-8"); - var utf8Encoder2 = new TextEncoder(); - function normalizeURL(url) { - if (url.indexOf("://") === -1) - url = "wss://" + url; - let p = new URL(url); - p.pathname = p.pathname.replace(/\/+/g, "/"); - if (p.pathname.endsWith("/")) - p.pathname = p.pathname.slice(0, -1); - if (p.port === "80" && p.protocol === "ws:" || p.port === "443" && p.protocol === "wss:") - p.port = ""; - p.searchParams.sort(); - p.hash = ""; - return p.toString(); - } - var QueueNode = class { - value; - next = null; - prev = null; - constructor(message) { - this.value = message; - } - }; - var Queue = class { - first; - last; - constructor() { - this.first = null; - this.last = null; - } - enqueue(value) { - const newNode = new QueueNode(value); - if (!this.last) { - this.first = newNode; - this.last = newNode; - } else if (this.last === this.first) { - this.last = newNode; - this.last.prev = this.first; - this.first.next = newNode; - } else { - newNode.prev = this.last; - this.last.next = newNode; - this.last = newNode; - } - return true; - } - dequeue() { - if (!this.first) - return null; - if (this.first === this.last) { - const target2 = this.first; - this.first = null; - this.last = null; - return target2.value; - } - const target = this.first; - this.first = target.next; - return target.value; - } - }; - var JS = class { - generateSecretKey() { - return schnorr.utils.randomPrivateKey(); - } - getPublicKey(secretKey) { - return bytesToHex(schnorr.getPublicKey(secretKey)); - } - finalizeEvent(t, secretKey) { - const event = t; - event.pubkey = bytesToHex(schnorr.getPublicKey(secretKey)); - event.id = getEventHash(event); - event.sig = bytesToHex(schnorr.sign(getEventHash(event), secretKey)); - event[verifiedSymbol] = true; - return event; - } - verifyEvent(event) { - if (typeof event[verifiedSymbol] === "boolean") - return event[verifiedSymbol]; - const hash3 = getEventHash(event); - if (hash3 !== event.id) { - event[verifiedSymbol] = false; - return false; - } - try { - const valid = schnorr.verify(event.sig, hash3, event.pubkey); - event[verifiedSymbol] = valid; - return valid; - } catch (err) { - event[verifiedSymbol] = false; - return false; - } - } - }; - function serializeEvent(evt) { - if (!validateEvent(evt)) - throw new Error("can't serialize event with wrong or missing properties"); - return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]); - } - function getEventHash(event) { - let eventHash = sha2562(utf8Encoder2.encode(serializeEvent(event))); - return bytesToHex(eventHash); - } - var i = new JS(); - var generateSecretKey = i.generateSecretKey; - var getPublicKey = i.getPublicKey; - var finalizeEvent = i.finalizeEvent; - var verifyEvent = i.verifyEvent; - var ClientAuth = 22242; - function matchFilter(filter, event) { - if (filter.ids && filter.ids.indexOf(event.id) === -1) { - return false; - } - if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) { - return false; - } - if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) { - return false; - } - for (let f in filter) { - if (f[0] === "#") { - let tagName = f.slice(1); - let values = filter[`#${tagName}`]; - if (values && !event.tags.find(([t, v]) => t === f.slice(1) && values.indexOf(v) !== -1)) - return false; - } - } - if (filter.since && event.created_at < filter.since) - return false; - if (filter.until && event.created_at > filter.until) - return false; - return true; - } - function matchFilters(filters, event) { - for (let i2 = 0; i2 < filters.length; i2++) { - if (matchFilter(filters[i2], event)) { - return true; - } - } - return false; - } - function getHex64(json, field) { - let len = field.length + 3; - let idx = json.indexOf(`"${field}":`) + len; - let s = json.slice(idx).indexOf(`"`) + idx + 1; - return json.slice(s, s + 64); - } - function getSubscriptionId(json) { - let idx = json.slice(0, 22).indexOf(`"EVENT"`); - if (idx === -1) - return null; - let pstart = json.slice(idx + 7 + 1).indexOf(`"`); - if (pstart === -1) - return null; - let start = idx + 7 + 1 + pstart; - let pend = json.slice(start + 1, 80).indexOf(`"`); - if (pend === -1) - return null; - let end = start + 1 + pend; - return json.slice(start + 1, end); - } - function makeAuthEvent(relayURL, challenge2) { - return { - kind: ClientAuth, - created_at: Math.floor(Date.now() / 1e3), - tags: [ - ["relay", relayURL], - ["challenge", challenge2] - ], - content: "" - }; - } - async function yieldThread() { - return new Promise((resolve) => { - const ch = new MessageChannel(); - const handler = () => { - ch.port1.removeEventListener("message", handler); - resolve(); - }; - ch.port1.addEventListener("message", handler); - ch.port2.postMessage(0); - ch.port1.start(); - }); - } - var alwaysTrue = (t) => { - t[verifiedSymbol] = true; - return true; - }; - var AbstractRelay = class { - url; - _connected = false; - onclose = null; - onnotice = (msg) => console.debug(`NOTICE from ${this.url}: ${msg}`); - _onauth = null; - baseEoseTimeout = 4400; - connectionTimeout = 4400; - openSubs = /* @__PURE__ */ new Map(); - connectionTimeoutHandle; - connectionPromise; - openCountRequests = /* @__PURE__ */ new Map(); - openEventPublishes = /* @__PURE__ */ new Map(); - ws; - incomingMessageQueue = new Queue(); - queueRunning = false; - challenge; - serial = 0; - verifyEvent; - _WebSocket; - constructor(url, opts) { - this.url = normalizeURL(url); - this.verifyEvent = opts.verifyEvent; - this._WebSocket = opts.websocketImplementation || WebSocket; - } - static async connect(url, opts) { - const relay = new AbstractRelay(url, opts); - await relay.connect(); - return relay; - } - closeAllSubscriptions(reason) { - for (let [_, sub] of this.openSubs) { - sub.close(reason); - } - this.openSubs.clear(); - for (let [_, ep] of this.openEventPublishes) { - ep.reject(new Error(reason)); - } - this.openEventPublishes.clear(); - for (let [_, cr] of this.openCountRequests) { - cr.reject(new Error(reason)); - } - this.openCountRequests.clear(); - } - get connected() { - return this._connected; - } - async connect() { - if (this.connectionPromise) - return this.connectionPromise; - this.challenge = void 0; - this.connectionPromise = new Promise((resolve, reject) => { - this.connectionTimeoutHandle = setTimeout(() => { - reject("connection timed out"); - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection timed out"); - }, this.connectionTimeout); - try { - this.ws = new this._WebSocket(this.url); - } catch (err) { - reject(err); - return; - } - this.ws.onopen = () => { - clearTimeout(this.connectionTimeoutHandle); - this._connected = true; - resolve(); - }; - this.ws.onerror = (ev) => { - reject(ev.message || "websocket error"); - if (this._connected) { - this._connected = false; - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection errored"); - } - }; - this.ws.onclose = async () => { - if (this._connected) { - this._connected = false; - this.connectionPromise = void 0; - this.onclose?.(); - this.closeAllSubscriptions("relay connection closed"); - } - }; - this.ws.onmessage = this._onmessage.bind(this); - }); - return this.connectionPromise; - } - async runQueue() { - this.queueRunning = true; - while (true) { - if (false === this.handleNext()) { - break; - } - await yieldThread(); - } - this.queueRunning = false; - } - handleNext() { - const json = this.incomingMessageQueue.dequeue(); - if (!json) { - return false; - } - const subid = getSubscriptionId(json); - if (subid) { - const so = this.openSubs.get(subid); - if (!so) { - return; - } - const id = getHex64(json, "id"); - const alreadyHave = so.alreadyHaveEvent?.(id); - so.receivedEvent?.(this, id); - if (alreadyHave) { - return; - } - } - try { - let data = JSON.parse(json); - switch (data[0]) { - case "EVENT": { - const so = this.openSubs.get(data[1]); - const event = data[2]; - if (this.verifyEvent(event) && matchFilters(so.filters, event)) { - so.onevent(event); - } - return; - } - case "COUNT": { - const id = data[1]; - const payload = data[2]; - const cr = this.openCountRequests.get(id); - if (cr) { - cr.resolve(payload.count); - this.openCountRequests.delete(id); - } - return; - } - case "EOSE": { - const so = this.openSubs.get(data[1]); - if (!so) - return; - so.receivedEose(); - return; - } - case "OK": { - const id = data[1]; - const ok = data[2]; - const reason = data[3]; - const ep = this.openEventPublishes.get(id); - if (ok) - ep.resolve(reason); - else - ep.reject(new Error(reason)); - this.openEventPublishes.delete(id); - return; - } - case "CLOSED": { - const id = data[1]; - const so = this.openSubs.get(id); - if (!so) - return; - so.closed = true; - so.close(data[2]); - return; - } - case "NOTICE": - this.onnotice(data[1]); - return; - case "AUTH": { - this.challenge = data[1]; - this._onauth?.(data[1]); - return; - } - } - } catch (err) { - return; - } - } - async send(message) { - if (!this.connectionPromise) - throw new Error("sending on closed connection"); - this.connectionPromise.then(() => { - this.ws?.send(message); - }); - } - async auth(signAuthEvent) { - if (!this.challenge) - throw new Error("can't perform auth, no challenge was received"); - const evt = await signAuthEvent(makeAuthEvent(this.url, this.challenge)); - const ret = new Promise((resolve, reject) => { - this.openEventPublishes.set(evt.id, { resolve, reject }); - }); - this.send('["AUTH",' + JSON.stringify(evt) + "]"); - return ret; - } - async publish(event) { - const ret = new Promise((resolve, reject) => { - this.openEventPublishes.set(event.id, { resolve, reject }); - }); - this.send('["EVENT",' + JSON.stringify(event) + "]"); - return ret; - } - async count(filters, params) { - this.serial++; - const id = params?.id || "count:" + this.serial; - const ret = new Promise((resolve, reject) => { - this.openCountRequests.set(id, { resolve, reject }); - }); - this.send('["COUNT","' + id + '",' + JSON.stringify(filters).substring(1)); - return ret; - } - subscribe(filters, params) { - const subscription = this.prepareSubscription(filters, params); - subscription.fire(); - return subscription; - } - prepareSubscription(filters, params) { - this.serial++; - const id = params.id || "sub:" + this.serial; - const subscription = new Subscription(this, id, filters, params); - this.openSubs.set(id, subscription); - return subscription; - } - close() { - this.closeAllSubscriptions("relay connection closed by us"); - this._connected = false; - this.ws?.close(); - } - _onmessage(ev) { - this.incomingMessageQueue.enqueue(ev.data); - if (!this.queueRunning) { - this.runQueue(); - } - } - }; - var Subscription = class { - relay; - id; - closed = false; - eosed = false; - filters; - alreadyHaveEvent; - receivedEvent; - onevent; - oneose; - onclose; - eoseTimeout; - eoseTimeoutHandle; - constructor(relay, id, filters, params) { - this.relay = relay; - this.filters = filters; - this.id = id; - this.alreadyHaveEvent = params.alreadyHaveEvent; - this.receivedEvent = params.receivedEvent; - this.eoseTimeout = params.eoseTimeout || relay.baseEoseTimeout; - this.oneose = params.oneose; - this.onclose = params.onclose; - this.onevent = params.onevent || ((event) => { - console.warn( - `onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`, - event - ); - }); - } - fire() { - this.relay.send('["REQ","' + this.id + '",' + JSON.stringify(this.filters).substring(1)); - this.eoseTimeoutHandle = setTimeout(this.receivedEose.bind(this), this.eoseTimeout); - } - receivedEose() { - if (this.eosed) - return; - clearTimeout(this.eoseTimeoutHandle); - this.eosed = true; - this.oneose?.(); - } - close(reason = "closed by caller") { - if (!this.closed && this.relay.connected) { - this.relay.send('["CLOSE",' + JSON.stringify(this.id) + "]"); - this.closed = true; - } - this.relay.openSubs.delete(this.id); - this.onclose?.(reason); - } - }; - var AbstractSimplePool = class { - relays = /* @__PURE__ */ new Map(); - seenOn = /* @__PURE__ */ new Map(); - trackRelays = false; - verifyEvent; - trustedRelayURLs = /* @__PURE__ */ new Set(); - _WebSocket; - constructor(opts) { - this.verifyEvent = opts.verifyEvent; - this._WebSocket = opts.websocketImplementation; - } - async ensureRelay(url, params) { - url = normalizeURL(url); - let relay = this.relays.get(url); - if (!relay) { - relay = new AbstractRelay(url, { - verifyEvent: this.trustedRelayURLs.has(url) ? alwaysTrue : this.verifyEvent, - websocketImplementation: this._WebSocket - }); - if (params?.connectionTimeout) - relay.connectionTimeout = params.connectionTimeout; - this.relays.set(url, relay); - } - await relay.connect(); - return relay; - } - close(relays) { - relays.map(normalizeURL).forEach((url) => { - this.relays.get(url)?.close(); - }); - } - subscribeMany(relays, filters, params) { - return this.subscribeManyMap(Object.fromEntries(relays.map((url) => [url, filters])), params); - } - subscribeManyMap(requests, params) { - if (this.trackRelays) { - params.receivedEvent = (relay, id) => { - let set = this.seenOn.get(id); - if (!set) { - set = /* @__PURE__ */ new Set(); - this.seenOn.set(id, set); - } - set.add(relay); - }; - } - const _knownIds = /* @__PURE__ */ new Set(); - const subs = []; - const relaysLength = Object.keys(requests).length; - const eosesReceived = []; - let handleEose = (i2) => { - eosesReceived[i2] = true; - if (eosesReceived.filter((a) => a).length === relaysLength) { - params.oneose?.(); - handleEose = () => { - }; - } - }; - const closesReceived = []; - let handleClose = (i2, reason) => { - handleEose(i2); - closesReceived[i2] = reason; - if (closesReceived.filter((a) => a).length === relaysLength) { - params.onclose?.(closesReceived); - handleClose = () => { - }; - } - }; - const localAlreadyHaveEventHandler = (id) => { - if (params.alreadyHaveEvent?.(id)) { - return true; - } - const have = _knownIds.has(id); - _knownIds.add(id); - return have; - }; - const allOpened = Promise.all( - Object.entries(requests).map(async (req, i2, arr) => { - if (arr.indexOf(req) !== i2) { - handleClose(i2, "duplicate url"); - return; - } - let [url, filters] = req; - url = normalizeURL(url); - let relay; - try { - relay = await this.ensureRelay(url, { - connectionTimeout: params.maxWait ? Math.max(params.maxWait * 0.8, params.maxWait - 1e3) : void 0 - }); - } catch (err) { - handleClose(i2, err?.message || String(err)); - return; - } - let subscription = relay.subscribe(filters, { - ...params, - oneose: () => handleEose(i2), - onclose: (reason) => handleClose(i2, reason), - alreadyHaveEvent: localAlreadyHaveEventHandler, - eoseTimeout: params.maxWait - }); - subs.push(subscription); - }) - ); - return { - async close() { - await allOpened; - subs.forEach((sub) => { - sub.close(); - }); - } - }; - } - subscribeManyEose(relays, filters, params) { - const subcloser = this.subscribeMany(relays, filters, { - ...params, - oneose() { - subcloser.close(); - } - }); - return subcloser; - } - async querySync(relays, filter, params) { - return new Promise(async (resolve) => { - const events = []; - this.subscribeManyEose(relays, [filter], { - ...params, - onevent(event) { - events.push(event); - }, - onclose(_) { - resolve(events); - } - }); - }); - } - async get(relays, filter, params) { - filter.limit = 1; - const events = await this.querySync(relays, filter, params); - events.sort((a, b) => b.created_at - a.created_at); - return events[0] || null; - } - publish(relays, event) { - return relays.map(normalizeURL).map(async (url, i2, arr) => { - if (arr.indexOf(url) !== i2) { - return Promise.reject("duplicate url"); - } - let r = await this.ensureRelay(url); - return r.publish(event); - }); - } - }; - var _WebSocket; - try { - _WebSocket = WebSocket; - } catch { - } - var SimplePool = class extends AbstractSimplePool { - constructor() { - super({ verifyEvent, websocketImplementation: _WebSocket }); - } - }; - - // node_modules/nostr-tools/lib/esm/nip05.js - var NIP05_REGEX = /^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/; - var _fetch; - try { - _fetch = fetch; - } catch { - } - async function queryProfile(fullname) { - const match = fullname.match(NIP05_REGEX); - if (!match) - return null; - const [_, name = "_", domain] = match; - try { - const url = `https://${domain}/.well-known/nostr.json?name=${name}`; - const res = await (await _fetch(url, { redirect: "error" })).json(); - let pubkey = res.names[name]; - return pubkey ? { pubkey, relays: res.relays?.[pubkey] } : null; - } catch (_e) { - return null; - } - } - - // metadata.ts - var import_lru_cache = __toESM(require_lru_cache(), 1); - var pool = window.nostrSharedPool || new SimplePool(); - var metadataCache = window.nostrMetadataCache || new import_lru_cache.default(2e3); - function fetchMetadata(pubkey, hints) { - let metadata = metadataCache.get(pubkey); - if (metadata) - return metadata; - const relays = ["wss://purplepag.es", "wss://user.kindpag.es", "wss://relay.nos.social"]; - relays.push(...hints); - let promise = new Promise( - (resolve, reject) => pool.subscribeManyEose( - relays, - [ - { - kinds: [0], - authors: [pubkey] - } - ], - { - onevent(evt) { - try { - resolve(JSON.parse(evt.content)); - } catch (err) { - } - }, - onclose: reject - } - ) - ); - metadataCache.set(pubkey, promise); - return promise; - } - async function inputToPubkey(input) { - try { - const { type, data } = decode(input); - if (type === "nprofile") { - return [data.pubkey, data.relays || []]; - } else if (type === "npub") { - return [data, []]; - } - } catch (err) { - if (input.match(/[0-9a-f]{64}/)) { - return [input, []]; - } else if (input.match(".")) { - let res = await queryProfile(input); - if (!res) - return [void 0]; - return [res.pubkey, res.relays || []]; - } - } - return [void 0]; - } - - // nostr-picture.ts - var import_debounce = __toESM(require_debounce(), 1); - - // utils.ts - var transparentPixel = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=="; - function handleImageError(ev) { - const el = ev.target; - console.log("error loading image", ev); - if (el.src !== transparentPixel) { - el.src = transparentPixel; - } - } - - // nostr-picture.ts - var NostrPicture = class extends HTMLElement { - img; - constructor() { - super(); - this.img = document.createElement("img"); - this.img.setAttribute("part", "img"); - this.img.onerror = handleImageError; - this.attachShadow({ mode: "open" }); - const { shadowRoot } = this; - shadowRoot.appendChild(this.img); - } - connectedCallback() { - this.style.display = "inline-block"; - this.style.width = "fit-content"; - this.style.height = "fit-content"; - this.set(); - } - attributeChangedCallback(name, _, value) { - if (name === "pubkey") - this.set(); - else if (name === "width" || name === "height") - this.img.setAttribute(name, value); - } - set = (0, import_debounce.default)(async () => { - let input = this.getAttribute("pubkey"); - if (input) { - let [pubkey, hints] = await inputToPubkey(input); - if (pubkey) { - let metadata = await fetchMetadata(pubkey, hints || []); - this.img.src = metadata.picture || transparentPixel; - let name = metadata.name || metadata.display_name || npubEncode(pubkey); - this.img.alt = `picture for "${name}"`; - } - } - }, 200); - }; - __publicField(NostrPicture, "observedAttributes", ["pubkey", "width", "height"]); - window.customElements.define("nostr-picture", NostrPicture); -})(); diff --git a/public/main.js b/public/main.js index 719861f..b08e1fc 100644 --- a/public/main.js +++ b/public/main.js @@ -1,35 +1,58 @@ -import { nip19, SimplePool } from "nostr-tools"; +import { LitElement, html, css } from "lit"; +import { repeat } from "lit/directives/repeat.js"; +import "./components/nsite-card.js"; +import { pool, relays } from "./pool.js"; -const relays = ["wss://relay.damus.io", "wss://nos.lol", "wss://nostr.wine"]; -const pool = new SimplePool(); +export class NsiteApp extends LitElement { + static properties = { + selected: { state: true }, + status: { state: true, type: String }, + sites: { state: true, type: Array }, + }; -const seen = new Set(); -function addSite(event) { - if (seen.has(event.pubkey)) return; - seen.add(event.pubkey); + static styles = css` + .sites { + display: flex; + gap: 0.5em; + flex-wrap: wrap; + } + `; - try { - const template = document.getElementById("site"); - const site = template.content.cloneNode(true); - const npub = nip19.npubEncode(event.pubkey); + seen = new Set(); + constructor() { + super(); + this.sites = []; + } - site.querySelector("nostr-name").setAttribute("pubkey", event.pubkey); - site.querySelector("nostr-name").textContent = npub.slice(0, 8); - site.querySelector("nostr-picture").setAttribute("pubkey", event.pubkey); + connectedCallback() { + super.connectedCallback(); - site - .querySelector(".nsite-link") - ?.setAttribute("href", new URL("/", `${location.protocol}//${npub}.${location.host}`).toString()); - site.querySelector("time").textContent = new Date(event.created_at * 1000).toDateString(); + pool.subscribeMany(relays, [{ kinds: [34128], "#d": ["/index.html"] }], { + onevent: (event) => { + if (this.seen.has(event.pubkey)) return; + this.seen.add(event.pubkey); - document.getElementById("sites").appendChild(site); - } catch (error) { - console.log("Failed to add site", event); - console.log(error); + this.sites = [...this.sites, event].sort((a, b) => b.created_at - a.created_at); + }, + }); + } + + render() { + return html`
+ +

nsite

+ Source Code + +

Latest nsites:

+
+ ${repeat( + this.sites, + (nsite) => nsite.pubkey, + (nsite) => html``, + )} +
+
`; } } -console.log("Loading sites"); -pool.subscribeMany(relays, [{ kinds: [34128], "#d": ["/index.html"] }], { - onevent: addSite, -}); +customElements.define("nsite-app", NsiteApp); diff --git a/public/pool.js b/public/pool.js new file mode 100644 index 0000000..d333c8c --- /dev/null +++ b/public/pool.js @@ -0,0 +1,4 @@ +import { SimplePool } from "nostr-tools"; + +export const relays = ["wss://relay.damus.io", "wss://nos.lol", "wss://nostr.wine"]; +export const pool = new SimplePool(); diff --git a/src/env.ts b/src/env.ts index 3c0fa45..c1c6ccb 100644 --- a/src/env.ts +++ b/src/env.ts @@ -5,7 +5,10 @@ const LOOKUP_RELAYS = process.env.LOOKUP_RELAYS?.split(",").map((u) => u.trim()) "wss://user.kindpag.es/", "wss://purplepag.es/", ]; -const SUBSCRIPTION_RELAYS = process.env.SUBSCRIPTION_RELAYS?.split(",").map((u) => u.trim()) ?? []; +const SUBSCRIPTION_RELAYS = process.env.SUBSCRIPTION_RELAYS?.split(",").map((u) => u.trim()) ?? [ + "wss://nos.lol", + "wss://relay.damus.io", +]; const BLOSSOM_SERVERS = process.env.BLOSSOM_SERVERS?.split(",").map((u) => u.trim()) ?? []; const MAX_FILE_SIZE = process.env.MAX_FILE_SIZE ? xbytes.parseSize(process.env.MAX_FILE_SIZE) : Infinity; @@ -17,6 +20,12 @@ const PAC_PROXY = process.env.PAC_PROXY; const TOR_PROXY = process.env.TOR_PROXY; const I2P_PROXY = process.env.I2P_PROXY; +const NSITE_HOST = process.env.NSITE_HOST || "0.0.0.0"; +const NSITE_PORT = process.env.NSITE_PORT ? parseInt(process.env.NSITE_PORT) : 3000; +const HOST = `${NSITE_HOST}:${NSITE_PORT}`; + +const SCREENSHOTS_DIR = process.env.SCREENSHOTS_DIR || "./screenshots"; + export { SUBSCRIPTION_RELAYS, LOOKUP_RELAYS, @@ -27,4 +36,8 @@ export { PAC_PROXY, TOR_PROXY, I2P_PROXY, + NSITE_HOST, + NSITE_PORT, + HOST, + SCREENSHOTS_DIR, }; diff --git a/src/index.ts b/src/index.ts index 00a7862..821dc56 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,21 +2,22 @@ import "./polyfill.js"; import Koa from "koa"; import serve from "koa-static"; -import path from "node:path"; +import path, { basename } from "node:path"; import cors from "@koa/cors"; import fs from "node:fs"; import { fileURLToPath } from "node:url"; import mime from "mime"; import morgan from "koa-morgan"; +import send from "koa-send"; import { resolveNpubFromHostname } from "./helpers/dns.js"; import { getNsiteBlobs, parseNsiteEvent } from "./events.js"; import { downloadFile, getUserBlossomServers } from "./blossom.js"; -import { BLOSSOM_SERVERS, NGINX_CACHE_DIR, SUBSCRIPTION_RELAYS } from "./env.js"; +import { BLOSSOM_SERVERS, HOST, NGINX_CACHE_DIR, NSITE_HOST, NSITE_PORT, SUBSCRIPTION_RELAYS } from "./env.js"; import { userDomains, userRelays, userServers } from "./cache.js"; -import { NSITE_KIND } from "./const.js"; import { invalidatePubkeyPath } from "./nginx.js"; import pool, { getUserOutboxes, subscribeForEvents } from "./nostr.js"; +import { getScreenshotPath, hasScreenshot, removeScreenshot, takeScreenshot } from "./screenshots.js"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -43,7 +44,7 @@ app.use(async (ctx, next) => { } catch (err) { console.log(err); ctx.status = 500; - ctx.body = { message: "Something went wrong" }; + if (err instanceof Error) ctx.body = { message: err.message }; } }); @@ -84,6 +85,10 @@ app.use(async (ctx, next) => { } } + relays.push(...SUBSCRIPTION_RELAYS); + + if (relays.length === 0) throw new Error("No nostr relays"); + console.log(`${pubkey}: Searching for ${ctx.path}`); const blobs = await getNsiteBlobs(pubkey, ctx.path, relays); @@ -145,26 +150,39 @@ try { app.use(serve(www)); } -app.listen( - { - port: process.env.NSITE_PORT || 3000, - host: process.env.NSITE_HOST || "0.0.0.0", - }, - () => { - console.log("Started on port", process.env.PORT || 3000); - }, -); +// get screenshots for websites +app.use(async (ctx, next) => { + if (ctx.method === "GET" && ctx.path.startsWith("/screenshot")) { + const [pubkey, etx] = basename(ctx.path).split("."); -// invalidate nginx cache on new events -if (NGINX_CACHE_DIR && SUBSCRIPTION_RELAYS.length > 0) { + if (pubkey) { + if (!(await hasScreenshot(pubkey))) await takeScreenshot(pubkey); + + await send(ctx, getScreenshotPath(pubkey)); + } else throw Error("Missing pubkey"); + } else return next(); +}); + +app.listen({ host: NSITE_HOST, port: NSITE_PORT }, () => { + console.log("Started on port", HOST); +}); + +// invalidate nginx cache and screenshots on new events +if (SUBSCRIPTION_RELAYS.length > 0) { console.log(`Listening for new nsite events`); - subscribeForEvents(SUBSCRIPTION_RELAYS, async (event) => { try { const nsite = parseNsiteEvent(event); if (nsite) { - console.log(`${nsite.pubkey}: Invalidating ${nsite.path}`); - await invalidatePubkeyPath(nsite.pubkey, nsite.path); + if (NGINX_CACHE_DIR) { + console.log(`${nsite.pubkey}: Invalidating ${nsite.path}`); + await invalidatePubkeyPath(nsite.pubkey, nsite.path); + } + + // invalidate screenshot for nsite + if (nsite.path === "/" || nsite.path === "/index.html") { + await removeScreenshot(nsite.pubkey); + } } } catch (error) { console.log(`Failed to invalidate ${event.id}`); diff --git a/src/screenshots.ts b/src/screenshots.ts new file mode 100644 index 0000000..c04e3bd --- /dev/null +++ b/src/screenshots.ts @@ -0,0 +1,40 @@ +import { nip19 } from "nostr-tools"; +import puppeteer from "puppeteer"; +import { join } from "path"; +import pfs from "fs/promises"; + +import { NSITE_PORT, SCREENSHOTS_DIR } from "./env.js"; + +try { + await pfs.mkdir(SCREENSHOTS_DIR, { recursive: true }); +} catch (error) {} + +export function getScreenshotPath(pubkey: string) { + return join(SCREENSHOTS_DIR, pubkey + ".png"); +} + +export async function hasScreenshot(pubkey: string) { + try { + await pfs.stat(getScreenshotPath(pubkey)); + return true; + } catch (error) { + return false; + } +} + +export async function takeScreenshot(pubkey: string) { + console.log(`${pubkey}: Generating screenshot`); + + const browser = await puppeteer.launch(); + const page = await browser.newPage(); + const url = new URL(`http://${nip19.npubEncode(pubkey)}.localhost:${NSITE_PORT}`); + await page.goto(url.toString()); + await page.screenshot({ path: getScreenshotPath(pubkey) }); + await browser.close(); +} + +export async function removeScreenshot(pubkey: string) { + try { + await pfs.rm(getScreenshotPath(pubkey)); + } catch (error) {} +}