From e5f0b354ae8125f3ad04573b4af1057f96c3deda Mon Sep 17 00:00:00 2001 From: Cafe137 <77121044+Cafe137@users.noreply.github.com> Date: Mon, 22 May 2023 20:11:10 +0200 Subject: [PATCH] feat!: change http library (#842) * feat!: change http library --- .github/workflows/tests.yaml | 10 +- README.md | 2 +- package-lock.json | 829 ++---------------- package.json | 11 +- src/bee-debug.ts | 240 ++--- src/bee.ts | 272 +++--- src/chunk/soc.ts | 35 +- src/feed/index.ts | 62 +- src/feed/json.ts | 16 +- src/feed/retrievable.ts | 21 +- src/index.ts | 6 +- src/modules/bytes.ts | 38 +- src/modules/bzz.ts | 62 +- src/modules/chunk.ts | 33 +- src/modules/debug/balance.ts | 40 +- src/modules/debug/chequebook.ts | 84 +- src/modules/debug/chunk.ts | 27 +- src/modules/debug/connectivity.ts | 53 +- src/modules/debug/settlements.ts | 21 +- src/modules/debug/stake.ts | 37 +- src/modules/debug/stamps.ts | 69 +- src/modules/debug/states.ts | 29 +- src/modules/debug/status.ts | 56 +- src/modules/debug/tag.ts | 13 +- src/modules/debug/transactions.ts | 40 +- src/modules/feed.ts | 37 +- src/modules/pinning.ts | 33 +- src/modules/pss.ts | 19 +- src/modules/soc.ts | 17 +- src/modules/status.ts | 10 +- src/modules/stewardship.ts | 19 +- src/modules/tag.ts | 45 +- src/types/debug.ts | 4 +- src/types/index.ts | 78 +- src/utils/error.ts | 37 - src/utils/headers.ts | 8 +- src/utils/http.ts | 191 +--- src/utils/merge.ts | 34 - src/utils/sleep.ts | 8 - src/utils/tar.ts | 4 +- src/utils/type.ts | 26 +- test/integration/bee-class.spec.ts | 18 +- test/integration/bee-debug-class.spec.ts | 6 +- test/integration/chunk/bmt.spec.ts | 6 +- test/integration/chunk/cac.spec.ts | 8 +- test/integration/chunk/soc.spec.ts | 10 +- test/integration/feed/index.spec.ts | 30 +- test/integration/modules/bytes.spec.ts | 4 +- test/integration/modules/bzz.spec.ts | 6 +- test/integration/modules/chunk.spec.ts | 4 +- .../integration/modules/debug/balance.spec.ts | 6 +- .../modules/debug/chequebook.spec.ts | 8 +- .../modules/debug/connectivity.spec.ts | 6 +- .../modules/debug/settlements.spec.ts | 4 +- test/integration/modules/debug/states.spec.ts | 4 +- test/integration/modules/debug/status.spec.ts | 14 +- test/integration/modules/debug/tag.spec.ts | 4 +- .../modules/debug/transactions.spec.ts | 2 +- test/integration/modules/feed.spec.ts | 6 +- test/integration/modules/pinning.spec.ts | 16 +- test/integration/modules/pss.spec.ts | 4 +- test/integration/modules/tag.spec.ts | 4 +- test/tests-setup.ts | 28 +- test/unit/assertions.ts | 29 +- test/unit/bee-class.spec.ts | 193 +--- test/unit/bee-debug-class.spec.ts | 58 +- test/unit/utils/http.spec.ts | 31 +- test/utils.ts | 44 +- 68 files changed, 1070 insertions(+), 2159 deletions(-) delete mode 100644 src/utils/merge.ts delete mode 100644 src/utils/sleep.ts diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index da7f2d71..961cb471 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -36,28 +36,28 @@ jobs: cache: 'npm' - name: Install npm deps - run: npm install -g npm && npm ci + run: npm install -g npm && npm ci && npm install -g @ethersphere/bee-factory # Start Bee Factory environment - name: Start Bee Factory environment - if: matrix.node-version != '18.x' + if: matrix.node-version != '18.x' run: npm run bee -- --verbose --detach # Start Bee Factory environment for Node 18 - name: Start Bee Factory environment for Node 18 - if: matrix.node-version == '18.x' + if: matrix.node-version == '18.x' env: NODE_OPTIONS: '--no-experimental-fetch' run: npm run bee -- --verbose --detach - name: Tests Node 18 - if: matrix.node-version == '18.x' + if: matrix.node-version == '18.x' env: NODE_OPTIONS: '--no-experimental-fetch' run: npm run test - name: Tests non-Node 18 - if: matrix.node-version != '18.x' + if: matrix.node-version != '18.x' run: npm run test - name: Debug workflow if failed diff --git a/README.md b/README.md index 4cd7fe4d..779c2c61 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ **Warning: This project is in beta state. There might (and most probably will) be changes in the future to its API and working. Also, no guarantees can be made about its stability, efficiency, and security at this stage.** -This project is intended to be used with **Bee version 1.12.0**. Using it with older or newer Bee versions is not recommended and may not work. Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6) and by keeping an eye on the [releases tab](https://github.com/ethersphere/bee-js/releases). +This project is intended to be used with **Bee version 1.13.0**. Using it with older or newer Bee versions is not recommended and may not work. Stay up to date by joining the [official Discord](https://discord.gg/GU22h2utj6) and by keeping an eye on the [releases tab](https://github.com/ethersphere/bee-js/releases). ## Table of Contents diff --git a/package-lock.json b/package-lock.json index 7014e0e7..a428091e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,21 +6,19 @@ "packages": { "": { "name": "@ethersphere/bee-js", - "version": "5.1.1", + "version": "5.2.0", "license": "BSD-3-Clause", "dependencies": { "@ethersphere/swarm-cid": "^0.1.0", "@types/readable-stream": "^2.3.13", - "bufferutil": "^4.0.6", + "axios": "^1.3.4", + "cafe-utility": "^9.0.1", "elliptic": "^6.5.4", "fetch-blob": "2.1.2", "isomorphic-ws": "^4.0.1", "js-sha3": "^0.8.0", - "ky": "^0.33.2", - "ky-universal": "^0.11.0", "semver": "^7.3.5", "tar-js": "^0.3.0", - "utf-8-validate": "^5.0.9", "web-streams-polyfill": "^4.0.0-beta.3", "ws": "^8.7.0" }, @@ -33,7 +31,6 @@ "@babel/preset-typescript": "^7.18.6", "@commitlint/cli": "^17.0.2", "@commitlint/config-conventional": "^17.4.2", - "@ethersphere/bee-factory": "^0.5.2", "@fluffy-spoon/substitute": "^1.208.0", "@naholyr/cross-env": "^1.0.0", "@types/chai": "^4.3.4", @@ -79,7 +76,7 @@ "webpack-cli": "^5.0.1" }, "engines": { - "bee": "1.11.1-1992b846", + "bee": "1.13.0-f1067884", "beeApiVersion": "4.0.0", "beeDebugApiVersion": "4.0.0", "node": ">=14.0.0", @@ -1784,11 +1781,6 @@ "node": ">=6.9.0" } }, - "node_modules/@balena/dockerignore": { - "version": "1.0.2", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/@commitlint/cli": { "version": "17.0.2", "dev": true, @@ -2307,219 +2299,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@ethersphere/bee-factory": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/@ethersphere/bee-factory/-/bee-factory-0.5.2.tgz", - "integrity": "sha512-WPEAAhROqYCV8z4NwFpeni9dyPnSHgw0ylT0WaHWcdsgbVN2Z/pLQ84zJsUiNzaibaBg6P7L5dlegR8xUuEX3A==", - "dev": true, - "dependencies": { - "@ethersphere/bee-js": "^5.0.0", - "chalk": "^4.1.2", - "dockerode": "^3.3.4", - "furious-commander": "^1.7.1", - "node-fetch": "3.0.0-beta.9", - "ora": "^5.3.0", - "semver": "^7.3.8" - }, - "bin": { - "bee-factory": "dist/src/index.js" - }, - "engines": { - "bee": "1.9.0", - "node": ">=12.0.0", - "npm": ">=6.0.0", - "supportedBee": ">=1.9.0" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/ansi-styles": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/chalk": { - "version": "4.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/color-convert": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/color-name": { - "version": "1.1.4", - "dev": true, - "license": "MIT" - }, - "node_modules/@ethersphere/bee-factory/node_modules/has-flag": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/lru-cache": { - "version": "6.0.0", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/node-fetch": { - "version": "3.0.0-beta.9", - "dev": true, - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^3.0.1", - "fetch-blob": "^2.1.1" - }, - "engines": { - "node": "^10.17 || >=12.3" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/semver": { - "version": "7.3.8", - "dev": true, - "license": "ISC", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/supports-color": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@ethersphere/bee-factory/node_modules/yallist": { - "version": "4.0.0", - "dev": true, - "license": "ISC" - }, - "node_modules/@ethersphere/bee-js": { - "version": "5.0.0", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@ethersphere/swarm-cid": "^0.1.0", - "@types/readable-stream": "^2.3.13", - "bufferutil": "^4.0.6", - "elliptic": "^6.5.4", - "fetch-blob": "2.1.2", - "isomorphic-ws": "^4.0.1", - "js-sha3": "^0.8.0", - "ky": "^0.25.1", - "ky-universal": "^0.8.2", - "semver": "^7.3.5", - "tar-js": "^0.3.0", - "utf-8-validate": "^5.0.9", - "web-streams-polyfill": "^4.0.0-beta.1", - "ws": "^8.7.0" - }, - "engines": { - "bee": "1.7.0-bbf13011", - "beeApiVersion": "3.0.2", - "beeDebugApiVersion": "3.0.2", - "node": ">=14.0.0", - "npm": ">=6.0.0" - } - }, - "node_modules/@ethersphere/bee-js/node_modules/ky": { - "version": "0.25.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/ky?sponsor=1" - } - }, - "node_modules/@ethersphere/bee-js/node_modules/ky-universal": { - "version": "0.8.2", - "dev": true, - "license": "MIT", - "dependencies": { - "abort-controller": "^3.0.0", - "node-fetch": "3.0.0-beta.9" - }, - "engines": { - "node": ">=10.17" - }, - "funding": { - "url": "https://github.com/sindresorhus/ky-universal?sponsor=1" - }, - "peerDependencies": { - "ky": ">=0.17.0", - "web-streams-polyfill": ">=2.0.0" - }, - "peerDependenciesMeta": { - "web-streams-polyfill": { - "optional": true - } - } - }, - "node_modules/@ethersphere/bee-js/node_modules/node-fetch": { - "version": "3.0.0-beta.9", - "dev": true, - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^3.0.1", - "fetch-blob": "^2.1.1" - }, - "engines": { - "node": "^10.17 || >=12.3" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, "node_modules/@ethersphere/swarm-cid": { "version": "0.1.0", "license": "BSD-3-Clause", @@ -3524,16 +3303,6 @@ "dev": true, "license": "Apache-2.0" }, - "node_modules/abort-controller": { - "version": "3.0.0", - "license": "MIT", - "dependencies": { - "event-target-shim": "^5.0.0" - }, - "engines": { - "node": ">=6.5" - } - }, "node_modules/acorn": { "version": "8.8.2", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.8.2.tgz", @@ -3737,14 +3506,6 @@ "node": ">=0.10.0" } }, - "node_modules/asn1": { - "version": "0.2.6", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": "~2.1.0" - } - }, "node_modules/assertion-error": { "version": "1.1.0", "dev": true, @@ -3753,6 +3514,11 @@ "node": "*" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/available-typed-arrays": { "version": "1.0.5", "dev": true, @@ -3764,6 +3530,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axios": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.3.4.tgz", + "integrity": "sha512-toYm+Bsyl6VC5wSkfkbbNB6ROv7KY93PEBBL6xyDczaIHasAiv4wPqQ/c4RjoQzipxRD2W5g21cOqQulZ7rHwQ==", + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/babel-loader": { "version": "9.1.0", "dev": true, @@ -3859,14 +3635,6 @@ ], "license": "MIT" }, - "node_modules/bcrypt-pbkdf": { - "version": "1.0.2", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tweetnacl": "^0.14.3" - } - }, "node_modules/big.js": { "version": "5.2.2", "dev": true, @@ -3883,16 +3651,6 @@ "node": ">=8" } }, - "node_modules/bl": { - "version": "4.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, "node_modules/blob-polyfill": { "version": "5.0.20210201", "dev": true, @@ -3963,52 +3721,15 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, - "node_modules/buffer": { - "version": "5.7.1", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, "node_modules/buffer-from": { "version": "1.1.1", "dev": true, "license": "MIT" }, - "node_modules/bufferutil": { - "version": "4.0.6", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, - "node_modules/buildcheck": { - "version": "0.0.3", - "dev": true, - "optional": true, - "engines": { - "node": ">=10.0.0" - } + "node_modules/cafe-utility": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/cafe-utility/-/cafe-utility-9.0.1.tgz", + "integrity": "sha512-QiTaoRPkK8UyBBsGwv4zJRM88JibhcQ2GRHsLYTq+JaKIK6UyW1xSOlerJWAFHS/r/SpXffCQxlNIeiOA7MgCQ==" }, "node_modules/call-bind": { "version": "1.0.2", @@ -4149,11 +3870,6 @@ "fsevents": "~2.3.2" } }, - "node_modules/chownr": { - "version": "1.1.4", - "dev": true, - "license": "ISC" - }, "node_modules/chrome-trace-event": { "version": "1.0.3", "dev": true, @@ -4202,17 +3918,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cli-cursor": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "restore-cursor": "^3.1.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/cli-spinners": { "version": "2.6.1", "dev": true, @@ -4255,6 +3960,17 @@ "dev": true, "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "9.5.0", "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz", @@ -4409,19 +4125,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cpu-features": { - "version": "0.0.4", - "dev": true, - "hasInstallScript": true, - "optional": true, - "dependencies": { - "buildcheck": "0.0.3", - "nan": "^2.15.0" - }, - "engines": { - "node": ">=10.0.0" - } - }, "node_modules/cpy": { "version": "9.0.1", "dev": true, @@ -4574,14 +4277,6 @@ "node": ">=8" } }, - "node_modules/data-uri-to-buffer": { - "version": "3.0.1", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, "node_modules/debug": { "version": "4.3.4", "dev": true, @@ -4698,6 +4393,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/depcheck": { "version": "1.4.3", "dev": true, @@ -4789,44 +4492,6 @@ "node": ">=8" } }, - "node_modules/docker-modem": { - "version": "3.0.6", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "debug": "^4.1.1", - "readable-stream": "^3.5.0", - "split-ca": "^1.0.1", - "ssh2": "^1.11.0" - }, - "engines": { - "node": ">= 8.0" - } - }, - "node_modules/dockerode": { - "version": "3.3.4", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@balena/dockerignore": "^1.0.2", - "docker-modem": "^3.0.0", - "tar-fs": "~2.0.1" - }, - "engines": { - "node": ">= 8.0" - } - }, - "node_modules/dockerode/node_modules/tar-fs": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.0.0" - } - }, "node_modules/doctrine": { "version": "3.0.0", "dev": true, @@ -4896,14 +4561,6 @@ "node": ">= 4" } }, - "node_modules/end-of-stream": { - "version": "1.4.4", - "dev": true, - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, "node_modules/enhanced-resolve": { "version": "5.12.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.12.0.tgz", @@ -5465,13 +5122,6 @@ "node": ">=0.10.0" } }, - "node_modules/event-target-shim": { - "version": "5.0.1", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/events": { "version": "3.3.0", "dev": true, @@ -5667,57 +5317,46 @@ "dev": true, "license": "ISC" }, - "node_modules/for-each": { - "version": "0.3.3", - "dev": true, - "license": "MIT", - "dependencies": { - "is-callable": "^1.1.3" - } - }, - "node_modules/formdata-polyfill": { - "version": "4.0.10", - "license": "MIT", - "dependencies": { - "fetch-blob": "^3.1.2" - }, - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/formdata-polyfill/node_modules/fetch-blob": { - "version": "3.2.0", + "node_modules/follow-redirects": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz", + "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==", "funding": [ { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true } - ], + } + }, + "node_modules/for-each": { + "version": "0.3.3", + "dev": true, "license": "MIT", "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" + "is-callable": "^1.1.3" } }, - "node_modules/formdata-polyfill/node_modules/web-streams-polyfill": { - "version": "3.2.1", - "license": "MIT", + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, "engines": { - "node": ">= 8" + "node": ">= 6" } }, - "node_modules/fs-constants": { - "version": "1.0.0", - "dev": true, - "license": "MIT" - }, "node_modules/fs-extra": { "version": "10.1.0", "dev": true, @@ -5788,19 +5427,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/furious-commander": { - "version": "1.7.1", - "dev": true, - "license": "MIT", - "dependencies": { - "madlad": "^1.2.1", - "reflect-metadata": "^0.1.13" - }, - "engines": { - "node": ">=10.0.0", - "npm": ">=6.0.0" - } - }, "node_modules/generic-names": { "version": "2.0.1", "dev": true, @@ -6404,14 +6030,6 @@ "node": ">=0.10.0" } }, - "node_modules/is-interactive": { - "version": "1.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/is-map": { "version": "2.0.2", "dev": true, @@ -7159,91 +6777,6 @@ "node": ">=6" } }, - "node_modules/ky": { - "version": "0.33.2", - "resolved": "https://registry.npmjs.org/ky/-/ky-0.33.2.tgz", - "integrity": "sha512-f6oS2rKUcPu5FzdqCDbFpmzis/JlqFZw8uIHm/jf8Kc3vtnW+VDhuashOAKyBZv8bFiZFZUMNxTC0JtahEvujA==", - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sindresorhus/ky?sponsor=1" - } - }, - "node_modules/ky-universal": { - "version": "0.11.0", - "license": "MIT", - "dependencies": { - "abort-controller": "^3.0.0", - "node-fetch": "^3.2.10" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sindresorhus/ky-universal?sponsor=1" - }, - "peerDependencies": { - "ky": ">=0.31.4", - "web-streams-polyfill": ">=3.2.1" - }, - "peerDependenciesMeta": { - "web-streams-polyfill": { - "optional": true - } - } - }, - "node_modules/ky-universal/node_modules/data-uri-to-buffer": { - "version": "4.0.0", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/ky-universal/node_modules/fetch-blob": { - "version": "3.2.0", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" - } - }, - "node_modules/ky-universal/node_modules/node-fetch": { - "version": "3.3.0", - "license": "MIT", - "dependencies": { - "data-uri-to-buffer": "^4.0.0", - "fetch-blob": "^3.1.4", - "formdata-polyfill": "^4.0.10" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/node-fetch" - } - }, - "node_modules/ky-universal/node_modules/web-streams-polyfill": { - "version": "3.2.1", - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, "node_modules/levn": { "version": "0.4.1", "dev": true, @@ -7447,11 +6980,6 @@ "yallist": "^3.0.2" } }, - "node_modules/madlad": { - "version": "1.3.0", - "dev": true, - "license": "MIT" - }, "node_modules/magic-string": { "version": "0.25.7", "dev": true, @@ -7609,7 +7137,6 @@ }, "node_modules/mime-db": { "version": "1.47.0", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -7617,7 +7144,6 @@ }, "node_modules/mime-types": { "version": "2.1.30", - "dev": true, "license": "MIT", "dependencies": { "mime-db": "1.47.0" @@ -7687,11 +7213,6 @@ "node": ">=0.10.0" } }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "dev": true, - "license": "MIT" - }, "node_modules/mocha": { "version": "10.2.0", "dev": true, @@ -7901,12 +7422,6 @@ "node": ">=8" } }, - "node_modules/nan": { - "version": "2.17.0", - "dev": true, - "license": "MIT", - "optional": true - }, "node_modules/nanoid": { "version": "3.3.3", "dev": true, @@ -7966,32 +7481,6 @@ "node": ">= 10.13" } }, - "node_modules/node-domexception": { - "version": "1.0.0", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-gyp-build": { - "version": "4.3.0", - "license": "MIT", - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } - }, "node_modules/node-releases": { "version": "2.0.6", "dev": true, @@ -8124,92 +7613,6 @@ "node": ">= 0.8.0" } }, - "node_modules/ora": { - "version": "5.4.1", - "dev": true, - "license": "MIT", - "dependencies": { - "bl": "^4.1.0", - "chalk": "^4.1.0", - "cli-cursor": "^3.1.0", - "cli-spinners": "^2.5.0", - "is-interactive": "^1.0.0", - "is-unicode-supported": "^0.1.0", - "log-symbols": "^4.1.0", - "strip-ansi": "^6.0.0", - "wcwidth": "^1.0.1" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ora/node_modules/ansi-styles": { - "version": "4.3.0", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/ora/node_modules/chalk": { - "version": "4.1.2", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/ora/node_modules/color-convert": { - "version": "2.0.1", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/ora/node_modules/color-name": { - "version": "1.1.4", - "dev": true, - "license": "MIT" - }, - "node_modules/ora/node_modules/has-flag": { - "version": "4.0.0", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ora/node_modules/supports-color": { - "version": "7.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/p-event": { "version": "4.2.0", "dev": true, @@ -9007,20 +8410,16 @@ "node": ">= 8" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/pseudomap": { "version": "1.0.2", "dev": true, "license": "ISC" }, - "node_modules/pump": { - "version": "3.0.0", - "dev": true, - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, "node_modules/punycode": { "version": "2.1.1", "dev": true, @@ -9254,11 +8653,6 @@ "node": ">=8" } }, - "node_modules/reflect-metadata": { - "version": "0.1.13", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/regenerate": { "version": "1.4.2", "dev": true, @@ -9417,18 +8811,6 @@ "node": ">=8" } }, - "node_modules/restore-cursor": { - "version": "3.1.0", - "dev": true, - "license": "MIT", - "dependencies": { - "onetime": "^5.1.0", - "signal-exit": "^3.0.2" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/resumer": { "version": "0.0.0", "dev": true, @@ -9529,11 +8911,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "dev": true, - "license": "MIT" - }, "node_modules/sass": { "version": "1.32.10", "dev": true, @@ -9831,11 +9208,6 @@ "dev": true, "license": "CC0-1.0" }, - "node_modules/split-ca": { - "version": "1.0.1", - "dev": true, - "license": "ISC" - }, "node_modules/split2": { "version": "3.2.2", "dev": true, @@ -9849,22 +9221,6 @@ "dev": true, "license": "BSD-3-Clause" }, - "node_modules/ssh2": { - "version": "1.11.0", - "dev": true, - "hasInstallScript": true, - "dependencies": { - "asn1": "^0.2.4", - "bcrypt-pbkdf": "^1.0.2" - }, - "engines": { - "node": ">=10.16.0" - }, - "optionalDependencies": { - "cpu-features": "~0.0.4", - "nan": "^2.16.0" - } - }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -10126,21 +9482,6 @@ "node_modules/tar-js": { "version": "0.3.0" }, - "node_modules/tar-stream": { - "version": "2.2.0", - "dev": true, - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/temp-dir": { "version": "2.0.0", "dev": true, @@ -10437,11 +9778,6 @@ "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" } }, - "node_modules/tweetnacl": { - "version": "0.14.5", - "dev": true, - "license": "Unlicense" - }, "node_modules/type-check": { "version": "0.4.0", "dev": true, @@ -10595,17 +9931,6 @@ "punycode": "^2.1.0" } }, - "node_modules/utf-8-validate": { - "version": "5.0.9", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "node-gyp-build": "^4.3.0" - }, - "engines": { - "node": ">=6.14.2" - } - }, "node_modules/util-deprecate": { "version": "1.0.2", "dev": true, diff --git a/package.json b/package.json index b3209db9..89912109 100644 --- a/package.json +++ b/package.json @@ -55,21 +55,19 @@ "lint": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\" && prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "lint:check": "eslint \"src/**/*.ts\" \"test/**/*.ts\" && prettier --check \"src/**/*.ts\" \"test/**/*.ts\"", "depcheck": "depcheck .", - "bee": "bee-factory start" + "bee": "npx bee-factory start" }, "dependencies": { "@ethersphere/swarm-cid": "^0.1.0", "@types/readable-stream": "^2.3.13", - "bufferutil": "^4.0.6", + "axios": "^1.3.4", + "cafe-utility": "^9.0.1", "elliptic": "^6.5.4", "fetch-blob": "2.1.2", "isomorphic-ws": "^4.0.1", "js-sha3": "^0.8.0", - "ky": "^0.33.2", - "ky-universal": "^0.11.0", "semver": "^7.3.5", "tar-js": "^0.3.0", - "utf-8-validate": "^5.0.9", "web-streams-polyfill": "^4.0.0-beta.3", "ws": "^8.7.0" }, @@ -82,7 +80,6 @@ "@babel/preset-typescript": "^7.18.6", "@commitlint/cli": "^17.0.2", "@commitlint/config-conventional": "^17.4.2", - "@ethersphere/bee-factory": "^0.5.2", "@fluffy-spoon/substitute": "^1.208.0", "@naholyr/cross-env": "^1.0.0", "@types/chai": "^4.3.4", @@ -132,6 +129,6 @@ "npm": ">=6.0.0", "beeApiVersion": "4.0.0", "beeDebugApiVersion": "4.0.0", - "bee": "1.12.0-88c1d236" + "bee": "1.13.0-f1067884" } } diff --git a/src/bee-debug.ts b/src/bee-debug.ts index 409eb651..ddd724d9 100644 --- a/src/bee-debug.ts +++ b/src/bee-debug.ts @@ -7,12 +7,14 @@ import * as states from './modules/debug/states' import * as status from './modules/debug/status' import * as transactions from './modules/debug/transactions' +import { Objects, System } from 'cafe-utility' import * as stamps from './modules/debug/stamps' import * as tag from './modules/debug/tag' import type { Address, AllSettlements, BalanceResponse, + BeeRequestOptions, BeeVersions, ChainState, ChequebookAddressResponse, @@ -44,7 +46,6 @@ import { BeeOptions, CashoutOptions, PostageBatchOptions, - RequestOptions, STAMPS_DEPTH_MAX, STAMPS_DEPTH_MIN, Tag, @@ -65,13 +66,6 @@ import { } from './utils/type' import { assertBeeUrl, stripLastSlash } from './utils/url' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky-universal' - -import { DEFAULT_KY_CONFIG, wrapRequestClosure, wrapResponseClosure } from './utils/http' -import { deepMerge } from './utils/merge' -import { sleep } from './utils/sleep' - export class BeeDebug { /** * URL on which is the Debug API of Bee node exposed @@ -82,7 +76,7 @@ export class BeeDebug { * Ky instance that defines connection to Bee node * @private */ - private readonly kyOptions: KyOptions + private readonly requestOptions: BeeRequestOptions constructor(url: string, options?: BeeOptions) { assertBeeUrl(url) @@ -92,42 +86,32 @@ export class BeeDebug { // unnecessary redirects. this.url = stripLastSlash(url) - const kyOptions: KyOptions = { - prefixUrl: this.url, + const requestOptions: BeeRequestOptions = { + baseURL: this.url, timeout: options?.timeout ?? false, - retry: options?.retry, - fetch: options?.fetch, - hooks: { - beforeRequest: [], - afterResponse: [], - }, } - if (options?.defaultHeaders) { - kyOptions.headers = options.defaultHeaders + if (options?.headers) { + requestOptions.headers = options.headers } if (options?.onRequest) { - kyOptions.hooks!.beforeRequest!.push(wrapRequestClosure(options.onRequest)) - } - - if (options?.onResponse) { - kyOptions.hooks!.afterResponse!.push(wrapResponseClosure(options.onResponse)) + requestOptions.onRequest = options.onRequest } - this.kyOptions = deepMerge(DEFAULT_KY_CONFIG, kyOptions) + this.requestOptions = requestOptions } - async getNodeAddresses(options?: RequestOptions): Promise { + async getNodeAddresses(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return connectivity.getNodeAddresses(this.getKyOptionsForCall(options)) + return connectivity.getNodeAddresses(this.getRequestOptionsForCall(options)) } - async getBlocklist(options?: RequestOptions): Promise { + async getBlocklist(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return connectivity.getBlocklist(this.getKyOptionsForCall(options)) + return connectivity.getBlocklist(this.getRequestOptionsForCall(options)) } /** @@ -140,7 +124,7 @@ export class BeeDebug { * @see [Bee API reference - `GET /tags/{uid}`](https://docs.ethswarm.org/debug-api/#tag/Tag) * */ - async retrieveExtendedTag(tagUid: number | Tag, options?: RequestOptions): Promise { + async retrieveExtendedTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise { assertRequestOptions(options) if (isTag(tagUid)) { @@ -151,36 +135,36 @@ export class BeeDebug { throw new TypeError('tagUid has to be either Tag or a number (UID)!') } - return tag.retrieveExtendedTag(this.getKyOptionsForCall(options), tagUid) + return tag.retrieveExtendedTag(this.getRequestOptionsForCall(options), tagUid) } /** * Get list of peers for this node */ - async getPeers(options?: RequestOptions): Promise { + async getPeers(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return connectivity.getPeers(this.getKyOptionsForCall(options)) + return connectivity.getPeers(this.getRequestOptionsForCall(options)) } - async removePeer(peer: string | Address, options?: RequestOptions): Promise { + async removePeer(peer: string | Address, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertAddress(peer) - return connectivity.removePeer(this.getKyOptionsForCall(options), peer) + return connectivity.removePeer(this.getRequestOptionsForCall(options), peer) } - async getTopology(options?: RequestOptions): Promise { + async getTopology(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return connectivity.getTopology(this.getKyOptionsForCall(options)) + return connectivity.getTopology(this.getRequestOptionsForCall(options)) } - async pingPeer(peer: string | Address, options?: RequestOptions): Promise { + async pingPeer(peer: string | Address, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertAddress(peer) - return connectivity.pingPeer(this.getKyOptionsForCall(options), peer) + return connectivity.pingPeer(this.getRequestOptionsForCall(options), peer) } /* @@ -190,10 +174,10 @@ export class BeeDebug { /** * Get the balances with all known peers including prepaid services */ - async getAllBalances(options?: RequestOptions): Promise { + async getAllBalances(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return balance.getAllBalances(this.getKyOptionsForCall(options)) + return balance.getAllBalances(this.getRequestOptionsForCall(options)) } /** @@ -201,20 +185,20 @@ export class BeeDebug { * * @param address Swarm address of peer */ - async getPeerBalance(address: Address | string, options?: RequestOptions): Promise { + async getPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertAddress(address) - return balance.getPeerBalance(this.getKyOptionsForCall(options), address) + return balance.getPeerBalance(this.getRequestOptionsForCall(options), address) } /** * Get the past due consumption balances with all known peers */ - async getPastDueConsumptionBalances(options?: RequestOptions): Promise { + async getPastDueConsumptionBalances(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return balance.getPastDueConsumptionBalances(this.getKyOptionsForCall(options)) + return balance.getPastDueConsumptionBalances(this.getRequestOptionsForCall(options)) } /** @@ -222,11 +206,11 @@ export class BeeDebug { * * @param address Swarm address of peer */ - async getPastDueConsumptionPeerBalance(address: Address | string, options?: RequestOptions): Promise { + async getPastDueConsumptionPeerBalance(address: Address | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertAddress(address) - return balance.getPastDueConsumptionPeerBalance(this.getKyOptionsForCall(options), address) + return balance.getPastDueConsumptionPeerBalance(this.getRequestOptionsForCall(options), address) } /* @@ -239,28 +223,28 @@ export class BeeDebug { * **Warning:** The address is returned with 0x prefix unlike all other calls. * https://github.com/ethersphere/bee/issues/1443 */ - async getChequebookAddress(options?: RequestOptions): Promise { + async getChequebookAddress(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return chequebook.getChequebookAddress(this.getKyOptionsForCall(options)) + return chequebook.getChequebookAddress(this.getRequestOptionsForCall(options)) } /** * Get the balance of the chequebook */ - async getChequebookBalance(options?: RequestOptions): Promise { + async getChequebookBalance(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return chequebook.getChequebookBalance(this.getKyOptionsForCall(options)) + return chequebook.getChequebookBalance(this.getRequestOptionsForCall(options)) } /** * Get last cheques for all peers */ - async getLastCheques(options?: RequestOptions): Promise { + async getLastCheques(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return chequebook.getLastCheques(this.getKyOptionsForCall(options)) + return chequebook.getLastCheques(this.getRequestOptionsForCall(options)) } /** @@ -270,12 +254,12 @@ export class BeeDebug { */ async getLastChequesForPeer( address: Address | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertAddress(address) - return chequebook.getLastChequesForPeer(this.getKyOptionsForCall(options), address) + return chequebook.getLastChequesForPeer(this.getRequestOptionsForCall(options), address) } /** @@ -283,11 +267,14 @@ export class BeeDebug { * * @param address Swarm address of peer */ - async getLastCashoutAction(address: Address | string, options?: RequestOptions): Promise { + async getLastCashoutAction( + address: Address | string, + options?: BeeRequestOptions, + ): Promise { assertRequestOptions(options) assertAddress(address) - return chequebook.getLastCashoutAction(this.getKyOptionsForCall(options), address) + return chequebook.getLastCashoutAction(this.getRequestOptionsForCall(options), address) } /** @@ -298,11 +285,15 @@ export class BeeDebug { * @param options.gasPrice Gas price for the cashout transaction in WEI * @param options.gasLimit Gas limit for the cashout transaction in WEI */ - async cashoutLastCheque(address: string | Address, options?: CashoutOptions): Promise { + async cashoutLastCheque( + address: string | Address, + options?: CashoutOptions, + requestOptions?: BeeRequestOptions, + ): Promise { assertCashoutOptions(options) assertAddress(address) - return chequebook.cashoutLastCheque(this.getKyOptionsForCall(options), address, options) + return chequebook.cashoutLastCheque(this.getRequestOptionsForCall(requestOptions), address, options) } /** @@ -315,7 +306,7 @@ export class BeeDebug { async depositTokens( amount: number | NumberString, gasPrice?: NumberString, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertNonNegativeInteger(amount) @@ -324,7 +315,7 @@ export class BeeDebug { assertNonNegativeInteger(gasPrice) } - return chequebook.depositTokens(this.getKyOptionsForCall(options), amount, gasPrice) + return chequebook.depositTokens(this.getRequestOptionsForCall(options), amount, gasPrice) } /** @@ -337,7 +328,7 @@ export class BeeDebug { async withdrawTokens( amount: number | NumberString, gasPrice?: NumberString, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertNonNegativeInteger(amount) @@ -346,7 +337,7 @@ export class BeeDebug { assertNonNegativeInteger(gasPrice) } - return chequebook.withdrawTokens(this.getKyOptionsForCall(options), amount, gasPrice) + return chequebook.withdrawTokens(this.getRequestOptionsForCall(options), amount, gasPrice) } /* @@ -358,47 +349,47 @@ export class BeeDebug { * * @param address Swarm address of peer */ - async getSettlements(address: Address | string, options?: RequestOptions): Promise { + async getSettlements(address: Address | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertAddress(address) - return settlements.getSettlements(this.getKyOptionsForCall(options), address) + return settlements.getSettlements(this.getRequestOptionsForCall(options), address) } /** * Get settlements with all known peers and total amount sent or received */ - async getAllSettlements(options?: RequestOptions): Promise { + async getAllSettlements(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return settlements.getAllSettlements(this.getKyOptionsForCall(options)) + return settlements.getAllSettlements(this.getRequestOptionsForCall(options)) } /** * Get health of node */ - async getHealth(options?: RequestOptions): Promise { + async getHealth(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return status.getHealth(this.getKyOptionsForCall(options)) + return status.getHealth(this.getRequestOptionsForCall(options)) } /** * Get readiness of node */ - async getReadiness(options?: RequestOptions): Promise { + async getReadiness(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return status.getReadiness(this.getKyOptionsForCall(options)) + return status.getReadiness(this.getRequestOptionsForCall(options)) } /** * Get mode information of node */ - async getNodeInfo(options?: RequestOptions): Promise { + async getNodeInfo(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return status.getNodeInfo(this.getKyOptionsForCall(options)) + return status.getNodeInfo(this.getRequestOptionsForCall(options)) } /** @@ -407,10 +398,10 @@ export class BeeDebug { * @returns true if the Bee node version is supported * @deprecated Use `BeeDebug.isSupportedExactVersion()` instead */ - async isSupportedVersion(options?: RequestOptions): Promise | never { + async isSupportedVersion(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.isSupportedVersion(this.getKyOptionsForCall(options)) + return status.isSupportedVersion(this.getRequestOptionsForCall(options)) } /** @@ -423,10 +414,10 @@ export class BeeDebug { * * @param options */ - async isSupportedExactVersion(options?: RequestOptions): Promise | never { + async isSupportedExactVersion(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.isSupportedExactVersion(this.getKyOptionsForCall(options)) + return status.isSupportedExactVersion(this.getRequestOptionsForCall(options)) } /** @@ -437,10 +428,10 @@ export class BeeDebug { * * @param options */ - async isSupportedMainApiVersion(options?: RequestOptions): Promise | never { + async isSupportedMainApiVersion(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.isSupportedMainApiVersion(this.getKyOptionsForCall(options)) + return status.isSupportedMainApiVersion(this.getRequestOptionsForCall(options)) } /** @@ -451,10 +442,10 @@ export class BeeDebug { * * @param options */ - async isSupportedDebugApiVersion(options?: RequestOptions): Promise | never { + async isSupportedDebugApiVersion(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.isSupportedDebugApiVersion(this.getKyOptionsForCall(options)) + return status.isSupportedDebugApiVersion(this.getRequestOptionsForCall(options)) } /** @@ -465,10 +456,10 @@ export class BeeDebug { * * @param options */ - async isSupportedApiVersion(options?: RequestOptions): Promise | never { + async isSupportedApiVersion(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.isSupportedDebugApiVersion(this.getKyOptionsForCall(options)) + return status.isSupportedDebugApiVersion(this.getRequestOptionsForCall(options)) } /** @@ -477,28 +468,28 @@ export class BeeDebug { * * @param options */ - async getVersions(options?: RequestOptions): Promise | never { + async getVersions(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options) - return status.getVersions(this.getKyOptionsForCall(options)) + return status.getVersions(this.getRequestOptionsForCall(options)) } /** * Get reserve state */ - async getReserveState(options?: RequestOptions): Promise { + async getReserveState(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return states.getReserveState(this.getKyOptionsForCall(options)) + return states.getReserveState(this.getRequestOptionsForCall(options)) } /** * Get chain state */ - async getChainState(options?: RequestOptions): Promise { + async getChainState(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return states.getChainState(this.getKyOptionsForCall(options)) + return states.getChainState(this.getRequestOptionsForCall(options)) } /** @@ -506,10 +497,10 @@ export class BeeDebug { * * @param options */ - async getWalletBalance(options?: RequestOptions): Promise { + async getWalletBalance(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return states.getWalletBalance(this.getKyOptionsForCall(options)) + return states.getWalletBalance(this.getRequestOptionsForCall(options)) } /** @@ -529,7 +520,12 @@ export class BeeDebug { * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) * @see [Bee Debug API reference - `POST /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{amount}~1{depth}/post) */ - async createPostageBatch(amount: NumberString, depth: number, options?: PostageBatchOptions): Promise { + async createPostageBatch( + amount: NumberString, + depth: number, + options?: PostageBatchOptions, + requestOptions?: BeeRequestOptions, + ): Promise { assertPostageBatchOptions(options) assertPositiveInteger(amount) assertNonNegativeInteger(depth) @@ -542,7 +538,7 @@ export class BeeDebug { throw new BeeArgumentError(`Depth has to be at most ${STAMPS_DEPTH_MAX}`, depth) } - const stamp = await stamps.createPostageBatch(this.getKyOptionsForCall(options), amount, depth, options) + const stamp = await stamps.createPostageBatch(this.getRequestOptionsForCall(requestOptions), amount, depth, options) if (options?.waitForUsable !== false) { await this.waitForUsablePostageStamp(stamp, options?.waitForUsableTimeout) @@ -566,12 +562,12 @@ export class BeeDebug { * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) */ - async topUpBatch(postageBatchId: BatchId | string, amount: NumberString, options?: RequestOptions): Promise { + async topUpBatch(postageBatchId: BatchId | string, amount: NumberString, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertNonNegativeInteger(amount, 'Amount') assertBatchId(postageBatchId) - await stamps.topUpBatch(this.getKyOptionsForCall(options), postageBatchId, amount) + await stamps.topUpBatch(this.getRequestOptionsForCall(options), postageBatchId, amount) } /** @@ -590,12 +586,12 @@ export class BeeDebug { * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) * @see [Bee Debug API reference - `PATCH /stamps/topup/${id}/${amount}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1topup~1{id}~1{amount}/patch) */ - async diluteBatch(postageBatchId: BatchId | string, depth: number, options?: RequestOptions): Promise { + async diluteBatch(postageBatchId: BatchId | string, depth: number, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertNonNegativeInteger(depth, 'Depth') assertBatchId(postageBatchId) - await stamps.diluteBatch(this.getKyOptionsForCall(options), postageBatchId, depth) + await stamps.diluteBatch(this.getRequestOptionsForCall(options), postageBatchId, depth) } /** @@ -606,11 +602,11 @@ export class BeeDebug { * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) * @see [Bee Debug API reference - `GET /stamps/${id}`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps~1{id}/get) */ - async getPostageBatch(postageBatchId: BatchId | string, options?: RequestOptions): Promise { + async getPostageBatch(postageBatchId: BatchId | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertBatchId(postageBatchId) - return stamps.getPostageBatch(this.getKyOptionsForCall(options), postageBatchId) + return stamps.getPostageBatch(this.getRequestOptionsForCall(options), postageBatchId) } /** @@ -623,12 +619,12 @@ export class BeeDebug { */ async getPostageBatchBuckets( postageBatchId: BatchId | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertBatchId(postageBatchId) - return stamps.getPostageBatchBuckets(this.getKyOptionsForCall(options), postageBatchId) + return stamps.getPostageBatchBuckets(this.getRequestOptionsForCall(options), postageBatchId) } /** @@ -637,19 +633,19 @@ export class BeeDebug { * @see [Bee docs - Keep your data alive / Postage stamps](https://docs.ethswarm.org/docs/access-the-swarm/keep-your-data-alive) * @see [Bee Debug API reference - `GET /stamps`](https://docs.ethswarm.org/debug-api/#tag/Postage-Stamps/paths/~1stamps/get) */ - async getAllPostageBatch(options?: RequestOptions): Promise { + async getAllPostageBatch(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return stamps.getAllPostageBatches(this.getKyOptionsForCall(options)) + return stamps.getAllPostageBatches(this.getRequestOptionsForCall(options)) } /** * Return lists of all current pending transactions that the Bee made */ - async getAllPendingTransactions(options?: RequestOptions): Promise { + async getAllPendingTransactions(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return transactions.getAllTransactions(this.getKyOptionsForCall(options)) + return transactions.getAllTransactions(this.getRequestOptionsForCall(options)) } /** @@ -658,12 +654,12 @@ export class BeeDebug { */ async getPendingTransaction( transactionHash: TransactionHash | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertTransactionHash(transactionHash) - return transactions.getTransaction(this.getKyOptionsForCall(options), transactionHash) + return transactions.getTransaction(this.getRequestOptionsForCall(options), transactionHash) } /** @@ -674,12 +670,12 @@ export class BeeDebug { */ async rebroadcastPendingTransaction( transactionHash: TransactionHash | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertTransactionHash(transactionHash) - return transactions.rebroadcastTransaction(this.getKyOptionsForCall(options), transactionHash) + return transactions.rebroadcastTransaction(this.getRequestOptionsForCall(options), transactionHash) } /** @@ -690,7 +686,7 @@ export class BeeDebug { async cancelPendingTransaction( transactionHash: TransactionHash | string, gasPrice?: NumberString, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertTransactionHash(transactionHash) @@ -699,7 +695,7 @@ export class BeeDebug { assertNonNegativeInteger(gasPrice) } - return transactions.cancelTransaction(this.getKyOptionsForCall(options), transactionHash, gasPrice) + return transactions.cancelTransaction(this.getRequestOptionsForCall(options), transactionHash, gasPrice) } /** @@ -707,10 +703,10 @@ export class BeeDebug { * * @param options */ - async getStake(options?: RequestOptions): Promise { + async getStake(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return stake.getStake(this.getKyOptionsForCall(options)) + return stake.getStake(this.getRequestOptionsForCall(options)) } /** @@ -721,11 +717,15 @@ export class BeeDebug { * @param amount Amount of BZZ token (in PLUR unit) to be staked. Minimum is 100_000_000_000_000_000 PLUR (10 BZZ). * @param options */ - async depositStake(amount: NumberString, options?: RequestOptions & TransactionOptions): Promise { + async depositStake( + amount: NumberString, + options?: TransactionOptions, + requestOptions?: BeeRequestOptions, + ): Promise { assertRequestOptions(options) assertTransactionOptions(options) - await stake.stake(this.getKyOptionsForCall(options), amount, options) + await stake.stake(this.getRequestOptionsForCall(requestOptions), amount, options) } /** @@ -733,10 +733,10 @@ export class BeeDebug { * * @param options */ - async getRedistributionState(options?: RequestOptions): Promise { + async getRedistributionState(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return stake.getRedistributionState(this.getKyOptionsForCall(options)) + return stake.getRedistributionState(this.getRequestOptionsForCall(options)) } private async waitForUsablePostageStamp(id: BatchId, timeout = 120_000): Promise { @@ -748,13 +748,13 @@ export class BeeDebug { return } - await sleep(TIME_STEP) + await System.sleepMillis(TIME_STEP) } throw new BeeError('Timeout on waiting for postage stamp to become usable') } - private getKyOptionsForCall(options?: RequestOptions): KyOptions { - return deepMerge(this.kyOptions, options) + private getRequestOptionsForCall(options?: BeeRequestOptions): BeeRequestOptions { + return options ? Objects.deepMerge2(this.requestOptions, options) : this.requestOptions } } diff --git a/src/bee.ts b/src/bee.ts index ec07c1bb..a0f8be2a 100644 --- a/src/bee.ts +++ b/src/bee.ts @@ -1,50 +1,27 @@ -import * as bzz from './modules/bzz' -import * as stewardship from './modules/stewardship' -import * as tag from './modules/tag' -import * as pinning from './modules/pinning' -import * as bytes from './modules/bytes' -import * as chunk from './modules/chunk' -import * as pss from './modules/pss' -import * as status from './modules/status' - -import { BeeArgumentError, BeeError, BeeResponseError } from './utils/error' -import { prepareWebsocketData } from './utils/data' -import { fileArrayBuffer, isFile } from './utils/file' -import { Index, IndexBytes, makeFeedReader, makeFeedWriter } from './feed' +import { ReferenceType } from '@ethersphere/swarm-cid' +import { Objects } from 'cafe-utility' import { makeSigner } from './chunk/signer' -import { assertFeedType, DEFAULT_FEED_TYPE, FeedType } from './feed/type' import { downloadSingleOwnerChunk, uploadSingleOwnerChunkData } from './chunk/soc' +import { Index, IndexBytes, makeFeedReader, makeFeedWriter } from './feed' +import { getJsonData, setJsonData } from './feed/json' +import { areAllSequentialFeedsUpdateRetrievable } from './feed/retrievable' import { makeTopic, makeTopicFromString } from './feed/topic' +import { assertFeedType, DEFAULT_FEED_TYPE, FeedType } from './feed/type' +import * as bytes from './modules/bytes' +import * as bzz from './modules/bzz' +import * as chunk from './modules/chunk' import { createFeedManifest } from './modules/feed' -import { assertBeeUrl, stripLastSlash } from './utils/url' -import { EthAddress, makeEthAddress, makeHexEthAddress } from './utils/eth' -import { wrapBytesWithHelpers } from './utils/bytes' -import { - addCidConversionFunction, - assertAddressPrefix, - assertAllTagsOptions, - assertBatchId, - assertCollectionUploadOptions, - assertData, - assertFileData, - assertFileUploadOptions, - assertPssMessageHandler, - assertPublicKey, - assertReference, - assertReferenceOrEns, - assertRequestOptions, - assertUploadOptions, - makeReferenceOrEns, - makeTagUid, -} from './utils/type' -import { getJsonData, setJsonData } from './feed/json' -import { assertCollection, makeCollectionFromFileList } from './utils/collection' -import { makeCollectionFromFS } from './utils/collection.node' +import * as pinning from './modules/pinning' +import * as pss from './modules/pss' +import * as status from './modules/status' +import * as stewardship from './modules/stewardship' +import * as tag from './modules/tag' import type { AddressPrefix, AnyJson, BatchId, BeeOptions, + BeeRequestOptions, CollectionUploadOptions, Data, FeedReader, @@ -73,18 +50,36 @@ import { Readable, ReferenceCidOrEns, ReferenceOrEns, - RequestOptions, SPAN_SIZE, UploadResult, } from './types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' -import { DEFAULT_KY_CONFIG, wrapRequestClosure, wrapResponseClosure } from './utils/http' +import { wrapBytesWithHelpers } from './utils/bytes' +import { assertCollection, makeCollectionFromFileList } from './utils/collection' +import { makeCollectionFromFS } from './utils/collection.node' +import { prepareWebsocketData } from './utils/data' +import { BeeArgumentError, BeeError } from './utils/error' +import { EthAddress, makeEthAddress, makeHexEthAddress } from './utils/eth' +import { fileArrayBuffer, isFile } from './utils/file' import { isReadable } from './utils/stream' -import { areAllSequentialFeedsUpdateRetrievable } from './feed/retrievable' -import { ReferenceType } from '@ethersphere/swarm-cid' -import { deepMerge } from './utils/merge' +import { + addCidConversionFunction, + assertAddressPrefix, + assertAllTagsOptions, + assertBatchId, + assertCollectionUploadOptions, + assertData, + assertFileData, + assertFileUploadOptions, + assertPssMessageHandler, + assertPublicKey, + assertReference, + assertReferenceOrEns, + assertRequestOptions, + assertUploadOptions, + makeReferenceOrEns, + makeTagUid, +} from './utils/type' +import { assertBeeUrl, stripLastSlash } from './utils/url' /** * The main component that abstracts operations available on the main Bee API. @@ -107,7 +102,7 @@ export class Bee { * Ky instance that defines connection to Bee node * @private */ - private readonly kyOptions: KyOptions + private readonly requestOptions: BeeRequestOptions /** * @param url URL on which is the main API of Bee node exposed @@ -125,30 +120,20 @@ export class Bee { this.signer = makeSigner(options.signer) } - const kyOptions: KyOptions = { - prefixUrl: this.url, + const requestOptions: BeeRequestOptions = { + baseURL: this.url, timeout: options?.timeout ?? false, - retry: options?.retry, - fetch: options?.fetch, - hooks: { - beforeRequest: [], - afterResponse: [], - }, } - if (options?.defaultHeaders) { - kyOptions.headers = options.defaultHeaders + if (options?.headers) { + requestOptions.headers = options.headers } if (options?.onRequest) { - kyOptions.hooks!.beforeRequest!.push(wrapRequestClosure(options.onRequest)) + requestOptions.onRequest = options.onRequest } - if (options?.onResponse) { - kyOptions.hooks!.afterResponse!.push(wrapResponseClosure(options.onResponse)) - } - - this.kyOptions = deepMerge(DEFAULT_KY_CONFIG, kyOptions) + this.requestOptions = requestOptions } /** @@ -166,13 +151,14 @@ export class Bee { postageBatchId: string | BatchId, data: string | Uint8Array, options?: UploadOptions, + requestOptions?: BeeRequestOptions, ): Promise { assertBatchId(postageBatchId) assertData(data) if (options) assertUploadOptions(options) - return bytes.upload(this.getKyOptionsForCall(options), data, postageBatchId, options) + return bytes.upload(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options) } /** @@ -185,11 +171,11 @@ export class Bee { * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/access-the-swarm/upload-and-download) * @see [Bee API reference - `GET /bytes`](https://docs.ethswarm.org/api/#tag/Bytes/paths/~1bytes~1{reference}/get) */ - async downloadData(reference: ReferenceOrEns | string, options?: RequestOptions): Promise { + async downloadData(reference: ReferenceOrEns | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReferenceOrEns(reference) - return bytes.download(this.getKyOptionsForCall(options), reference) + return bytes.download(this.getRequestOptionsForCall(options), reference) } /** @@ -204,12 +190,12 @@ export class Bee { */ async downloadReadableData( reference: ReferenceOrEns | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise> { assertRequestOptions(options) assertReferenceOrEns(reference) - return bytes.downloadReadable(this.getKyOptionsForCall(options), reference) + return bytes.downloadReadable(this.getRequestOptionsForCall(options), reference) } /** @@ -223,7 +209,12 @@ export class Bee { * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/access-the-swarm/upload-and-download) * @see [Bee API reference - `POST /chunks`](https://docs.ethswarm.org/api/#tag/Chunk/paths/~1chunks/post) */ - async uploadChunk(postageBatchId: string | BatchId, data: Uint8Array, options?: UploadOptions): Promise { + async uploadChunk( + postageBatchId: string | BatchId, + data: Uint8Array, + options?: UploadOptions, + requestOptions?: BeeRequestOptions, + ): Promise { assertBatchId(postageBatchId) if (!(data instanceof Uint8Array)) { @@ -240,7 +231,7 @@ export class Bee { if (options) assertUploadOptions(options) - return chunk.upload(this.getKyOptionsForCall(options), data, postageBatchId, options) + return chunk.upload(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options) } /** @@ -253,11 +244,11 @@ export class Bee { * @see [Bee docs - Upload and download](https://docs.ethswarm.org/docs/access-the-swarm/upload-and-download) * @see [Bee API reference - `GET /chunks`](https://docs.ethswarm.org/api/#tag/Chunk/paths/~1chunks~1{reference}/get) */ - async downloadChunk(reference: ReferenceOrEns | string, options?: RequestOptions): Promise { + async downloadChunk(reference: ReferenceOrEns | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReferenceOrEns(reference) - return chunk.download(this.getKyOptionsForCall(options), reference) + return chunk.download(this.getRequestOptionsForCall(options), reference) } /** @@ -281,6 +272,7 @@ export class Bee { data: string | Uint8Array | Readable | File, name?: string, options?: FileUploadOptions, + requestOptions?: BeeRequestOptions, ): Promise { assertBatchId(postageBatchId) assertFileData(data) @@ -298,18 +290,30 @@ export class Bee { const fileOptions = { contentType, ...options } return addCidConversionFunction( - await bzz.uploadFile(this.getKyOptionsForCall(options), fileData, postageBatchId, fileName, fileOptions), + await bzz.uploadFile( + this.getRequestOptionsForCall(requestOptions), + fileData, + postageBatchId, + fileName, + fileOptions, + ), ReferenceType.MANIFEST, ) } else if (isReadable(data) && options?.tag && !options.size) { // TODO: Needed until https://github.com/ethersphere/bee/issues/2317 is resolved - const result = await bzz.uploadFile(this.getKyOptionsForCall(options), data, postageBatchId, name, options) + const result = await bzz.uploadFile( + this.getRequestOptionsForCall(requestOptions), + data, + postageBatchId, + name, + options, + ) await this.updateTag(options.tag, result.reference) return addCidConversionFunction(result, ReferenceType.MANIFEST) } else { return addCidConversionFunction( - await bzz.uploadFile(this.getKyOptionsForCall(options), data, postageBatchId, name, options), + await bzz.uploadFile(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, name, options), ReferenceType.MANIFEST, ) } @@ -330,12 +334,12 @@ export class Bee { async downloadFile( reference: ReferenceCidOrEns | string, path = '', - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise> { assertRequestOptions(options) reference = makeReferenceOrEns(reference, ReferenceType.MANIFEST) - return bzz.downloadFile(this.getKyOptionsForCall(options), reference, path) + return bzz.downloadFile(this.getRequestOptionsForCall(options), reference, path) } /** @@ -353,12 +357,12 @@ export class Bee { async downloadReadableFile( reference: ReferenceCidOrEns | string, path = '', - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise>> { assertRequestOptions(options) reference = makeReferenceOrEns(reference, ReferenceType.MANIFEST) - return bzz.downloadFileReadable(this.getKyOptionsForCall(options), reference, path) + return bzz.downloadFileReadable(this.getRequestOptionsForCall(options), reference, path) } /** @@ -381,6 +385,7 @@ export class Bee { postageBatchId: string | BatchId, fileList: FileList | File[], options?: CollectionUploadOptions, + requestOptions?: BeeRequestOptions, ): Promise { assertBatchId(postageBatchId) @@ -389,7 +394,7 @@ export class Bee { const data = await makeCollectionFromFileList(fileList) return addCidConversionFunction( - await bzz.uploadCollection(this.getKyOptionsForCall(options), data, postageBatchId, options), + await bzz.uploadCollection(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options), ReferenceType.MANIFEST, ) } @@ -415,7 +420,7 @@ export class Bee { if (options) assertCollectionUploadOptions(options) return addCidConversionFunction( - await bzz.uploadCollection(this.kyOptions, collection, postageBatchId, options), + await bzz.uploadCollection(this.requestOptions, collection, postageBatchId, options), ReferenceType.MANIFEST, ) } @@ -440,6 +445,7 @@ export class Bee { postageBatchId: string | BatchId, dir: string, options?: CollectionUploadOptions, + requestOptions?: BeeRequestOptions, ): Promise { assertBatchId(postageBatchId) @@ -447,7 +453,7 @@ export class Bee { const data = await makeCollectionFromFS(dir) return addCidConversionFunction( - await bzz.uploadCollection(this.getKyOptionsForCall(options), data, postageBatchId, options), + await bzz.uploadCollection(this.getRequestOptionsForCall(requestOptions), data, postageBatchId, options), ReferenceType.MANIFEST, ) } @@ -459,10 +465,10 @@ export class Bee { * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/access-the-swarm/syncing) * @see [Bee API reference - `POST /tags`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags/post) */ - async createTag(options?: RequestOptions): Promise { + async createTag(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return tag.createTag(this.getKyOptionsForCall(options)) + return tag.createTag(this.getRequestOptionsForCall(options)) } /** @@ -481,7 +487,7 @@ export class Bee { assertRequestOptions(options) assertAllTagsOptions(options) - return tag.getAllTags(this.getKyOptionsForCall(options), options?.offset, options?.limit) + return tag.getAllTags(this.getRequestOptionsForCall(options), options?.offset, options?.limit) } /** @@ -495,12 +501,12 @@ export class Bee { * @see [Bee API reference - `GET /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/get) * */ - async retrieveTag(tagUid: number | Tag, options?: RequestOptions): Promise { + async retrieveTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise { assertRequestOptions(options) tagUid = makeTagUid(tagUid) - return tag.retrieveTag(this.getKyOptionsForCall(options), tagUid) + return tag.retrieveTag(this.getRequestOptionsForCall(options), tagUid) } /** @@ -514,12 +520,12 @@ export class Bee { * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/access-the-swarm/syncing) * @see [Bee API reference - `DELETE /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/delete) */ - async deleteTag(tagUid: number | Tag, options?: RequestOptions): Promise { + async deleteTag(tagUid: number | Tag, options?: BeeRequestOptions): Promise { assertRequestOptions(options) tagUid = makeTagUid(tagUid) - return tag.deleteTag(this.getKyOptionsForCall(options), tagUid) + return tag.deleteTag(this.getRequestOptionsForCall(options), tagUid) } /** @@ -537,13 +543,13 @@ export class Bee { * @see [Bee docs - Syncing / Tags](https://docs.ethswarm.org/docs/access-the-swarm/syncing) * @see [Bee API reference - `PATCH /tags/{uid}`](https://docs.ethswarm.org/api/#tag/Tag/paths/~1tags~1{uid}/patch) */ - async updateTag(tagUid: number | Tag, reference: Reference | string, options?: RequestOptions): Promise { + async updateTag(tagUid: number | Tag, reference: Reference | string, options?: BeeRequestOptions): Promise { assertReference(reference) assertRequestOptions(options) tagUid = makeTagUid(tagUid) - return tag.updateTag(this.getKyOptionsForCall(options), tagUid, reference) + return tag.updateTag(this.getRequestOptionsForCall(options), tagUid, reference) } /** @@ -555,11 +561,11 @@ export class Bee { * * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/access-the-swarm/pinning) */ - async pin(reference: Reference | string, options?: RequestOptions): Promise { + async pin(reference: Reference | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReference(reference) - return pinning.pin(this.getKyOptionsForCall(options), reference) + return pinning.pin(this.getRequestOptionsForCall(options), reference) } /** @@ -571,11 +577,11 @@ export class Bee { * * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/access-the-swarm/pinning) */ - async unpin(reference: Reference | string, options?: RequestOptions): Promise { + async unpin(reference: Reference | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReference(reference) - return pinning.unpin(this.getKyOptionsForCall(options), reference) + return pinning.unpin(this.getRequestOptionsForCall(options), reference) } /** @@ -584,10 +590,10 @@ export class Bee { * @param options Options that affects the request behavior * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/access-the-swarm/pinning) */ - async getAllPins(options?: RequestOptions): Promise { + async getAllPins(options?: BeeRequestOptions): Promise { assertRequestOptions(options) - return pinning.getAllPins(this.getKyOptionsForCall(options)) + return pinning.getAllPins(this.getRequestOptionsForCall(options)) } /** @@ -600,11 +606,11 @@ export class Bee { * * @see [Bee docs - Pinning](https://docs.ethswarm.org/docs/access-the-swarm/pinning) */ - async getPin(reference: Reference | string, options?: RequestOptions): Promise { + async getPin(reference: Reference | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReference(reference) - return pinning.getPin(this.getKyOptionsForCall(options), reference) + return pinning.getPin(this.getRequestOptionsForCall(options), reference) } /** @@ -618,11 +624,11 @@ export class Bee { * * @see [Bee API reference - `PUT /stewardship`](https://docs.ethswarm.org/api/#tag/Stewardship/paths/~1stewardship~1{reference}/put) */ - async reuploadPinnedData(reference: ReferenceOrEns | string, options?: RequestOptions): Promise { + async reuploadPinnedData(reference: ReferenceOrEns | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReferenceOrEns(reference) - await stewardship.reupload(this.getKyOptionsForCall(options), reference) + await stewardship.reupload(this.getRequestOptionsForCall(options), reference) } /** @@ -635,11 +641,11 @@ export class Bee { * * @see [Bee API reference - `GET /stewardship`](https://docs.ethswarm.org/api/#tag/Stewardship/paths/~1stewardship~1{reference}/get) */ - async isReferenceRetrievable(reference: ReferenceOrEns | string, options?: RequestOptions): Promise { + async isReferenceRetrievable(reference: ReferenceOrEns | string, options?: BeeRequestOptions): Promise { assertRequestOptions(options) assertReferenceOrEns(reference) - return stewardship.isRetrievable(this.getKyOptionsForCall(options), reference) + return stewardship.isRetrievable(this.getRequestOptionsForCall(options), reference) } /** @@ -662,7 +668,7 @@ export class Bee { owner: EthAddress | Uint8Array | string, topic: Topic | Uint8Array | string, index?: Index | number | IndexBytes | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { const canonicalOwner = makeEthAddress(owner) const canonicalTopic = makeTopic(topic) @@ -672,11 +678,8 @@ export class Bee { await this.makeFeedReader(type, canonicalTopic, canonicalOwner).download() return true - } catch (e) { - const err = e as BeeResponseError - - // Only if the error is "not-found" then we return false otherwise we re-throw the error - if (err?.status === 404) { + } catch (e: any) { + if (e?.response?.status === 404) { return false } @@ -688,7 +691,13 @@ export class Bee { throw new BeeError('Only Sequence type of Feeds is supported at the moment') } - return areAllSequentialFeedsUpdateRetrievable(this, canonicalOwner, canonicalTopic, index, options) + return areAllSequentialFeedsUpdateRetrievable( + this, + canonicalOwner, + canonicalTopic, + index, + this.getRequestOptionsForCall(options), + ) } /** @@ -719,7 +728,7 @@ export class Bee { target: AddressPrefix, data: string | Uint8Array, recipient?: string | PublicKey, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertData(data) @@ -733,9 +742,9 @@ export class Bee { if (recipient) { assertPublicKey(recipient) - return pss.send(this.getKyOptionsForCall(options), topic, target, data, postageBatchId, recipient) + return pss.send(this.getRequestOptionsForCall(options), topic, target, data, postageBatchId, recipient) } else { - return pss.send(this.getKyOptionsForCall(options), topic, target, data, postageBatchId) + return pss.send(this.getRequestOptionsForCall(options), topic, target, data, postageBatchId) } } @@ -876,7 +885,7 @@ export class Bee { type: FeedType, topic: Topic | Uint8Array | string, owner: EthAddress | Uint8Array | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): Promise { assertRequestOptions(options) assertFeedType(type) @@ -886,7 +895,7 @@ export class Bee { const canonicalOwner = makeHexEthAddress(owner) const reference = await createFeedManifest( - this.getKyOptionsForCall(options), + this.getRequestOptionsForCall(options), canonicalOwner, canonicalTopic, postageBatchId, @@ -912,7 +921,7 @@ export class Bee { type: FeedType, topic: Topic | Uint8Array | string, owner: EthAddress | Uint8Array | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): FeedReader { assertRequestOptions(options) assertFeedType(type) @@ -920,7 +929,7 @@ export class Bee { const canonicalTopic = makeTopic(topic) const canonicalOwner = makeHexEthAddress(owner) - return makeFeedReader(this.getKyOptionsForCall(options), type, canonicalTopic, canonicalOwner) + return makeFeedReader(this.getRequestOptionsForCall(options), type, canonicalTopic, canonicalOwner) } /** @@ -937,7 +946,7 @@ export class Bee { type: FeedType, topic: Topic | Uint8Array | string, signer?: Signer | Uint8Array | string, - options?: RequestOptions, + options?: BeeRequestOptions, ): FeedWriter { assertRequestOptions(options) assertFeedType(type) @@ -945,7 +954,7 @@ export class Bee { const canonicalTopic = makeTopic(topic) const canonicalSigner = this.resolveSigner(signer) - return makeFeedWriter(this.getKyOptionsForCall(options), type, canonicalTopic, canonicalSigner) + return makeFeedWriter(this.getRequestOptionsForCall(options), type, canonicalTopic, canonicalSigner) } /** @@ -971,15 +980,16 @@ export class Bee { topic: string, data: T, options?: JsonFeedOptions, + requestOptions?: BeeRequestOptions, ): Promise { assertRequestOptions(options, 'JsonFeedOptions') assertBatchId(postageBatchId) const hashedTopic = this.makeFeedTopic(topic) const feedType = options?.type ?? DEFAULT_FEED_TYPE - const writer = this.makeFeedWriter(feedType, hashedTopic, options?.signer, options) + const writer = this.makeFeedWriter(feedType, hashedTopic, options?.signer, requestOptions) - return setJsonData(this, writer, postageBatchId, data, options) + return setJsonData(this, writer, postageBatchId, data, options, requestOptions) } /** @@ -1051,13 +1061,13 @@ export class Bee { * @param options Options that affects the request behavior * @see [Bee docs - Chunk Types](https://docs.ethswarm.org/docs/dapps-on-swarm/chunk-types#single-owner-chunks) */ - makeSOCReader(ownerAddress: EthAddress | Uint8Array | string, options?: RequestOptions): SOCReader { + makeSOCReader(ownerAddress: EthAddress | Uint8Array | string, options?: BeeRequestOptions): SOCReader { assertRequestOptions(options) const canonicalOwner = makeEthAddress(ownerAddress) return { owner: makeHexEthAddress(canonicalOwner), - download: downloadSingleOwnerChunk.bind(null, this.getKyOptionsForCall(options), canonicalOwner), + download: downloadSingleOwnerChunk.bind(null, this.getRequestOptionsForCall(options), canonicalOwner), } } @@ -1068,14 +1078,14 @@ export class Bee { * @param options Options that affects the request behavior * @see [Bee docs - Chunk Types](https://docs.ethswarm.org/docs/dapps-on-swarm/chunk-types#single-owner-chunks) */ - makeSOCWriter(signer?: Signer | Uint8Array | string, options?: RequestOptions): SOCWriter { + makeSOCWriter(signer?: Signer | Uint8Array | string, options?: BeeRequestOptions): SOCWriter { assertRequestOptions(options) const canonicalSigner = this.resolveSigner(signer) return { ...this.makeSOCReader(canonicalSigner.address, options), - upload: uploadSingleOwnerChunkData.bind(null, this.getKyOptionsForCall(options), canonicalSigner), + upload: uploadSingleOwnerChunkData.bind(null, this.getRequestOptionsForCall(options), canonicalSigner), } } @@ -1085,10 +1095,10 @@ export class Bee { * @param options Options that affects the request behavior * @throws If connection was not successful throw error */ - async checkConnection(options?: RequestOptions): Promise | never { + async checkConnection(options?: BeeRequestOptions): Promise | never { assertRequestOptions(options, 'PostageBatchOptions') - return status.checkConnection(this.getKyOptionsForCall(options)) + return status.checkConnection(this.getRequestOptionsForCall(options)) } /** @@ -1097,11 +1107,11 @@ export class Bee { * @param options Options that affects the request behavior * @returns true if successful, false on error */ - async isConnected(options?: RequestOptions): Promise { + async isConnected(options?: BeeRequestOptions): Promise { assertRequestOptions(options, 'PostageBatchOptions') try { - await status.checkConnection(this.getKyOptionsForCall(options)) + await status.checkConnection(this.getRequestOptionsForCall(options)) } catch (e) { return false } @@ -1126,7 +1136,7 @@ export class Bee { throw new BeeError('You have to pass Signer as property to either the method call or constructor! Non found.') } - private getKyOptionsForCall(options?: RequestOptions): KyOptions { - return deepMerge(this.kyOptions, options) + private getRequestOptionsForCall(options?: BeeRequestOptions): BeeRequestOptions { + return options ? Objects.deepMerge2(this.requestOptions, options) : this.requestOptions } } diff --git a/src/chunk/soc.ts b/src/chunk/soc.ts index 09afa98c..fb91f7fc 100644 --- a/src/chunk/soc.ts +++ b/src/chunk/soc.ts @@ -1,20 +1,17 @@ +import * as chunkAPI from '../modules/chunk' +import * as socAPI from '../modules/soc' +import { BatchId, BeeRequestOptions, PlainBytesReference, Reference, Signature, Signer, UploadOptions } from '../types' import { Bytes, bytesAtOffset, bytesEqual, flexBytesAtOffset } from '../utils/bytes' -import { bmtHash } from './bmt' -import { recoverAddress, sign } from './signer' -import { keccak256Hash } from '../utils/hash' -import { SPAN_SIZE } from './span' -import { serializeBytes } from './serialize' import { BeeError } from '../utils/error' -import { Chunk, makeContentAddressedChunk, MAX_PAYLOAD_SIZE, MIN_PAYLOAD_SIZE, assertValidChunkData } from './cac' -import { UploadOptions, Signature, Signer, BatchId, Reference, PlainBytesReference } from '../types' -import { bytesToHex } from '../utils/hex' -import * as socAPI from '../modules/soc' -import * as chunkAPI from '../modules/chunk' import { EthAddress } from '../utils/eth' +import { keccak256Hash } from '../utils/hash' +import { bytesToHex } from '../utils/hex' import { assertAddress } from '../utils/type' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' +import { bmtHash } from './bmt' +import { assertValidChunkData, Chunk, makeContentAddressedChunk, MAX_PAYLOAD_SIZE, MIN_PAYLOAD_SIZE } from './cac' +import { serializeBytes } from './serialize' +import { recoverAddress, sign } from './signer' +import { SPAN_SIZE } from './span' const IDENTIFIER_SIZE = 32 const SIGNATURE_SIZE = 65 @@ -129,7 +126,7 @@ export async function makeSingleOwnerChunk( * @param options Upload options */ export async function uploadSingleOwnerChunk( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, chunk: SingleOwnerChunk, postageBatchId: BatchId, options?: UploadOptions, @@ -139,7 +136,7 @@ export async function uploadSingleOwnerChunk( const signature = bytesToHex(chunk.signature()) const data = serializeBytes(chunk.span(), chunk.payload()) - return socAPI.upload(kyOptions, owner, identifier, signature, data, postageBatchId, options) + return socAPI.upload(requestOptions, owner, identifier, signature, data, postageBatchId, options) } /** @@ -153,7 +150,7 @@ export async function uploadSingleOwnerChunk( * @param options */ export async function uploadSingleOwnerChunkData( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, signer: Signer, postageBatchId: BatchId | string, identifier: Identifier, @@ -164,7 +161,7 @@ export async function uploadSingleOwnerChunkData( const cac = makeContentAddressedChunk(data) const soc = await makeSingleOwnerChunk(cac, identifier, signer) - return uploadSingleOwnerChunk(kyOptions, soc, postageBatchId, options) + return uploadSingleOwnerChunk(requestOptions, soc, postageBatchId, options) } /** @@ -175,12 +172,12 @@ export async function uploadSingleOwnerChunkData( * @param identifier The identifier of the chunk */ export async function downloadSingleOwnerChunk( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, ownerAddress: EthAddress, identifier: Identifier, ): Promise { const address = makeSOCAddress(identifier, ownerAddress) - const data = await chunkAPI.download(kyOptions, bytesToHex(address)) + const data = await chunkAPI.download(requestOptions, bytesToHex(address)) return makeSingleOwnerChunkFromData(data, address) } diff --git a/src/feed/index.ts b/src/feed/index.ts index 7687453b..0b94e9b4 100644 --- a/src/feed/index.ts +++ b/src/feed/index.ts @@ -1,14 +1,15 @@ -import { keccak256Hash } from '../utils/hash' import { serializeBytes } from '../chunk/serialize' -import { FeedUpdateOptions, fetchLatestFeedUpdate, FetchFeedUpdateResponse } from '../modules/feed' import { makeSingleOwnerChunkFromData, uploadSingleOwnerChunkData } from '../chunk/soc' +import * as chunkAPI from '../modules/chunk' +import { FeedUpdateOptions, FetchFeedUpdateResponse, fetchLatestFeedUpdate } from '../modules/feed' import { Address, BatchId, + BeeRequestOptions, BytesReference, - FEED_INDEX_HEX_LENGTH, FeedReader, FeedWriter, + FEED_INDEX_HEX_LENGTH, PlainBytesReference, Reference, Signer, @@ -16,19 +17,14 @@ import { UploadOptions, } from '../types' import { Bytes, bytesAtOffset, makeBytes } from '../utils/bytes' -import { BeeResponseError } from '../utils/error' -import { bytesToHex, hexToBytes, HexString, makeHexString } from '../utils/hex' -import { readUint64BigEndian, writeUint64BigEndian } from '../utils/uint64' -import * as chunkAPI from '../modules/chunk' import { EthAddress, HexEthAddress, makeHexEthAddress } from '../utils/eth' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - -import type { FeedType } from './type' +import { keccak256Hash } from '../utils/hash' +import { bytesToHex, HexString, hexToBytes, makeHexString } from '../utils/hex' +import { makeBytesReference } from '../utils/reference' import { assertAddress } from '../utils/type' +import { readUint64BigEndian, writeUint64BigEndian } from '../utils/uint64' import { makeFeedIdentifier } from './identifier' -import { makeBytesReference } from '../utils/reference' +import type { FeedType } from './type' const TIMESTAMP_PAYLOAD_OFFSET = 0 const TIMESTAMP_PAYLOAD_SIZE = 8 @@ -54,17 +50,17 @@ export interface FeedUpdate { } export async function findNextIndex( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, owner: HexEthAddress, topic: Topic, options?: FeedUpdateOptions, ): Promise> { try { - const feedUpdate = await fetchLatestFeedUpdate(kyOptions, owner, topic, options) + const feedUpdate = await fetchLatestFeedUpdate(requestOptions, owner, topic, options) return makeHexString(feedUpdate.feedIndexNext, FEED_INDEX_HEX_LENGTH) - } catch (e) { - if (e instanceof BeeResponseError && e.status === 404) { + } catch (e: any) { + if (e?.response?.status === 404) { return bytesToHex(makeBytes(8)) } throw e @@ -72,7 +68,7 @@ export async function findNextIndex( } export async function updateFeed( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, signer: Signer, topic: Topic, reference: BytesReference, @@ -81,14 +77,14 @@ export async function updateFeed( index: Index = 'latest', ): Promise { const ownerHex = makeHexEthAddress(signer.address) - const nextIndex = index === 'latest' ? await findNextIndex(kyOptions, ownerHex, topic, options) : index + const nextIndex = index === 'latest' ? await findNextIndex(requestOptions, ownerHex, topic, options) : index const identifier = makeFeedIdentifier(topic, nextIndex) const at = options?.at ?? Date.now() / 1000.0 const timestamp = writeUint64BigEndian(at) const payloadBytes = serializeBytes(timestamp, reference) - return uploadSingleOwnerChunkData(kyOptions, signer, postageBatchId, identifier, payloadBytes, options) + return uploadSingleOwnerChunkData(requestOptions, signer, postageBatchId, identifier, payloadBytes, options) } export function getFeedUpdateChunkReference(owner: EthAddress, topic: Topic, index: Index): PlainBytesReference { @@ -98,14 +94,14 @@ export function getFeedUpdateChunkReference(owner: EthAddress, topic: Topic, ind } export async function downloadFeedUpdate( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, owner: EthAddress, topic: Topic, index: Index, ): Promise { const address = getFeedUpdateChunkReference(owner, topic, index) const addressHex = bytesToHex(address) - const data = await chunkAPI.download(kyOptions, addressHex) + const data = await chunkAPI.download(requestOptions, addressHex) const soc = makeSingleOwnerChunkFromData(data, address) const payload = soc.payload() const timestampBytes = bytesAtOffset(payload, TIMESTAMP_PAYLOAD_OFFSET, TIMESTAMP_PAYLOAD_SIZE) @@ -118,17 +114,22 @@ export async function downloadFeedUpdate( } } -export function makeFeedReader(kyOptions: KyOptions, type: FeedType, topic: Topic, owner: HexEthAddress): FeedReader { +export function makeFeedReader( + requestOptions: BeeRequestOptions, + type: FeedType, + topic: Topic, + owner: HexEthAddress, +): FeedReader { return { type, owner, topic, async download(options?: FeedUpdateOptions): Promise { if (!options?.index) { - return fetchLatestFeedUpdate(kyOptions, owner, topic, { ...options, type }) + return fetchLatestFeedUpdate(requestOptions, owner, topic, { ...options, type }) } - const update = await downloadFeedUpdate(kyOptions, hexToBytes(owner), topic, options.index) + const update = await downloadFeedUpdate(requestOptions, hexToBytes(owner), topic, options.index) return { reference: bytesToHex(update.reference), @@ -139,7 +140,12 @@ export function makeFeedReader(kyOptions: KyOptions, type: FeedType, topic: Topi } } -export function makeFeedWriter(kyOptions: KyOptions, type: FeedType, topic: Topic, signer: Signer): FeedWriter { +export function makeFeedWriter( + requestOptions: BeeRequestOptions, + type: FeedType, + topic: Topic, + signer: Signer, +): FeedWriter { const upload = async ( postageBatchId: string | Address, reference: BytesReference | Reference, @@ -148,11 +154,11 @@ export function makeFeedWriter(kyOptions: KyOptions, type: FeedType, topic: Topi assertAddress(postageBatchId) const canonicalReference = makeBytesReference(reference) - return updateFeed(kyOptions, signer, topic, canonicalReference, postageBatchId, { ...options, type }) + return updateFeed(requestOptions, signer, topic, canonicalReference, postageBatchId, { ...options, type }) } return { - ...makeFeedReader(kyOptions, type, topic, makeHexEthAddress(signer.address)), + ...makeFeedReader(requestOptions, type, topic, makeHexEthAddress(signer.address)), upload, } } diff --git a/src/feed/json.ts b/src/feed/json.ts index 2cbaa55b..548971d7 100644 --- a/src/feed/json.ts +++ b/src/feed/json.ts @@ -1,5 +1,14 @@ -import { FeedWriter, FeedReader, AnyJson, BatchId, Reference, RequestOptions } from '../types' import { Bee } from '../bee' +import { + AnyJson, + BatchId, + BeeRequestOptions, + FeedReader, + FeedWriter, + JsonFeedOptions, + Reference, + UploadOptions, +} from '../types' import { isError } from '../utils/type' function serializeJson(data: AnyJson): Uint8Array { @@ -27,10 +36,11 @@ export async function setJsonData( writer: FeedWriter, postageBatchId: BatchId, data: AnyJson, - options?: RequestOptions, + options?: JsonFeedOptions & UploadOptions, + requestOptions?: BeeRequestOptions, ): Promise { const serializedData = serializeJson(data) - const { reference } = await bee.uploadData(postageBatchId, serializedData, options) + const { reference } = await bee.uploadData(postageBatchId, serializedData, options, requestOptions) return writer.upload(postageBatchId, reference) } diff --git a/src/feed/retrievable.ts b/src/feed/retrievable.ts index 8c3a93a8..ecd0fb34 100644 --- a/src/feed/retrievable.ts +++ b/src/feed/retrievable.ts @@ -1,10 +1,9 @@ import { Bee } from '../bee' +import { BeeRequestOptions, Reference, Topic } from '../types' import { EthAddress } from '../utils/eth' -import { Reference, RequestOptions, Topic } from '../types' -import { getFeedUpdateChunkReference, Index } from './index' -import { readUint64BigEndian } from '../utils/uint64' import { bytesToHex } from '../utils/hex' -import { BeeResponseError } from '../utils/error' +import { readUint64BigEndian } from '../utils/uint64' +import { getFeedUpdateChunkReference, Index } from './index' function makeNumericIndex(index: Index): number { if (index instanceof Uint8Array) { @@ -30,15 +29,13 @@ function makeNumericIndex(index: Index): number { * @param ref * @param options */ -async function isChunkRetrievable(bee: Bee, ref: Reference, options?: RequestOptions): Promise { +async function isChunkRetrievable(bee: Bee, ref: Reference, requestOptions: BeeRequestOptions): Promise { try { - await bee.downloadChunk(ref, options) + await bee.downloadChunk(ref, requestOptions) return true - } catch (e) { - const err = e as BeeResponseError - - if (err.status === 404) { + } catch (e: any) { + if (e?.response?.status === 404) { return false } @@ -69,10 +66,10 @@ export async function areAllSequentialFeedsUpdateRetrievable( owner: EthAddress, topic: Topic, index: Index, - options?: RequestOptions, + requestOptions: BeeRequestOptions, ): Promise { const chunkRetrievablePromises = getAllSequenceUpdateReferences(owner, topic, index).map(async ref => - isChunkRetrievable(bee, ref, options), + isChunkRetrievable(bee, ref, requestOptions), ) return (await Promise.all(chunkRetrievablePromises)).every(result => result) diff --git a/src/index.ts b/src/index.ts index 4c2e0857..284092f7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,10 +1,10 @@ import { Bee } from './bee' import { BeeDebug } from './bee-debug' -export * as Utils from './utils/expose' +export { SUPPORTED_BEE_VERSION, SUPPORTED_BEE_VERSION_EXACT } from './modules/debug/status' export * from './types' export * from './utils/error' -export { SUPPORTED_BEE_VERSION, SUPPORTED_BEE_VERSION_EXACT } from './modules/debug/status' +export * as Utils from './utils/expose' export { Bee, BeeDebug } // for requrie-like imports @@ -16,8 +16,6 @@ declare global { BeeDebug: typeof import('./bee-debug').BeeDebug Utils: typeof import('./utils/expose') BeeError: typeof import('./utils/error').BeeError - BeeRequestError: typeof import('./utils/error').BeeRequestError - BeeResponseError: typeof import('./utils/error').BeeResponseError BeeArgumentError: typeof import('./utils/error').BeeArgumentError } } diff --git a/src/modules/bytes.ts b/src/modules/bytes.ts index 45026e98..078dd6c2 100644 --- a/src/modules/bytes.ts +++ b/src/modules/bytes.ts @@ -1,14 +1,10 @@ -import type { BatchId, Data, Reference, ReferenceOrEns, UploadOptions } from '../types' -import { prepareData } from '../utils/data' +import type { BatchId, BeeRequestOptions, Data, Reference, ReferenceOrEns, UploadOptions } from '../types' +import { UploadResult } from '../types' +import { wrapBytesWithHelpers } from '../utils/bytes' import { extractUploadHeaders } from '../utils/headers' import { http } from '../utils/http' -import { wrapBytesWithHelpers } from '../utils/bytes' -import { UploadResult } from '../types' import { makeTagUid } from '../utils/type' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const endpoint = 'bytes' /** @@ -20,16 +16,16 @@ const endpoint = 'bytes' * @param options Additional options like tag, encryption, pinning */ export async function upload( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, data: string | Uint8Array, postageBatchId: BatchId, options?: UploadOptions, ): Promise { - const response = await http<{ reference: Reference }>(kyOptions, { - path: endpoint, + const response = await http<{ reference: Reference }>(requestOptions, { + url: endpoint, method: 'post', responseType: 'json', - body: await prepareData(data), + data, headers: { 'content-type': 'application/octet-stream', ...extractUploadHeaders(postageBatchId, options), @@ -37,8 +33,8 @@ export async function upload( }) return { - reference: response.parsedData.reference, - tagUid: makeTagUid(response.headers.get('swarm-tag')), + reference: response.data.reference, + tagUid: makeTagUid(response.headers['swarm-tag']), } } @@ -48,13 +44,13 @@ export async function upload( * @param ky * @param hash Bee content reference */ -export async function download(kyOptions: KyOptions, hash: ReferenceOrEns): Promise { - const response = await http(kyOptions, { +export async function download(requestOptions: BeeRequestOptions, hash: ReferenceOrEns): Promise { + const response = await http(requestOptions, { responseType: 'arraybuffer', - path: `${endpoint}/${hash}`, + url: `${endpoint}/${hash}`, }) - return wrapBytesWithHelpers(new Uint8Array(response.parsedData)) + return wrapBytesWithHelpers(new Uint8Array(response.data)) } /** @@ -64,13 +60,13 @@ export async function download(kyOptions: KyOptions, hash: ReferenceOrEns): Prom * @param hash Bee content reference */ export async function downloadReadable( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, hash: ReferenceOrEns, ): Promise> { - const response = await http>(kyOptions, { + const response = await http>(requestOptions, { responseType: 'stream', - path: `${endpoint}/${hash}`, + url: `${endpoint}/${hash}`, }) - return response.parsedData + return response.data } diff --git a/src/modules/bzz.ts b/src/modules/bzz.ts index 4e6e7eb6..3098b396 100644 --- a/src/modules/bzz.ts +++ b/src/modules/bzz.ts @@ -1,5 +1,6 @@ import { BatchId, + BeeRequestOptions, Collection, CollectionUploadOptions, Data, @@ -11,18 +12,14 @@ import { UploadHeaders, UploadResult, } from '../types' +import { wrapBytesWithHelpers } from '../utils/bytes' +import { assertCollection } from '../utils/collection' import { extractUploadHeaders, readFileHeaders } from '../utils/headers' import { http } from '../utils/http' -import { prepareData } from '../utils/data' -import { makeTar } from '../utils/tar' -import { assertCollection } from '../utils/collection' -import { wrapBytesWithHelpers } from '../utils/bytes' import { isReadable } from '../utils/stream' +import { makeTar } from '../utils/tar' import { makeTagUid } from '../utils/type' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const bzzEndpoint = 'bzz' interface FileUploadHeaders extends UploadHeaders { @@ -50,7 +47,7 @@ function extractFileUploadHeaders(postageBatchId: BatchId, options?: FileUploadO * @param options */ export async function uploadFile( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, data: string | Uint8Array | Readable | ArrayBuffer, postageBatchId: BatchId, name?: string, @@ -58,24 +55,23 @@ export async function uploadFile( ): Promise { if (isReadable(data) && !options?.contentType) { if (!options) options = {} - options.contentType = 'application/octet-stream' } - const response = await http<{ reference: Reference }>(kyOptions, { + const response = await http<{ reference: Reference }>(requestOptions, { method: 'post', - path: bzzEndpoint, - body: await prepareData(data), + url: bzzEndpoint, + data, headers: { ...extractFileUploadHeaders(postageBatchId, options), }, - searchParams: { name }, + params: { name }, responseType: 'json', }) return { - reference: response.parsedData.reference, - tagUid: makeTagUid(response.headers.get('swarm-tag')), + reference: response.data.reference, + tagUid: makeTagUid(response.headers['swarm-tag']), } } @@ -86,15 +82,19 @@ export async function uploadFile( * @param hash Bee file or collection hash * @param path If hash is collection then this defines path to a single file in the collection */ -export async function downloadFile(kyOptions: KyOptions, hash: ReferenceOrEns, path = ''): Promise> { - const response = await http(kyOptions, { +export async function downloadFile( + requestOptions: BeeRequestOptions, + hash: ReferenceOrEns, + path = '', +): Promise> { + const response = await http(requestOptions, { method: 'GET', responseType: 'arraybuffer', - path: `${bzzEndpoint}/${hash}/${path}`, + url: `${bzzEndpoint}/${hash}/${path}`, }) const file = { - ...readFileHeaders(response.headers), - data: wrapBytesWithHelpers(new Uint8Array(response.parsedData)), + ...readFileHeaders(response.headers as Record), + data: wrapBytesWithHelpers(new Uint8Array(response.data)), } return file @@ -108,18 +108,18 @@ export async function downloadFile(kyOptions: KyOptions, hash: ReferenceOrEns, p * @param path If hash is collection then this defines path to a single file in the collection */ export async function downloadFileReadable( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, hash: ReferenceOrEns, path = '', ): Promise>> { - const response = await http>(kyOptions, { + const response = await http>(requestOptions, { method: 'GET', responseType: 'stream', - path: `${bzzEndpoint}/${hash}/${path}`, + url: `${bzzEndpoint}/${hash}/${path}`, }) const file = { - ...readFileHeaders(response.headers), - data: response.parsedData, + ...readFileHeaders(response.headers as Record), + data: response.data, } return file @@ -155,7 +155,7 @@ function extractCollectionUploadHeaders( * @param options */ export async function uploadCollection( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, collection: Collection, postageBatchId: BatchId, options?: CollectionUploadOptions, @@ -163,10 +163,10 @@ export async function uploadCollection( assertCollection(collection) const tarData = makeTar(collection) - const response = await http<{ reference: Reference }>(kyOptions, { + const response = await http<{ reference: Reference }>(requestOptions, { method: 'post', - path: bzzEndpoint, - body: tarData, + url: bzzEndpoint, + data: tarData, responseType: 'json', headers: { 'content-type': 'application/x-tar', @@ -176,7 +176,7 @@ export async function uploadCollection( }) return { - reference: response.parsedData.reference, - tagUid: makeTagUid(response.headers.get('swarm-tag')), + reference: response.data.reference, + tagUid: makeTagUid(response.headers['swarm-tag']), } } diff --git a/src/modules/chunk.ts b/src/modules/chunk.ts index 2dee28f2..4662bb6c 100644 --- a/src/modules/chunk.ts +++ b/src/modules/chunk.ts @@ -1,10 +1,15 @@ -import type { BatchId, Data, Reference, ReferenceOrEns, ReferenceResponse, UploadOptions } from '../types' +import type { + BatchId, + BeeRequestOptions, + Data, + Reference, + ReferenceOrEns, + ReferenceResponse, + UploadOptions, +} from '../types' +import { wrapBytesWithHelpers } from '../utils/bytes' import { extractUploadHeaders } from '../utils/headers' import { http } from '../utils/http' -import { wrapBytesWithHelpers } from '../utils/bytes' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' const endpoint = 'chunks' @@ -21,15 +26,15 @@ const endpoint = 'chunks' * @param options Additional options like tag, encryption, pinning */ export async function upload( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, data: Uint8Array, postageBatchId: BatchId, options?: UploadOptions, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: `${endpoint}`, - body: data, + url: `${endpoint}`, + data, headers: { 'content-type': 'application/octet-stream', ...extractUploadHeaders(postageBatchId, options), @@ -37,7 +42,7 @@ export async function upload( responseType: 'json', }) - return response.parsedData.reference + return response.data.reference } /** @@ -47,11 +52,11 @@ export async function upload( * @param hash Bee content reference * */ -export async function download(kyOptions: KyOptions, hash: ReferenceOrEns): Promise { - const response = await http(kyOptions, { +export async function download(requestOptions: BeeRequestOptions, hash: ReferenceOrEns): Promise { + const response = await http(requestOptions, { responseType: 'arraybuffer', - path: `${endpoint}/${hash}`, + url: `${endpoint}/${hash}`, }) - return wrapBytesWithHelpers(new Uint8Array(response.parsedData)) + return wrapBytesWithHelpers(new Uint8Array(response.data)) } diff --git a/src/modules/debug/balance.ts b/src/modules/debug/balance.ts index 9749e790..552ea298 100644 --- a/src/modules/debug/balance.ts +++ b/src/modules/debug/balance.ts @@ -1,8 +1,5 @@ +import type { BalanceResponse, BeeRequestOptions, PeerBalance } from '../../types' import { http } from '../../utils/http' -import type { PeerBalance, BalanceResponse } from '../../types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' const balancesEndpoint = 'balances' const consumedEndpoint = 'consumed' @@ -12,13 +9,13 @@ const consumedEndpoint = 'consumed' * * @param kyOptions Ky Options for making requests */ -export async function getAllBalances(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: balancesEndpoint, +export async function getAllBalances(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: balancesEndpoint, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -27,13 +24,13 @@ export async function getAllBalances(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: `${balancesEndpoint}/${address}`, +export async function getPeerBalance(requestOptions: BeeRequestOptions, address: string): Promise { + const response = await http(requestOptions, { + url: `${balancesEndpoint}/${address}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -41,13 +38,13 @@ export async function getPeerBalance(kyOptions: KyOptions, address: string): Pro * * @param kyOptions Ky Options for making requests */ -export async function getPastDueConsumptionBalances(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: consumedEndpoint, +export async function getPastDueConsumptionBalances(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: consumedEndpoint, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -56,11 +53,14 @@ export async function getPastDueConsumptionBalances(kyOptions: KyOptions): Promi * @param kyOptions Ky Options for making requests * @param address Swarm address of peer */ -export async function getPastDueConsumptionPeerBalance(kyOptions: KyOptions, address: string): Promise { - const response = await http(kyOptions, { - path: `${consumedEndpoint}/${address}`, +export async function getPastDueConsumptionPeerBalance( + requestOptions: BeeRequestOptions, + address: string, +): Promise { + const response = await http(requestOptions, { + url: `${consumedEndpoint}/${address}`, responseType: 'json', }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/chequebook.ts b/src/modules/debug/chequebook.ts index 8ecae71b..bc966b6e 100644 --- a/src/modules/debug/chequebook.ts +++ b/src/modules/debug/chequebook.ts @@ -1,18 +1,16 @@ -import { http } from '../../utils/http' import type { + BeeRequestOptions, + CashoutOptions, ChequebookAddressResponse, ChequebookBalanceResponse, LastCashoutActionResponse, - TransactionResponse, LastChequesForPeerResponse, LastChequesResponse, NumberString, - CashoutOptions, TransactionHash, + TransactionResponse, } from '../../types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' +import { http } from '../../utils/http' const chequebookEndpoint = 'chequebook' @@ -21,13 +19,13 @@ const chequebookEndpoint = 'chequebook' * * @param kyOptions Ky Options for making requests */ -export async function getChequebookAddress(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: chequebookEndpoint + '/address', +export async function getChequebookAddress(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: chequebookEndpoint + '/address', responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -35,13 +33,13 @@ export async function getChequebookAddress(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: chequebookEndpoint + '/balance', +export async function getChequebookBalance(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: chequebookEndpoint + '/balance', responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -50,13 +48,16 @@ export async function getChequebookBalance(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: chequebookEndpoint + `/cashout/${peer}`, +export async function getLastCashoutAction( + requestOptions: BeeRequestOptions, + peer: string, +): Promise { + const response = await http(requestOptions, { + url: chequebookEndpoint + `/cashout/${peer}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -67,7 +68,7 @@ export async function getLastCashoutAction(kyOptions: KyOptions, peer: string): * @param options */ export async function cashoutLastCheque( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, peer: string, options?: CashoutOptions, ): Promise { @@ -81,14 +82,14 @@ export async function cashoutLastCheque( headers['gas-limit'] = options.gasLimit.toString() } - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: chequebookEndpoint + `/cashout/${peer}`, + url: chequebookEndpoint + `/cashout/${peer}`, responseType: 'json', headers, }) - return response.parsedData.transactionHash + return response.data.transactionHash } /** @@ -97,13 +98,16 @@ export async function cashoutLastCheque( * @param kyOptions Ky Options for making requests * @param peer Swarm address of peer */ -export async function getLastChequesForPeer(kyOptions: KyOptions, peer: string): Promise { - const response = await http(kyOptions, { - path: chequebookEndpoint + `/cheque/${peer}`, +export async function getLastChequesForPeer( + requestOptions: BeeRequestOptions, + peer: string, +): Promise { + const response = await http(requestOptions, { + url: chequebookEndpoint + `/cheque/${peer}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -111,13 +115,13 @@ export async function getLastChequesForPeer(kyOptions: KyOptions, peer: string): * * @param kyOptions Ky Options for making requests */ -export async function getLastCheques(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: chequebookEndpoint + '/cheque', +export async function getLastCheques(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: chequebookEndpoint + '/cheque', responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -129,7 +133,7 @@ export async function getLastCheques(kyOptions: KyOptions): Promise { @@ -139,15 +143,15 @@ export async function depositTokens( headers['gas-price'] = gasPrice.toString() } - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: chequebookEndpoint + '/deposit', + url: chequebookEndpoint + '/deposit', responseType: 'json', - searchParams: { amount: amount.toString(10) }, + params: { amount: amount.toString(10) }, headers, }) - return response.parsedData.transactionHash + return response.data.transactionHash } /** @@ -159,7 +163,7 @@ export async function depositTokens( * @return string Hash of the transaction */ export async function withdrawTokens( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, amount: number | NumberString, gasPrice?: NumberString, ): Promise { @@ -169,13 +173,13 @@ export async function withdrawTokens( headers['gas-price'] = gasPrice.toString() } - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: chequebookEndpoint + '/withdraw', + url: chequebookEndpoint + '/withdraw', responseType: 'json', - searchParams: { amount: amount.toString(10) }, + params: { amount: amount.toString(10) }, headers, }) - return response.parsedData.transactionHash + return response.data.transactionHash } diff --git a/src/modules/debug/chunk.ts b/src/modules/debug/chunk.ts index 72eeb2e6..75a00659 100644 --- a/src/modules/debug/chunk.ts +++ b/src/modules/debug/chunk.ts @@ -1,9 +1,6 @@ -import type { BeeGenericResponse } from '../../types' +import type { BeeGenericResponse, BeeRequestOptions } from '../../types' import { http } from '../../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const endpoint = 'chunks' /** @@ -14,13 +11,16 @@ const endpoint = 'chunks' * * @returns BeeGenericResponse if chunk is found or throws an exception */ -export async function checkIfChunkExistsLocally(kyOptions: KyOptions, address: string): Promise { - const response = await http(kyOptions, { - path: endpoint + `/${address}`, +export async function checkIfChunkExistsLocally( + requestOptions: BeeRequestOptions, + address: string, +): Promise { + const response = await http(requestOptions, { + url: `${endpoint}/${address}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -31,12 +31,15 @@ export async function checkIfChunkExistsLocally(kyOptions: KyOptions, address: s * * @returns BeeGenericResponse if chunk was deleted or throws an exception */ -export async function deleteChunkFromLocalStorage(kyOptions: KyOptions, address: string): Promise { - const response = await http(kyOptions, { +export async function deleteChunkFromLocalStorage( + requestOptions: BeeRequestOptions, + address: string, +): Promise { + const response = await http(requestOptions, { method: 'delete', - path: endpoint + `/${address}`, + url: `${endpoint}/${address}`, responseType: 'json', }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/connectivity.ts b/src/modules/debug/connectivity.ts index b18f0c5a..55472554 100644 --- a/src/modules/debug/connectivity.ts +++ b/src/modules/debug/connectivity.ts @@ -1,64 +1,61 @@ +import type { BeeRequestOptions, NodeAddresses, Peer, PingResponse, RemovePeerResponse, Topology } from '../../types' import { http } from '../../utils/http' -import type { NodeAddresses, Peer, PingResponse, RemovePeerResponse, Topology } from '../../types' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - -export async function getNodeAddresses(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: 'addresses', +export async function getNodeAddresses(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: 'addresses', responseType: 'json', }) - return response.parsedData + return response.data } interface Peers { peers: Peer[] } -export async function getPeers(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: 'peers', +export async function getPeers(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: 'peers', responseType: 'json', }) - return response.parsedData.peers + return response.data.peers } -export async function getBlocklist(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: 'blocklist', +export async function getBlocklist(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: 'blocklist', responseType: 'json', }) - return response.parsedData.peers + return response.data.peers } -export async function removePeer(kyOptions: KyOptions, peer: string): Promise { - const response = await http(kyOptions, { - path: `peers/${peer}`, +export async function removePeer(requestOptions: BeeRequestOptions, peer: string): Promise { + const response = await http(requestOptions, { + url: `peers/${peer}`, responseType: 'json', method: 'DELETE', }) - return response.parsedData + return response.data } -export async function getTopology(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: `topology`, +export async function getTopology(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: `topology`, responseType: 'json', }) - return response.parsedData + return response.data } -export async function pingPeer(kyOptions: KyOptions, peer: string): Promise { - const response = await http(kyOptions, { - path: `pingpong/${peer}`, +export async function pingPeer(requestOptions: BeeRequestOptions, peer: string): Promise { + const response = await http(requestOptions, { + url: `pingpong/${peer}`, responseType: 'json', method: 'POST', }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/settlements.ts b/src/modules/debug/settlements.ts index 86e510ed..da489ce0 100644 --- a/src/modules/debug/settlements.ts +++ b/src/modules/debug/settlements.ts @@ -1,8 +1,5 @@ +import type { AllSettlements, BeeRequestOptions, Settlements } from '../../types' import { http } from '../../utils/http' -import type { Settlements, AllSettlements } from '../../types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' const settlementsEndpoint = 'settlements' @@ -12,13 +9,13 @@ const settlementsEndpoint = 'settlements' * @param kyOptions Ky Options for making requests * @param peer Swarm address of peer */ -export async function getSettlements(kyOptions: KyOptions, peer: string): Promise { - const response = await http(kyOptions, { - path: `${settlementsEndpoint}/${peer}`, +export async function getSettlements(requestOptions: BeeRequestOptions, peer: string): Promise { + const response = await http(requestOptions, { + url: `${settlementsEndpoint}/${peer}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -26,11 +23,11 @@ export async function getSettlements(kyOptions: KyOptions, peer: string): Promis * * @param kyOptions Ky Options for making requests */ -export async function getAllSettlements(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: settlementsEndpoint, +export async function getAllSettlements(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: settlementsEndpoint, responseType: 'json', }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/stake.ts b/src/modules/debug/stake.ts index 9a671d48..6929023f 100644 --- a/src/modules/debug/stake.ts +++ b/src/modules/debug/stake.ts @@ -1,9 +1,12 @@ -import { BeeGenericResponse, NumberString, RedistributionState, TransactionOptions } from '../../types' +import { + BeeGenericResponse, + BeeRequestOptions, + NumberString, + RedistributionState, + TransactionOptions, +} from '../../types' import { http } from '../../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const STAKE_ENDPOINT = 'stake' const REDISTRIBUTION_ENDPOINT = 'redistributionstate' @@ -16,14 +19,14 @@ interface GetStake { * * @param kyOptions Ky Options for making requests */ -export async function getStake(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getStake(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', responseType: 'json', - path: `${STAKE_ENDPOINT}`, + url: `${STAKE_ENDPOINT}`, }) - return response.parsedData.stakedAmount.toString() + return response.data.stakedAmount.toString() } /** @@ -33,7 +36,11 @@ export async function getStake(kyOptions: KyOptions): Promise { * @param amount * @param options */ -export async function stake(kyOptions: KyOptions, amount: NumberString, options?: TransactionOptions): Promise { +export async function stake( + requestOptions: BeeRequestOptions, + amount: NumberString, + options?: TransactionOptions, +): Promise { const headers: Record = {} if (options?.gasPrice) { @@ -44,10 +51,10 @@ export async function stake(kyOptions: KyOptions, amount: NumberString, options? headers['gas-limit'] = options.gasLimit.toString() } - await http(kyOptions, { + await http(requestOptions, { method: 'post', responseType: 'json', - path: `${STAKE_ENDPOINT}/${amount}`, + url: `${STAKE_ENDPOINT}/${amount}`, headers, }) } @@ -57,12 +64,12 @@ export async function stake(kyOptions: KyOptions, amount: NumberString, options? * * @param kyOptions Ky Options for making requests */ -export async function getRedistributionState(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getRedistributionState(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', responseType: 'json', - path: REDISTRIBUTION_ENDPOINT, + url: REDISTRIBUTION_ENDPOINT, }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/stamps.ts b/src/modules/debug/stamps.ts index d485eea4..17a1d96a 100644 --- a/src/modules/debug/stamps.ts +++ b/src/modules/debug/stamps.ts @@ -1,9 +1,13 @@ -import type { BatchId, PostageBatch, NumberString, PostageBatchBuckets, PostageBatchOptions } from '../../types' +import type { + BatchId, + BeeRequestOptions, + NumberString, + PostageBatch, + PostageBatchBuckets, + PostageBatchOptions, +} from '../../types' import { http } from '../../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const STAMPS_ENDPOINT = 'stamps' interface GetAllStampsResponse { @@ -14,41 +18,44 @@ interface StampResponse { batchID: BatchId } -export async function getAllPostageBatches(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getAllPostageBatches(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: `${STAMPS_ENDPOINT}`, + url: `${STAMPS_ENDPOINT}`, responseType: 'json', }) - return response.parsedData.stamps + return response.data.stamps } -export async function getPostageBatch(kyOptions: KyOptions, postageBatchId: BatchId): Promise { - const response = await http(kyOptions, { +export async function getPostageBatch( + requestOptions: BeeRequestOptions, + postageBatchId: BatchId, +): Promise { + const response = await http(requestOptions, { method: 'get', - path: `${STAMPS_ENDPOINT}/${postageBatchId}`, + url: `${STAMPS_ENDPOINT}/${postageBatchId}`, responseType: 'json', }) - return response.parsedData + return response.data } export async function getPostageBatchBuckets( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, postageBatchId: BatchId, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'get', - path: `${STAMPS_ENDPOINT}/${postageBatchId}/buckets`, + url: `${STAMPS_ENDPOINT}/${postageBatchId}/buckets`, responseType: 'json', }) - return response.parsedData + return response.data } export async function createPostageBatch( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, amount: NumberString, depth: number, options?: PostageBatchOptions, @@ -63,33 +70,37 @@ export async function createPostageBatch( headers.immutable = String(options.immutableFlag) } - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: `${STAMPS_ENDPOINT}/${amount}/${depth}`, + url: `${STAMPS_ENDPOINT}/${amount}/${depth}`, responseType: 'json', - searchParams: { label: options?.label }, + params: { label: options?.label }, headers, }) - return response.parsedData.batchID + return response.data.batchID } -export async function topUpBatch(kyOptions: KyOptions, id: string, amount: NumberString): Promise { - const response = await http(kyOptions, { +export async function topUpBatch( + requestOptions: BeeRequestOptions, + id: string, + amount: NumberString, +): Promise { + const response = await http(requestOptions, { method: 'patch', - path: `${STAMPS_ENDPOINT}/topup/${id}/${amount}`, + url: `${STAMPS_ENDPOINT}/topup/${id}/${amount}`, responseType: 'json', }) - return response.parsedData.batchID + return response.data.batchID } -export async function diluteBatch(kyOptions: KyOptions, id: string, depth: number): Promise { - const response = await http(kyOptions, { +export async function diluteBatch(requestOptions: BeeRequestOptions, id: string, depth: number): Promise { + const response = await http(requestOptions, { method: 'patch', - path: `${STAMPS_ENDPOINT}/dilute/${id}/${depth}`, + url: `${STAMPS_ENDPOINT}/dilute/${id}/${depth}`, responseType: 'json', }) - return response.parsedData.batchID + return response.data.batchID } diff --git a/src/modules/debug/states.ts b/src/modules/debug/states.ts index ea7174b6..4b8fb0bc 100644 --- a/src/modules/debug/states.ts +++ b/src/modules/debug/states.ts @@ -1,8 +1,5 @@ +import { BeeRequestOptions, ChainState, ReserveState, WalletBalance } from '../../types' import { http } from '../../utils/http' -import { ChainState, ReserveState, WalletBalance } from '../../types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' const RESERVE_STATE_ENDPOINT = 'reservestate' const WALLET_ENDPOINT = 'wallet' @@ -13,14 +10,14 @@ const CHAIN_STATE_ENDPOINT = 'chainstate' * * @param kyOptions Ky Options for making requests */ -export async function getReserveState(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getReserveState(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: `${RESERVE_STATE_ENDPOINT}`, + url: `${RESERVE_STATE_ENDPOINT}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -28,14 +25,14 @@ export async function getReserveState(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getChainState(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: `${CHAIN_STATE_ENDPOINT}`, + url: `${CHAIN_STATE_ENDPOINT}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -43,14 +40,14 @@ export async function getChainState(kyOptions: KyOptions): Promise { * * @param kyOptions Ky Options for making requests */ -export async function getWalletBalance(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getWalletBalance(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: `${WALLET_ENDPOINT}`, + url: `${WALLET_ENDPOINT}`, responseType: 'json', }) - return mapWalletProperties(response.parsedData) + return mapWalletProperties(response.data) } /** diff --git a/src/modules/debug/status.ts b/src/modules/debug/status.ts index e5bfe5d6..e9984b72 100644 --- a/src/modules/debug/status.ts +++ b/src/modules/debug/status.ts @@ -1,14 +1,12 @@ -import { http } from '../../utils/http' +import getMajorSemver from 'semver/functions/major.js' +import { BeeRequestOptions } from '../../index' import type { Health, NodeInfo } from '../../types/debug' import { BeeVersions } from '../../types/debug' -import getMajorSemver from 'semver/functions/major.js' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' +import { http } from '../../utils/http' // Following lines bellow are automatically updated with GitHub Action when Bee version is updated // so if you are changing anything about them change the `update_bee` action accordingly! -export const SUPPORTED_BEE_VERSION_EXACT = '1.12.0-88c1d236' +export const SUPPORTED_BEE_VERSION_EXACT = '1.13.0-f1067884' export const SUPPORTED_API_VERSION = '4.0.0' export const SUPPORTED_DEBUG_API_VERSION = '4.0.0' @@ -23,14 +21,14 @@ const READINESS_URL = 'readiness' * * @param kyOptions Ky Options for making requests */ -export async function getHealth(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getHealth(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: HEALTH_URL, + url: HEALTH_URL, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -38,11 +36,11 @@ export async function getHealth(kyOptions: KyOptions): Promise { * * @param kyOptions Ky Options for making requests */ -export async function getReadiness(kyOptions: KyOptions): Promise { +export async function getReadiness(requestOptions: BeeRequestOptions): Promise { try { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'get', - path: READINESS_URL, + url: READINESS_URL, }) return response.status === 200 @@ -56,14 +54,14 @@ export async function getReadiness(kyOptions: KyOptions): Promise { * * @param kyOptions Ky Options for making requests */ -export async function getNodeInfo(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getNodeInfo(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', - path: NODE_INFO_URL, + url: NODE_INFO_URL, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -75,8 +73,8 @@ export async function getNodeInfo(kyOptions: KyOptions): Promise { * @deprecated Use `isSupportedExactVersion` instead */ // TODO: Remove on break -export async function isSupportedVersion(kyOptions: KyOptions): Promise { - return isSupportedExactVersion(kyOptions) +export async function isSupportedVersion(requestOptions: BeeRequestOptions): Promise { + return isSupportedExactVersion(requestOptions) } /** @@ -89,8 +87,8 @@ export async function isSupportedVersion(kyOptions: KyOptions): Promise * * @param ky */ -export async function isSupportedExactVersion(kyOptions: KyOptions): Promise { - const { version } = await getHealth(kyOptions) +export async function isSupportedExactVersion(requestOptions: BeeRequestOptions): Promise { + const { version } = await getHealth(requestOptions) return version === SUPPORTED_BEE_VERSION_EXACT } @@ -103,8 +101,8 @@ export async function isSupportedExactVersion(kyOptions: KyOptions): Promise { - const { apiVersion } = await getHealth(kyOptions) +export async function isSupportedMainApiVersion(requestOptions: BeeRequestOptions): Promise { + const { apiVersion } = await getHealth(requestOptions) return getMajorSemver(apiVersion) === getMajorSemver(SUPPORTED_API_VERSION) } @@ -117,8 +115,8 @@ export async function isSupportedMainApiVersion(kyOptions: KyOptions): Promise { - const { debugApiVersion } = await getHealth(kyOptions) +export async function isSupportedDebugApiVersion(requestOptions: BeeRequestOptions): Promise { + const { debugApiVersion } = await getHealth(requestOptions) return getMajorSemver(debugApiVersion) === getMajorSemver(SUPPORTED_DEBUG_API_VERSION) } @@ -130,8 +128,8 @@ export async function isSupportedDebugApiVersion(kyOptions: KyOptions): Promise< * * @param ky */ -export async function isSupportedApiVersion(kyOptions: KyOptions): Promise { - const { apiVersion, debugApiVersion } = await getHealth(kyOptions) +export async function isSupportedApiVersion(requestOptions: BeeRequestOptions): Promise { + const { apiVersion, debugApiVersion } = await getHealth(requestOptions) return ( getMajorSemver(apiVersion) === getMajorSemver(SUPPORTED_API_VERSION) && @@ -145,8 +143,8 @@ export async function isSupportedApiVersion(kyOptions: KyOptions): Promise { - const { version, apiVersion, debugApiVersion } = await getHealth(kyOptions) +export async function getVersions(requestOptions: BeeRequestOptions): Promise { + const { version, apiVersion, debugApiVersion } = await getHealth(requestOptions) return { supportedBeeVersion: SUPPORTED_BEE_VERSION_EXACT, diff --git a/src/modules/debug/tag.ts b/src/modules/debug/tag.ts index c5085f39..71cd0ff7 100644 --- a/src/modules/debug/tag.ts +++ b/src/modules/debug/tag.ts @@ -1,9 +1,6 @@ -import { ExtendedTag } from '../../types' +import { BeeRequestOptions, ExtendedTag } from '../../types' import { http } from '../../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const endpoint = 'tags' /** @@ -12,11 +9,11 @@ const endpoint = 'tags' * @param kyOptions Ky Options for making requests * @param uid UID of tag to be retrieved */ -export async function retrieveExtendedTag(kyOptions: KyOptions, uid: number): Promise { - const response = await http(kyOptions, { - path: `${endpoint}/${uid}`, +export async function retrieveExtendedTag(requestOptions: BeeRequestOptions, uid: number): Promise { + const response = await http(requestOptions, { + url: `${endpoint}/${uid}`, responseType: 'json', }) - return response.parsedData + return response.data } diff --git a/src/modules/debug/transactions.ts b/src/modules/debug/transactions.ts index 6aa29e19..76f098fc 100644 --- a/src/modules/debug/transactions.ts +++ b/src/modules/debug/transactions.ts @@ -1,9 +1,6 @@ -import { NumberString, TransactionHash, TransactionInfo } from '../../types' +import { BeeRequestOptions, NumberString, TransactionHash, TransactionInfo } from '../../types' import { http } from '../../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const transactionsEndpoint = 'transactions' interface PendingTransactionsResponse { @@ -19,13 +16,13 @@ interface TransactionResponse { * * @param ky Debug Ky instance */ -export async function getAllTransactions(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: transactionsEndpoint, +export async function getAllTransactions(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { + url: transactionsEndpoint, responseType: 'json', }) - return response.parsedData.pendingTransactions + return response.data.pendingTransactions } /** @@ -34,13 +31,16 @@ export async function getAllTransactions(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { - path: `${transactionsEndpoint}/${transactionHash}`, +export async function getTransaction( + requestOptions: BeeRequestOptions, + transactionHash: TransactionHash, +): Promise { + const response = await http(requestOptions, { + url: `${transactionsEndpoint}/${transactionHash}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -50,16 +50,16 @@ export async function getTransaction(kyOptions: KyOptions, transactionHash: Tran * @param transactionHash Hash of the transaction */ export async function rebroadcastTransaction( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, transactionHash: TransactionHash, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: `${transactionsEndpoint}/${transactionHash}`, + url: `${transactionsEndpoint}/${transactionHash}`, responseType: 'json', }) - return response.parsedData.transactionHash + return response.data.transactionHash } /** @@ -70,16 +70,16 @@ export async function rebroadcastTransaction( * @param gasPrice Optional gas price */ export async function cancelTransaction( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, transactionHash: TransactionHash, gasPrice?: NumberString, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'delete', headers: { 'gas-price': gasPrice }, - path: `${transactionsEndpoint}/${transactionHash}`, + url: `${transactionsEndpoint}/${transactionHash}`, responseType: 'json', }) - return response.parsedData.transactionHash + return response.data.transactionHash } diff --git a/src/modules/feed.ts b/src/modules/feed.ts index bd267adb..80510eca 100644 --- a/src/modules/feed.ts +++ b/src/modules/feed.ts @@ -1,12 +1,9 @@ -import { BatchId, Reference, ReferenceResponse, Topic } from '../types' -import { filterHeaders, http } from '../utils/http' import { FeedType } from '../feed/type' +import { BatchId, BeeRequestOptions, Reference, ReferenceResponse, Topic } from '../types' +import { BeeError } from '../utils/error' import { HexEthAddress } from '../utils/eth' import { extractUploadHeaders } from '../utils/headers' -import { BeeError } from '../utils/error' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' +import { http } from '../utils/http' const feedEndpoint = 'feeds' @@ -55,26 +52,26 @@ export interface FetchFeedUpdateResponse extends ReferenceResponse, FeedUpdateHe * @param options Additional options, like type (default: 'sequence') */ export async function createFeedManifest( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, owner: HexEthAddress, topic: Topic, postageBatchId: BatchId, options?: CreateFeedOptions, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', responseType: 'json', - path: `${feedEndpoint}/${owner}/${topic}`, - searchParams: filterHeaders(options), + url: `${feedEndpoint}/${owner}/${topic}`, + params: options, headers: extractUploadHeaders(postageBatchId), }) - return response.parsedData.reference + return response.data.reference } -function readFeedUpdateHeaders(headers: Headers): FeedUpdateHeaders { - const feedIndex = headers.get('swarm-feed-index') - const feedIndexNext = headers.get('swarm-feed-index-next') +function readFeedUpdateHeaders(headers: Record): FeedUpdateHeaders { + const feedIndex = headers['swarm-feed-index'] + const feedIndexNext = headers['swarm-feed-index-next'] if (!feedIndex) { throw new BeeError('Response did not contain expected swarm-feed-index!') @@ -104,19 +101,19 @@ function readFeedUpdateHeaders(headers: Headers): FeedUpdateHeaders { * @param options Additional options, like index, at, type */ export async function fetchLatestFeedUpdate( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, owner: HexEthAddress, topic: Topic, options?: FeedUpdateOptions, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { responseType: 'json', - path: `${feedEndpoint}/${owner}/${topic}`, - searchParams: filterHeaders(options), + url: `${feedEndpoint}/${owner}/${topic}`, + params: options, }) return { - ...response.parsedData, - ...readFeedUpdateHeaders(response.headers), + ...response.data, + ...readFeedUpdateHeaders(response.headers as Record), } } diff --git a/src/modules/pinning.ts b/src/modules/pinning.ts index 7aa545fd..25ae68f8 100644 --- a/src/modules/pinning.ts +++ b/src/modules/pinning.ts @@ -1,9 +1,6 @@ -import type { BeeGenericResponse, Pin, Reference } from '../types' +import type { BeeGenericResponse, BeeRequestOptions, Pin, Reference } from '../types' import { http } from '../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const PINNING_ENDPOINT = 'pins' export interface GetAllPinResponse { @@ -16,11 +13,11 @@ export interface GetAllPinResponse { * @param kyOptions Ky Options for making requests * @param reference Bee data reference */ -export async function pin(kyOptions: KyOptions, reference: Reference): Promise { - await http(kyOptions, { +export async function pin(requestOptions: BeeRequestOptions, reference: Reference): Promise { + await http(requestOptions, { method: 'post', responseType: 'json', - path: `${PINNING_ENDPOINT}/${reference}`, + url: `${PINNING_ENDPOINT}/${reference}`, }) } @@ -30,11 +27,11 @@ export async function pin(kyOptions: KyOptions, reference: Reference): Promise { - await http(kyOptions, { +export async function unpin(requestOptions: BeeRequestOptions, reference: Reference): Promise { + await http(requestOptions, { method: 'delete', responseType: 'json', - path: `${PINNING_ENDPOINT}/${reference}`, + url: `${PINNING_ENDPOINT}/${reference}`, }) } @@ -45,14 +42,14 @@ export async function unpin(kyOptions: KyOptions, reference: Reference): Promise * @param reference * @throws Error if given address is not pinned */ -export async function getPin(kyOptions: KyOptions, reference: Reference): Promise { - const response = await http(kyOptions, { +export async function getPin(requestOptions: BeeRequestOptions, reference: Reference): Promise { + const response = await http(requestOptions, { method: 'get', responseType: 'json', - path: `${PINNING_ENDPOINT}/${reference}`, + url: `${PINNING_ENDPOINT}/${reference}`, }) - return response.parsedData + return response.data } /** @@ -60,12 +57,12 @@ export async function getPin(kyOptions: KyOptions, reference: Reference): Promis * * @param ky Ky instance */ -export async function getAllPins(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function getAllPins(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'get', responseType: 'json', - path: `${PINNING_ENDPOINT}`, + url: `${PINNING_ENDPOINT}`, }) - return response.parsedData.references + return response.data.references } diff --git a/src/modules/pss.ts b/src/modules/pss.ts index d204b752..dc1f945c 100644 --- a/src/modules/pss.ts +++ b/src/modules/pss.ts @@ -1,12 +1,7 @@ import WebSocket from 'isomorphic-ws' - -import { prepareData } from '../utils/data' -import { http } from '../utils/http' +import type { BatchId, BeeGenericResponse, BeeRequestOptions, PublicKey } from '../types' import { extractUploadHeaders } from '../utils/headers' -import type { BatchId, BeeGenericResponse, PublicKey } from '../types' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' +import { http } from '../utils/http' const endpoint = 'pss' @@ -22,19 +17,19 @@ const endpoint = 'pss' * */ export async function send( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, topic: string, target: string, data: string | Uint8Array, postageBatchId: BatchId, recipient?: PublicKey, ): Promise { - await http(kyOptions, { + await http(requestOptions, { method: 'post', - path: `${endpoint}/send/${topic}/${target}`, - body: await prepareData(data), + url: `${endpoint}/send/${topic}/${target}`, + data, responseType: 'json', - searchParams: { recipient }, + params: { recipient }, headers: extractUploadHeaders(postageBatchId), }) } diff --git a/src/modules/soc.ts b/src/modules/soc.ts index 56e39d00..975cde08 100644 --- a/src/modules/soc.ts +++ b/src/modules/soc.ts @@ -1,10 +1,7 @@ -import { BatchId, Reference, ReferenceResponse, UploadOptions } from '../types' +import { BatchId, BeeRequestOptions, Reference, ReferenceResponse, UploadOptions } from '../types' import { extractUploadHeaders } from '../utils/headers' import { http } from '../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const socEndpoint = 'soc' /** @@ -19,7 +16,7 @@ const socEndpoint = 'soc' * @param options Additional options like tag, encryption, pinning */ export async function upload( - kyOptions: KyOptions, + requestOptions: BeeRequestOptions, owner: string, identifier: string, signature: string, @@ -27,17 +24,17 @@ export async function upload( postageBatchId: BatchId, options?: UploadOptions, ): Promise { - const response = await http(kyOptions, { + const response = await http(requestOptions, { method: 'post', - path: `${socEndpoint}/${owner}/${identifier}`, - body: data, + url: `${socEndpoint}/${owner}/${identifier}`, + data, headers: { 'content-type': 'application/octet-stream', ...extractUploadHeaders(postageBatchId, options), }, responseType: 'json', - searchParams: { sig: signature }, + params: { sig: signature }, }) - return response.parsedData.reference + return response.data.reference } diff --git a/src/modules/status.ts b/src/modules/status.ts index 3813eb1c..0cbdfef6 100644 --- a/src/modules/status.ts +++ b/src/modules/status.ts @@ -1,15 +1,13 @@ +import { BeeRequestOptions } from '../index' import { http } from '../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - /** * Ping the base bee URL. If connection was not successful throw error * * @param kyOptions Ky instance for given Bee class instance */ -export async function checkConnection(kyOptions: KyOptions): Promise | never { - await http(kyOptions, { - path: '', +export async function checkConnection(requestOptions: BeeRequestOptions): Promise | never { + await http(requestOptions, { + url: '', }) } diff --git a/src/modules/stewardship.ts b/src/modules/stewardship.ts index 026e4d5c..a1c94f89 100644 --- a/src/modules/stewardship.ts +++ b/src/modules/stewardship.ts @@ -1,9 +1,6 @@ -import type { ReferenceOrEns } from '../types' +import type { BeeRequestOptions, ReferenceOrEns } from '../types' import { http } from '../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const stewardshipEndpoint = 'stewardship' /** @@ -13,10 +10,10 @@ const stewardshipEndpoint = 'stewardship' * @param options * @throws BeeResponseError if not locally pinned or invalid data */ -export async function reupload(kyOptions: KyOptions, reference: ReferenceOrEns): Promise { - await http(kyOptions, { +export async function reupload(requestOptions: BeeRequestOptions, reference: ReferenceOrEns): Promise { + await http(requestOptions, { method: 'put', - path: `${stewardshipEndpoint}/${reference}`, + url: `${stewardshipEndpoint}/${reference}`, }) } @@ -24,12 +21,12 @@ interface IsRetrievableResponse { isRetrievable: boolean } -export async function isRetrievable(kyOptions: KyOptions, reference: ReferenceOrEns): Promise { - const response = await http(kyOptions, { +export async function isRetrievable(requestOptions: BeeRequestOptions, reference: ReferenceOrEns): Promise { + const response = await http(requestOptions, { method: 'get', responseType: 'json', - path: `${stewardshipEndpoint}/${reference}`, + url: `${stewardshipEndpoint}/${reference}`, }) - return response.parsedData.isRetrievable + return response.data.isRetrievable } diff --git a/src/modules/tag.ts b/src/modules/tag.ts index 806f1266..09d037fb 100644 --- a/src/modules/tag.ts +++ b/src/modules/tag.ts @@ -1,9 +1,6 @@ -import { Reference, Tag } from '../types' +import { BeeRequestOptions, Reference, Tag } from '../types' import { http } from '../utils/http' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - const endpoint = 'tags' interface GetAllTagsResponse { @@ -15,14 +12,14 @@ interface GetAllTagsResponse { * * @param url Bee tag URL */ -export async function createTag(kyOptions: KyOptions): Promise { - const response = await http(kyOptions, { +export async function createTag(requestOptions: BeeRequestOptions): Promise { + const response = await http(requestOptions, { method: 'post', - path: endpoint, + url: endpoint, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -31,13 +28,13 @@ export async function createTag(kyOptions: KyOptions): Promise { * @param url Bee tag URL * @param uid UID of tag to be retrieved */ -export async function retrieveTag(kyOptions: KyOptions, uid: number): Promise { - const response = await http(kyOptions, { - path: `${endpoint}/${uid}`, +export async function retrieveTag(requestOptions: BeeRequestOptions, uid: number): Promise { + const response = await http(requestOptions, { + url: `${endpoint}/${uid}`, responseType: 'json', }) - return response.parsedData + return response.data } /** @@ -47,14 +44,14 @@ export async function retrieveTag(kyOptions: KyOptions, uid: number): Promise { - const response = await http(kyOptions, { - path: `${endpoint}`, - searchParams: { offset, limit }, +export async function getAllTags(requestOptions: BeeRequestOptions, offset?: number, limit?: number): Promise { + const response = await http(requestOptions, { + url: endpoint, + params: { offset, limit }, responseType: 'json', }) - return response.parsedData.tags + return response.data.tags } /** @@ -62,10 +59,10 @@ export async function getAllTags(kyOptions: KyOptions, offset?: number, limit?: * @param url * @param uid */ -export async function deleteTag(kyOptions: KyOptions, uid: number): Promise { - await http(kyOptions, { +export async function deleteTag(requestOptions: BeeRequestOptions, uid: number): Promise { + await http(requestOptions, { method: 'delete', - path: `${endpoint}/${uid}`, + url: `${endpoint}/${uid}`, }) } @@ -75,11 +72,11 @@ export async function deleteTag(kyOptions: KyOptions, uid: number): Promise { - await http(kyOptions, { +export async function updateTag(requestOptions: BeeRequestOptions, uid: number, reference: Reference): Promise { + await http(requestOptions, { method: 'patch', - path: `${endpoint}/${uid}`, - json: { + url: `${endpoint}/${uid}`, + data: { reference, }, }) diff --git a/src/types/debug.ts b/src/types/debug.ts index dbfe3c12..2f07de47 100644 --- a/src/types/debug.ts +++ b/src/types/debug.ts @@ -1,5 +1,5 @@ import { HexEthAddress } from '../utils/eth' -import { NumberString, PublicKey, Reference, RequestOptions, TransactionHash } from './index' +import { NumberString, PublicKey, Reference, TransactionHash } from './index' /** * Object that contains information about progress of upload of data to network. @@ -98,7 +98,7 @@ export interface TransactionOptions { gasLimit?: NumberString } -export type CashoutOptions = TransactionOptions & RequestOptions +export type CashoutOptions = TransactionOptions export interface CashoutResult { recipient: string diff --git a/src/types/index.ts b/src/types/index.ts index 4c392aaa..51d513d3 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -7,20 +7,12 @@ import type { BeeError } from '../utils/error' import type { EthAddress, HexEthAddress } from '../utils/eth' import type { HexString } from '../utils/hex' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type ky from 'ky-universal' - -import type { Readable as NativeReadable } from 'stream' import type { Readable as CompatibilityReadable } from 'readable-stream' +import type { Readable as NativeReadable } from 'stream' import type { ReadableStream as ReadableStreamPonyfill } from 'web-streams-polyfill' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - export * from './debug' -export type Ky = typeof ky - export interface Dictionary { [Key: string]: T } @@ -99,60 +91,20 @@ export type BatchId = HexString */ export type AddressPrefix = HexString -/** - * Internal interface that represents configuration for creating a request with Ky - */ -export interface KyRequestOptions extends Omit { - path: string - responseType?: 'json' | 'arraybuffer' | 'stream' - - /** - * Overridden parameter that allows undefined as a value. - */ - searchParams?: Record -} - -export interface RequestOptions { - /** - * Timeout of requests in milliseconds - */ - timeout?: number - - /** - * Configure backoff mechanism for requests retries. - * Specifies how many retries will be performed before failing a request. - * Retries are performed for GET, PUT, HEAD, DELETE, OPTIONS and TRACE requests. - * Default is 2. - */ - retry?: number - - /** - * User defined Fetch compatible function - */ - fetch?: Fetch +export type BeeRequestOptions = { + baseURL?: string + timeout?: number | false + retry?: number | false + headers?: Record + onRequest?: (request: BeeRequest) => void } -export interface BeeOptions extends RequestOptions { +export interface BeeOptions extends BeeRequestOptions { /** * Signer object or private key of the Signer in form of either hex string or Uint8Array that will be default signer for the instance. */ signer?: Signer | Uint8Array | string - - /** - * Object that contains default headers that will be present - * in all outgoing bee-js requests for instance of Bee class. - */ - defaultHeaders?: Record - - /** - * Function that registers listener callback for all outgoing HTTP requests that Bee instance makes. - */ - onRequest?: HookCallback - - /** - * Function that registers listener callback for all incoming HTTP responses that Bee instance made. - */ - onResponse?: HookCallback + onRequest?: (request: BeeRequest) => void } export interface UploadResultWithCid extends UploadResult { @@ -180,7 +132,7 @@ export interface UploadResult { tagUid: number } -export interface UploadOptions extends RequestOptions { +export interface UploadOptions { /** * Will pin the data locally in the Bee node as well. * @@ -295,7 +247,7 @@ export interface Tag { startedAt: string } -export interface AllTagsOptions extends RequestOptions { +export interface AllTagsOptions { limit?: number offset?: number } @@ -380,7 +332,7 @@ export type HookCallback = (value: V) => void | Promise export interface BeeRequest { url: string - method: HttpMethod + method: string headers?: Record params?: Record } @@ -434,7 +386,7 @@ export interface FeedReader { download(options?: FeedUpdateOptions): Promise } -export interface JsonFeedOptions extends RequestOptions { +export interface JsonFeedOptions { /** * Valid only for `get` action, where either this `address` or `signer` has * to be specified. @@ -552,7 +504,7 @@ export interface TransactionInfo { /** * Options for creation of postage batch */ -export interface PostageBatchOptions extends RequestOptions { +export interface PostageBatchOptions { /** * Sets label for the postage batch */ @@ -648,5 +600,3 @@ interface JsonMap { [key: string]: AnyJson } type JsonArray = Array - -type Fetch = (input: RequestInfo, init?: RequestInit) => Promise diff --git a/src/utils/error.ts b/src/utils/error.ts index 41462977..1f6edf87 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -1,5 +1,3 @@ -import { KyRequestOptions } from '../types' - export class BeeError extends Error { public constructor(message: string) { super(message) @@ -11,38 +9,3 @@ export class BeeArgumentError extends BeeError { super(message) } } - -export class BeeRequestError extends BeeError { - /** - * @param message - * @param requestOptions KyOptions that were used to assemble the request. THIS MIGHT NOT BE COMPLETE! If custom Ky instance was used that has set defaults then these defaults are not visible in this object! - */ - public constructor(message: string, readonly requestOptions: KyRequestOptions) { - super(message) - } -} - -export class BeeResponseError extends BeeError { - /** - * @param status HTTP status code number - * @param response Response returned from the server - * @param responseBody Response body as string which is returned from response.text() call - * @param requestOptions KyOptions that were used to assemble the request. THIS MIGHT NOT BE COMPLETE! If custom Ky instance was used that has set defaults then these defaults are not visible in this object! - * @param message - */ - public constructor( - readonly status: number, - readonly response: Response, - readonly responseBody: string, - readonly requestOptions: KyRequestOptions, - message: string, - ) { - super(message) - } -} - -export class BeeNotAJsonError extends BeeError { - public constructor() { - super(`Received response is not valid JSON.`) - } -} diff --git a/src/utils/headers.ts b/src/utils/headers.ts index fafd3bcd..8b7b8963 100644 --- a/src/utils/headers.ts +++ b/src/utils/headers.ts @@ -32,10 +32,10 @@ function readTagUid(header: string | null): number | undefined { return parseInt(header, 10) } -export function readFileHeaders(headers: Headers): FileHeaders { - const name = readContentDispositionFilename(headers.get('content-disposition')) - const tagUid = readTagUid(headers.get('swarm-tag-uid')) - const contentType = headers.get('content-type') || undefined +export function readFileHeaders(headers: Record): FileHeaders { + const name = readContentDispositionFilename(headers['content-disposition']) + const tagUid = readTagUid(headers['swarm-tag-uid']) + const contentType = headers['content-type'] || undefined return { name, diff --git a/src/utils/http.ts b/src/utils/http.ts index 58eb247c..8b87e2dc 100644 --- a/src/utils/http.ts +++ b/src/utils/http.ts @@ -1,188 +1,37 @@ -import { BeeError, BeeNotAJsonError, BeeRequestError, BeeResponseError } from './error' -import type { BeeRequest, BeeResponse, HookCallback, HttpMethod, Ky } from '../types' +import axios, { AxiosRequestConfig, AxiosResponse } from 'axios' +import { Objects, Strings } from 'cafe-utility' +import { BeeRequestOptions } from '../index' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { HTTPError, Options as KyOptions } from 'ky-universal' -import { normalizeToReadableStream } from './stream' -import { isObject, isStrictlyObject } from './type' -import { KyRequestOptions } from '../types' -import { deepMerge } from './merge' - -export const DEFAULT_KY_CONFIG: KyOptions = { +export const DEFAULT_HTTP_CONFIG = { headers: { accept: 'application/json, text/plain, */*', - 'user-agent': `bee-js`, }, } -interface UndiciError { - cause: Error -} - -interface KyResponse extends Response { - parsedData: T -} - -function isHttpError(e: unknown): e is HTTPError { - return isObject(e) && typeof e.response !== 'undefined' -} - -function isHttpRequestError(e: unknown): e is Error { - return isObject(e) && typeof e.request !== 'undefined' -} - -function headersToObject(header: Headers) { - return [...header.entries()].reduce>((obj, [key, val]) => { - obj[key] = val - - return obj - }, {}) -} - -function wrapRequest(request: Request): BeeRequest { - return { - url: request.url, - method: request.method.toUpperCase() as HttpMethod, - headers: headersToObject(request.headers), - } -} - -export function wrapRequestClosure(cb: HookCallback): (request: Request) => Promise { - return async (request: Request) => { - await cb(wrapRequest(request)) - } -} - -export function wrapResponseClosure( - cb: HookCallback, -): (request: Request, options: unknown, response: Response) => Promise { - return async (request: Request, options: unknown, response: Response) => { - await cb({ - headers: headersToObject(response.headers), - status: response.status, - statusText: response.statusText, - request: wrapRequest(request), - }) - } -} - -/** - * Filters out entries that has undefined value from headers object. - * Modifies the original object! - * - * @param obj - */ -// eslint-disable-next-line @typescript-eslint/ban-types -export function filterHeaders(obj?: object): Record | undefined { - if (obj === undefined) { - return undefined - } - - isStrictlyObject(obj) - - const typedObj = obj as Record - - for (const key in typedObj) { - if (typedObj[key] === undefined) { - delete typedObj[key] - } - } - - if (Object.keys(typedObj).length === 0) { - return undefined - } - - return typedObj -} - /** - * Main utility function to make HTTP requests. - * @param kyOptions - * @param config + * Main function to make HTTP requests. + * @param options User defined settings + * @param config Internal settings and/or Bee settings */ -export async function http(kyOptions: KyOptions, config: KyRequestOptions): Promise> { +export async function http(options: BeeRequestOptions, config: AxiosRequestConfig): Promise> { try { - const ky = await getKy() - const { path, responseType, ...kyConfig } = deepMerge(kyOptions as KyRequestOptions, config) - - const response = (await ky(path, { - ...kyConfig, - searchParams: filterHeaders(kyConfig.searchParams), - })) as KyResponse - - switch (responseType) { - case 'stream': - if (!response.body) { - throw new BeeError('Response was expected to get data but did not get any!') - } - - response.parsedData = normalizeToReadableStream(response.body) as unknown as T - break - case 'arraybuffer': - response.parsedData = (await response.arrayBuffer()) as unknown as T - break - case 'json': - try { - response.parsedData = (await response.json()) as unknown as T - } catch (e) { - throw new BeeNotAJsonError() - } - break - default: - break // If responseType is not set, then no data are expected - } + const requestConfig: AxiosRequestConfig = Objects.deepMerge3(DEFAULT_HTTP_CONFIG, config, options) + maybeRunOnRequestHook(options, requestConfig) + const response = await axios(requestConfig) return response } catch (e) { - // Passthrough thrown errors - if (e instanceof BeeNotAJsonError) { - throw e - } - - if (isHttpError(e)) { - let message - - // We store the response body here as it can be read only once in Response's lifecycle so to make it exposed - // to the user in the BeeResponseError, for further analysis. - const body = await e.response.text() - - try { - // The response can be Bee's JSON with structure `{code, message}` lets try to parse it - message = JSON.parse(body).message - } catch (e) {} - - if (message) { - throw new BeeResponseError(e.response.status, e.response, body, config, `${e.response.statusText}: ${message}`) - } else { - throw new BeeResponseError(e.response.status, e.response, body, config, e.response.statusText) - } - } else if (isHttpRequestError(e)) { - throw new BeeRequestError(e.message, config) - } else { - // Node 18 has native `fetch` implementation called Undici. Errors from this implementation have top level generic - // message "fetch failed" with the more specific error placed into `cause` property. Instead of "fetch failed" we - // expose the underlying problem. - if ((e as UndiciError).cause) { - throw new BeeError((e as UndiciError).cause.message) - } - - throw new BeeError((e as Error).message) - } + throw e } } -let ky: Ky | undefined - -async function getKy(): Promise { - if (ky) { - return ky - } - - ky = (await import('ky-universal')).default - - if (!ky) { - throw new Error('Ky was not found while it should have been!') +function maybeRunOnRequestHook(options: BeeRequestOptions, requestConfig: AxiosRequestConfig) { + if (options.onRequest) { + options.onRequest({ + method: requestConfig.method || 'GET', + url: Strings.joinUrl(requestConfig.baseURL as string, requestConfig.url as string), + headers: { ...requestConfig.headers } as Record, + params: requestConfig.params, + }) } - - return ky } diff --git a/src/utils/merge.ts b/src/utils/merge.ts deleted file mode 100644 index b0cf3520..00000000 --- a/src/utils/merge.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { isObject } from './type' - -/** - * Function that deep merges objects - * - * @copyright https://github.com/sindresorhus/ky/blob/b3c9e88fa49d50150dbb6e6b771b4af56cb40c98/source/utils/merge.ts - * @licence MIT - * @param sources - */ -export function deepMerge(...sources: Array | undefined>): T { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let returnValue: any = {} - - for (const source of sources) { - if (Array.isArray(source)) { - if (!Array.isArray(returnValue)) { - returnValue = [] - } - - returnValue = [...returnValue, ...source] - } else if (isObject(source)) { - // eslint-disable-next-line prefer-const - for (let [key, value] of Object.entries(source)) { - if (isObject(value) && key in returnValue) { - value = deepMerge(returnValue[key], value) - } - - returnValue = { ...returnValue, [key]: value } - } - } - } - - return returnValue -} diff --git a/src/utils/sleep.ts b/src/utils/sleep.ts deleted file mode 100644 index 3270d4ea..00000000 --- a/src/utils/sleep.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Sleep for N miliseconds - * - * @param ms Number of miliseconds to sleep - */ -export async function sleep(ms: number): Promise { - return new Promise(resolve => setTimeout(() => resolve(), ms)) -} diff --git a/src/utils/tar.ts b/src/utils/tar.ts index f7429256..06e3efe8 100644 --- a/src/utils/tar.ts +++ b/src/utils/tar.ts @@ -1,5 +1,5 @@ -import { Collection } from '../types' import Tar from 'tar-js' +import { Collection } from '../types' // this is a workaround type so that we are able to pass in Uint8Arrays // as string to `tar.append` @@ -20,7 +20,7 @@ function fixUnicodePath(path: string): StringLike { } export function makeTar(data: Collection): Uint8Array { - const tar = new Tar() + const tar = new Tar(1) for (const entry of data) { const path = fixUnicodePath(entry.path) tar.append(path, entry.data) diff --git a/src/utils/type.ts b/src/utils/type.ts index 5e32a9e7..41e69b73 100644 --- a/src/utils/type.ts +++ b/src/utils/type.ts @@ -1,37 +1,37 @@ +import { decodeCid, encodeReference, ReferenceType } from '@ethersphere/swarm-cid' import { Address, - ADDRESS_HEX_LENGTH, AddressPrefix, + ADDRESS_HEX_LENGTH, AllTagsOptions, - BATCH_ID_HEX_LENGTH, BatchId, + BATCH_ID_HEX_LENGTH, + BeeRequestOptions, + CashoutOptions, CollectionUploadOptions, ENCRYPTED_REFERENCE_HEX_LENGTH, FileUploadOptions, NumberString, + PostageBatchOptions, PssMessageHandler, + PSS_TARGET_HEX_LENGTH_MAX, PUBKEY_HEX_LENGTH, PublicKey, Readable, Reference, + ReferenceOrEns, REFERENCE_HEX_LENGTH, Tag, TAGS_LIMIT_MAX, TAGS_LIMIT_MIN, - PSS_TARGET_HEX_LENGTH_MAX, - UploadOptions, TransactionHash, - RequestOptions, - PostageBatchOptions, - CashoutOptions, - ReferenceOrEns, TransactionOptions, + UploadOptions, } from '../types' import { BeeArgumentError, BeeError } from './error' import { isFile } from './file' import { assertHexString, assertPrefixedHexString, isHexString } from './hex' import { isReadable } from './stream' -import { decodeCid, encodeReference, ReferenceType } from '@ethersphere/swarm-cid' export function isUint8Array(obj: unknown): obj is Uint8Array { return obj instanceof Uint8Array @@ -218,7 +218,7 @@ export function assertBatchId(value: unknown): asserts value is BatchId { assertHexString(value, BATCH_ID_HEX_LENGTH, 'BatchId') } -export function assertRequestOptions(value: unknown, name = 'RequestOptions'): asserts value is RequestOptions { +export function assertRequestOptions(value: unknown, name = 'RequestOptions'): asserts value is BeeRequestOptions { if (value === undefined) { return } @@ -227,7 +227,7 @@ export function assertRequestOptions(value: unknown, name = 'RequestOptions'): a throw new TypeError(`${name} has to be an object!`) } - const options = value as RequestOptions + const options = value as BeeRequestOptions if (options.retry) { assertNonNegativeInteger(options.retry, `${name}.retry`) @@ -236,10 +236,6 @@ export function assertRequestOptions(value: unknown, name = 'RequestOptions'): a if (options.timeout) { assertNonNegativeInteger(options.timeout, `${name}.timeout`) } - - if (options.fetch && typeof options.fetch !== 'function') { - throw new TypeError(`${name}.fetch has to be a function or undefined!`) - } } export function assertUploadOptions(value: unknown, name = 'UploadOptions'): asserts value is UploadOptions { diff --git a/test/integration/bee-class.spec.ts b/test/integration/bee-class.spec.ts index 489d80f2..e53751d9 100644 --- a/test/integration/bee-class.spec.ts +++ b/test/integration/bee-class.spec.ts @@ -1,6 +1,8 @@ +import { System } from 'cafe-utility' import { expect } from 'chai' import { expect as jestExpect } from 'expect' -import { Bee, BeeDebug, BeeResponseError, BytesReference, Collection, PssSubscription } from '../../src' +import { Readable } from 'stream' +import { Bee, BeeDebug, BytesReference, Collection, PssSubscription } from '../../src' import { makeSigner } from '../../src/chunk/signer' import { makeSOCAddress, uploadSingleOwnerChunkData } from '../../src/chunk/soc' import * as bzz from '../../src/modules/bzz' @@ -29,8 +31,6 @@ import { testJsonPayload, tryDeleteChunkFromLocalStorage, } from '../utils' -import { Readable } from 'stream' -import { sleep } from '../../src/utils/sleep' commonMatchers() @@ -359,7 +359,7 @@ describe('Bee class', () => { const content = randomByteArray(16, Date.now()) const result = await bee.uploadData(getPostageBatch(), content, { pin: true }) - await sleep(10) + await System.sleepMillis(10) await bee.reuploadPinnedData(result.reference) // Does not return anything, but will throw exception if something is going wrong }) @@ -368,7 +368,7 @@ describe('Bee class', () => { const content = randomByteArray(16, Date.now()) const result = await bee.uploadData(getPostageBatch(), content, { pin: true }) - await sleep(10) + await System.sleepMillis(10) await expect(bee.isReferenceRetrievable(result.reference)).eventually.to.eql(true) // Reference that has correct form, but should not exist on the network @@ -547,11 +547,9 @@ describe('Bee class', () => { try { await feed.download({ index: '0000000000000001' }) throw new Error('Should fail') - } catch (err) { - const e = err as BeeResponseError - - expect(e.status).to.eql(404) - expect(e.responseBody).to.contain('chunk not found') + } catch (e: any) { + expect(e.response.status).to.eql(404) + expect(e.response.data).to.contain('chunk not found') } }) diff --git a/test/integration/bee-debug-class.spec.ts b/test/integration/bee-debug-class.spec.ts index 1e8d4426..a7d629ac 100644 --- a/test/integration/bee-debug-class.spec.ts +++ b/test/integration/bee-debug-class.spec.ts @@ -1,13 +1,13 @@ +import { System } from 'cafe-utility' import { expect } from 'chai' import { expect as jestExpect } from 'expect' import { BeeArgumentError, BeeDebug } from '../../src' import { beeDebugUrl, - getOrCreatePostageBatch, BLOCKCHAIN_TRANSACTION_TIMEOUT, + getOrCreatePostageBatch, WAITING_USABLE_STAMP_TIMEOUT, } from '../utils' -import { sleep } from '../../src/utils/sleep' describe('Bee Debug class', () => { const BEE_DEBUG_URL = beeDebugUrl() @@ -38,7 +38,7 @@ describe('Bee Debug class', () => { await beeDebug.topUpBatch(batch.batchID, '10') - await sleep(4000) + await System.sleepMillis(4000) const batchDetails = await beeDebug.getPostageBatch(batch.batchID) const newAmount = (parseInt(batch.amount) + 10).toString() expect(batchDetails.amount).to.eql(newAmount) diff --git a/test/integration/chunk/bmt.spec.ts b/test/integration/chunk/bmt.spec.ts index f4741d4c..31637313 100644 --- a/test/integration/chunk/bmt.spec.ts +++ b/test/integration/chunk/bmt.spec.ts @@ -1,9 +1,9 @@ +import { expect } from 'chai' import { bmtHash } from '../../../src/chunk/bmt' -import { beeKyOptions, getPostageBatch, randomByteArray } from '../../utils' -import * as chunk from '../../../src/modules/chunk' import { makeSpan } from '../../../src/chunk/span' +import * as chunk from '../../../src/modules/chunk' import { bytesToHex } from '../../../src/utils/hex' -import { expect } from 'chai' +import { beeKyOptions, getPostageBatch, randomByteArray } from '../../utils' describe('bmt', () => { it('should produce the same hash as Bee', async function () { diff --git a/test/integration/chunk/cac.spec.ts b/test/integration/chunk/cac.spec.ts index 53452669..fb30a87c 100644 --- a/test/integration/chunk/cac.spec.ts +++ b/test/integration/chunk/cac.spec.ts @@ -1,9 +1,9 @@ +import { expect } from 'chai' +import { assertValidChunkData, makeContentAddressedChunk } from '../../../src/chunk/cac' +import * as chunkAPI from '../../../src/modules/chunk' import { assertBytes } from '../../../src/utils/bytes' -import { makeContentAddressedChunk, assertValidChunkData } from '../../../src/chunk/cac' +import { bytesToHex, hexToBytes } from '../../../src/utils/hex' import { beeKyOptions, getPostageBatch } from '../../utils' -import * as chunkAPI from '../../../src/modules/chunk' -import { hexToBytes, bytesToHex } from '../../../src/utils/hex' -import { expect } from 'chai' describe('cac', () => { const payload = new Uint8Array([1, 2, 3]) diff --git a/test/integration/chunk/soc.spec.ts b/test/integration/chunk/soc.spec.ts index defe8ee2..7c9cd3c5 100644 --- a/test/integration/chunk/soc.spec.ts +++ b/test/integration/chunk/soc.spec.ts @@ -1,11 +1,11 @@ -import { Bytes, assertBytes } from '../../../src/utils/bytes' -import { makeSingleOwnerChunk, makeSingleOwnerChunkFromData, uploadSingleOwnerChunk } from '../../../src/chunk/soc' +import { expect } from 'chai' import { makeContentAddressedChunk } from '../../../src/chunk/cac' -import { beeKyOptions, getPostageBatch, testIdentity, tryDeleteChunkFromLocalStorage } from '../../utils' import { makePrivateKeySigner } from '../../../src/chunk/signer' +import { makeSingleOwnerChunk, makeSingleOwnerChunkFromData, uploadSingleOwnerChunk } from '../../../src/chunk/soc' import * as chunkAPI from '../../../src/modules/chunk' -import { HexString, hexToBytes, bytesToHex } from '../../../src/utils/hex' -import { expect } from 'chai' +import { assertBytes, Bytes } from '../../../src/utils/bytes' +import { bytesToHex, HexString, hexToBytes } from '../../../src/utils/hex' +import { beeKyOptions, getPostageBatch, testIdentity, tryDeleteChunkFromLocalStorage } from '../../utils' describe('soc', () => { const privateKey = hexToBytes(testIdentity.privateKey) diff --git a/test/integration/feed/index.spec.ts b/test/integration/feed/index.spec.ts index b41cce33..0fd5f460 100644 --- a/test/integration/feed/index.spec.ts +++ b/test/integration/feed/index.spec.ts @@ -1,25 +1,21 @@ +import { expect } from 'chai' +import { makeContentAddressedChunk } from '../../../src/chunk/cac' +import { makePrivateKeySigner } from '../../../src/chunk/signer' +import { downloadFeedUpdate, findNextIndex, Index, updateFeed } from '../../../src/feed' +import * as chunkAPI from '../../../src/modules/chunk' import { fetchLatestFeedUpdate } from '../../../src/modules/feed' +import type { BeeRequestOptions, BytesReference, PrivateKeyBytes, Signer, Topic } from '../../../src/types' +import { assertBytes, Bytes } from '../../../src/utils/bytes' import { hexToBytes, makeHexString } from '../../../src/utils/hex' import { beeKyOptions, ERR_TIMEOUT, getPostageBatch, testIdentity } from '../../utils' -import { downloadFeedUpdate, findNextIndex, Index, updateFeed } from '../../../src/feed' -import { Bytes, assertBytes } from '../../../src/utils/bytes' -import { makePrivateKeySigner } from '../../../src/chunk/signer' -import { makeContentAddressedChunk } from '../../../src/chunk/cac' -import * as chunkAPI from '../../../src/modules/chunk' -import type { BytesReference, PrivateKeyBytes, Signer, Topic } from '../../../src/types' -import { BeeResponseError } from '../../../src' - -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' -import { expect } from 'chai' function makeChunk(index: number) { return makeContentAddressedChunk(new Uint8Array([index])) } -async function uploadChunk(kyOptions: KyOptions, index: number): Promise { +async function uploadChunk(options: BeeRequestOptions, index: number): Promise { const chunk = makeChunk(index) - const reference = await chunkAPI.upload(kyOptions, chunk.data, getPostageBatch()) + const reference = await chunkAPI.upload(options, chunk.data, getPostageBatch()) return hexToBytes(reference) as BytesReference } @@ -28,16 +24,16 @@ async function uploadChunk(kyOptions: KyOptions, index: number): Promise { it('getPeers', async function () { diff --git a/test/integration/modules/debug/settlements.spec.ts b/test/integration/modules/debug/settlements.spec.ts index 4b0a6052..c395da6a 100644 --- a/test/integration/modules/debug/settlements.spec.ts +++ b/test/integration/modules/debug/settlements.spec.ts @@ -1,7 +1,7 @@ -import * as settlements from '../../../../src/modules/debug/settlements' -import { beeDebugKyOptions, commonMatchers } from '../../../utils' import { expect } from 'chai' import { expect as jestExpect } from 'expect' +import * as settlements from '../../../../src/modules/debug/settlements' +import { beeDebugKyOptions, commonMatchers } from '../../../utils' commonMatchers() diff --git a/test/integration/modules/debug/states.spec.ts b/test/integration/modules/debug/states.spec.ts index 67f0e638..5ec6e9de 100644 --- a/test/integration/modules/debug/states.spec.ts +++ b/test/integration/modules/debug/states.spec.ts @@ -1,6 +1,6 @@ -import { beeDebugKyOptions, commonMatchers } from '../../../utils' -import * as states from '../../../../src/modules/debug/states' import { expect } from 'chai' +import * as states from '../../../../src/modules/debug/states' +import { beeDebugKyOptions, commonMatchers } from '../../../utils' const BEE_DEBUG_URL = beeDebugKyOptions() commonMatchers() diff --git a/test/integration/modules/debug/status.spec.ts b/test/integration/modules/debug/status.spec.ts index 8c757bac..6c7b6928 100644 --- a/test/integration/modules/debug/status.spec.ts +++ b/test/integration/modules/debug/status.spec.ts @@ -1,7 +1,13 @@ +import { expect } from 'chai' +import { expect as jestExpect } from 'expect' +import fs from 'fs' +import path from 'path' +import semver from 'semver' +import * as util from 'util' import { getHealth, - getVersions, getReadiness, + getVersions, isSupportedApiVersion, isSupportedDebugApiVersion, isSupportedExactVersion, @@ -12,12 +18,6 @@ import { SUPPORTED_DEBUG_API_VERSION, } from '../../../../src/modules/debug/status' import { beeDebugKyOptions } from '../../../utils' -import fs from 'fs' -import path from 'path' -import * as util from 'util' -import semver from 'semver' -import { expect } from 'chai' -import { expect as jestExpect } from 'expect' const BEE_DEBUG_URL = beeDebugKyOptions() diff --git a/test/integration/modules/debug/tag.spec.ts b/test/integration/modules/debug/tag.spec.ts index 9b642bc6..23b1aea8 100644 --- a/test/integration/modules/debug/tag.spec.ts +++ b/test/integration/modules/debug/tag.spec.ts @@ -1,7 +1,7 @@ -import * as beeTag from '../../../../src/modules/tag' +import { expect as jestExpect } from 'expect' import * as beeDebugTag from '../../../../src/modules/debug/tag' +import * as beeTag from '../../../../src/modules/tag' import { beeDebugKyOptions, beeKyOptions } from '../../../utils' -import { expect as jestExpect } from 'expect' const BEE_URL = beeKyOptions() const BEE_DEBUG_KY = beeDebugKyOptions() diff --git a/test/integration/modules/debug/transactions.spec.ts b/test/integration/modules/debug/transactions.spec.ts index 2488125c..0d5257f1 100644 --- a/test/integration/modules/debug/transactions.spec.ts +++ b/test/integration/modules/debug/transactions.spec.ts @@ -1,6 +1,6 @@ +import { expect } from 'chai' import * as transactions from '../../../../src/modules/debug/transactions' import { beeDebugKyOptions, commonMatchers } from '../../../utils' -import { expect } from 'chai' commonMatchers() diff --git a/test/integration/modules/feed.spec.ts b/test/integration/modules/feed.spec.ts index 65f2d620..e3ba28fa 100644 --- a/test/integration/modules/feed.spec.ts +++ b/test/integration/modules/feed.spec.ts @@ -1,4 +1,7 @@ +import { expect } from 'chai' import { createFeedManifest, fetchLatestFeedUpdate } from '../../../src/modules/feed' +import { upload as uploadSOC } from '../../../src/modules/soc' +import type { Topic } from '../../../src/types' import { HexString, hexToBytes, makeHexString } from '../../../src/utils/hex' import { beeKyOptions, @@ -8,9 +11,6 @@ import { testIdentity, tryDeleteChunkFromLocalStorage, } from '../../utils' -import { upload as uploadSOC } from '../../../src/modules/soc' -import type { Topic } from '../../../src/types' -import { expect } from 'chai' commonMatchers() diff --git a/test/integration/modules/pinning.spec.ts b/test/integration/modules/pinning.spec.ts index 998a9984..723055c9 100644 --- a/test/integration/modules/pinning.spec.ts +++ b/test/integration/modules/pinning.spec.ts @@ -1,19 +1,19 @@ -import * as pinning from '../../../src/modules/pinning' -import * as bzz from '../../../src/modules/bzz' +import { expect } from 'chai' import * as bytes from '../../../src/modules/bytes' +import * as bzz from '../../../src/modules/bzz' import * as chunk from '../../../src/modules/chunk' +import * as pinning from '../../../src/modules/pinning' +import { Collection } from '../../../src/types' import { + beeKyOptions, + commonMatchers, + ERR_TIMEOUT, + getPostageBatch, invalidReference, randomByteArray, testChunkData, testChunkHash, - ERR_TIMEOUT, - getPostageBatch, - commonMatchers, - beeKyOptions, } from '../../utils' -import { Collection } from '../../../src/types' -import { expect } from 'chai' const BEE_KY_OPTIONS = beeKyOptions() commonMatchers() diff --git a/test/integration/modules/pss.spec.ts b/test/integration/modules/pss.spec.ts index 93cae291..dc137354 100644 --- a/test/integration/modules/pss.spec.ts +++ b/test/integration/modules/pss.spec.ts @@ -1,5 +1,6 @@ -import * as pss from '../../../src/modules/pss' +import { expect } from 'chai' import * as connectivity from '../../../src/modules/debug/connectivity' +import * as pss from '../../../src/modules/pss' import { beeDebugKyOptions, beeKyOptions, @@ -10,7 +11,6 @@ import { makeTestTarget, PSS_TIMEOUT, } from '../../utils' -import { expect } from 'chai' const BEE_KY_OPTIONS = beeKyOptions() const BEE_URL = beeUrl() diff --git a/test/integration/modules/tag.spec.ts b/test/integration/modules/tag.spec.ts index 46a321ad..90e10bc0 100644 --- a/test/integration/modules/tag.spec.ts +++ b/test/integration/modules/tag.spec.ts @@ -1,7 +1,7 @@ -import * as tag from '../../../src/modules/tag' -import { beeKyOptions, commonMatchers } from '../../utils' import { expect } from 'chai' import { expect as jestExpect } from 'expect' +import * as tag from '../../../src/modules/tag' +import { beeKyOptions, commonMatchers } from '../../utils' const BEE_KY_OPTIONS = beeKyOptions() diff --git a/test/tests-setup.ts b/test/tests-setup.ts index c37873a6..bca50887 100644 --- a/test/tests-setup.ts +++ b/test/tests-setup.ts @@ -1,9 +1,7 @@ /* eslint-disable no-console */ +import { BatchId, BeeRequestOptions } from '../src' import { createPostageBatch, getPostageBatch } from '../src/modules/debug/stamps' -import { BatchId } from '../src' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' import chai, { Assertion } from 'chai' import chaiAsPromised from 'chai-as-promised' import chaiParentheses from 'chai-parentheses' @@ -32,18 +30,18 @@ export async function mochaGlobalSetup(): Promise { }) try { - const beeDebugKyOptions: KyOptions = { - prefixUrl: process.env.BEE_DEBUG_API_URL || 'http://127.0.0.1:1635/', + const beeDebugRequestOptions: BeeRequestOptions = { + baseURL: process.env.BEE_DEBUG_API_URL || 'http://127.0.0.1:1635/', timeout: false, } - const beeDebugPeerKyOptions: KyOptions = { - prefixUrl: process.env.BEE_PEER_DEBUG_API_URL || 'http://127.0.0.1:11635/', + const beeDebugPeerRequestOptions: BeeRequestOptions = { + baseURL: process.env.BEE_PEER_DEBUG_API_URL || 'http://127.0.0.1:11635/', timeout: false, } if (process.env.BEE_POSTAGE) { try { - if (!(await getPostageBatch(beeDebugKyOptions, process.env.BEE_POSTAGE as BatchId)).usable) { + if (!(await getPostageBatch(beeDebugRequestOptions, process.env.BEE_POSTAGE as BatchId)).usable) { delete process.env.BEE_POSTAGE console.log('BEE_POSTAGE stamp was found but is not usable') } else { @@ -57,7 +55,7 @@ export async function mochaGlobalSetup(): Promise { if (process.env.BEE_PEER_POSTAGE) { try { - if (!(await getPostageBatch(beeDebugPeerKyOptions, process.env.BEE_PEER_POSTAGE as BatchId)).usable) { + if (!(await getPostageBatch(beeDebugPeerRequestOptions, process.env.BEE_PEER_POSTAGE as BatchId)).usable) { delete process.env.BEE_PEER_POSTAGE console.log('BEE_PEER_POSTAGE stamp was found but is not usable') } else { @@ -72,17 +70,19 @@ export async function mochaGlobalSetup(): Promise { if (!process.env.BEE_POSTAGE || !process.env.BEE_PEER_POSTAGE) { console.log('Creating postage stamps...') - const stampsOrder: { kyOptions: KyOptions; env: string }[] = [] + const stampsOrder: { requestOptions: BeeRequestOptions; env: string }[] = [] if (!process.env.BEE_POSTAGE) { - stampsOrder.push({ kyOptions: beeDebugKyOptions, env: 'BEE_POSTAGE' }) + stampsOrder.push({ requestOptions: beeDebugRequestOptions, env: 'BEE_POSTAGE' }) } if (!process.env.BEE_PEER_POSTAGE) { - stampsOrder.push({ kyOptions: beeDebugPeerKyOptions, env: 'BEE_PEER_POSTAGE' }) + stampsOrder.push({ requestOptions: beeDebugPeerRequestOptions, env: 'BEE_PEER_POSTAGE' }) } - const stamps = await Promise.all(stampsOrder.map(async order => createPostageBatch(order.kyOptions, '100', 20))) + const stamps = await Promise.all( + stampsOrder.map(async order => createPostageBatch(order.requestOptions, '100', 20)), + ) for (let i = 0; i < stamps.length; i++) { process.env[stampsOrder[i].env] = stamps[i] @@ -96,7 +96,7 @@ export async function mochaGlobalSetup(): Promise { // eslint-disable-next-line max-depth try { // eslint-disable-next-line max-depth - if (!(await getPostageBatch(stampsOrder[i].kyOptions, stamps[i] as BatchId)).usable) { + if (!(await getPostageBatch(stampsOrder[i].requestOptions, stamps[i] as BatchId)).usable) { allUsable = false break } else { diff --git a/test/unit/assertions.ts b/test/unit/assertions.ts index 6244334e..5f4a2cd1 100644 --- a/test/unit/assertions.ts +++ b/test/unit/assertions.ts @@ -1,8 +1,7 @@ /* eslint-disable */ +import { expect } from 'chai' import { BeeArgumentError, BeeOptions } from '../../src' import { makeBytes } from '../../src/utils/bytes' -import { expect } from 'chai' -import sinon from 'sinon' export function testBatchIdAssertion(executor: (input: unknown) => Promise): void { it('should throw exception for bad BatchId', async function () { @@ -94,33 +93,7 @@ export function testRequestOptionsAssertions( await expect(executor({ retry: {} })).rejectedWith(TypeError) await expect(executor({ retry: [] })).rejectedWith(TypeError) await expect(executor({ retry: -1 })).rejectedWith(BeeArgumentError) - - await expect(executor({ fetch: 'plur' })).rejectedWith(TypeError) - await expect(executor({ fetch: true })).rejectedWith(TypeError) - await expect(executor({ fetch: {} })).rejectedWith(TypeError) - await expect(executor({ fetch: [] })).rejectedWith(TypeError) - await expect(executor({ fetch: -1 })).rejectedWith(TypeError) - await expect(executor({ fetch: 1 })).rejectedWith(TypeError) }) - - if (testFetch) { - it('should use per-call request options instead of instance request options', async function () { - const instanceFetch = sinon.stub() - const instanceMessage = 'instance error' - const instanceError = { message: instanceMessage } - instanceFetch.rejects(instanceError) - await expect(executor({}, { retry: 0, fetch: instanceFetch })).rejectedWith(instanceMessage) - expect(instanceFetch.calledOnce).to.be.true() - - const callFetch = sinon.stub() - const callMessage = 'call error' - const callError = { message: callMessage } - callFetch.rejects(callError) - await expect(executor({ fetch: callFetch }, { retry: 0, fetch: instanceFetch })).rejectedWith(callMessage) - expect(instanceFetch.calledOnce).to.be.true() // The count did not change from last call - expect(callFetch.calledOnce).to.be.true() - }) - } } export function testPostageBatchOptionsAssertions(executor: (input: unknown) => Promise): void { diff --git a/test/unit/bee-class.spec.ts b/test/unit/bee-class.spec.ts index a8536c05..416521e3 100644 --- a/test/unit/bee-class.spec.ts +++ b/test/unit/bee-class.spec.ts @@ -1,16 +1,19 @@ -import { assertAllIsDone, downloadDataMock, fetchFeedUpdateMock, MOCK_SERVER_URL, uploadFileMock } from './nock' +import { fail } from 'assert' +import { expect } from 'chai' import { BatchId, Bee, BeeArgumentError, + BeeRequestOptions, + CHUNK_SIZE, CollectionUploadOptions, PssMessageHandler, ReferenceResponse, - UploadOptions, - RequestOptions, - CHUNK_SIZE, SPAN_SIZE, + UploadOptions, } from '../../src' +import { makeTopicFromString } from '../../src/feed/topic' +import { FeedType } from '../../src/feed/type' import { randomByteArray, testBatchId, @@ -23,31 +26,26 @@ import { testJsonPayload, testJsonStringPayload, } from '../utils' -import { makeTopicFromString } from '../../src/feed/topic' import { testAddressPrefixAssertions, testBatchIdAssertion, testCollectionUploadOptionsAssertions, testDataAssertions, + testEthAddressAssertions, + testFeedTopicAssertions, + testFeedTypeAssertions, testFileDataAssertions, testFileUploadOptionsAssertions, + testMakeSignerAssertions, testPssMessageHandlerAssertions, testPublicKeyAssertions, testReferenceAssertions, + testReferenceOrEnsAssertions, + testRequestOptionsAssertions, testTopicAssertions, testUploadOptionsAssertions, - testFeedTypeAssertions, - testFeedTopicAssertions, - testEthAddressAssertions, - testMakeSignerAssertions, - testRequestOptionsAssertions, - testReferenceOrEnsAssertions, } from './assertions' -import { FeedType } from '../../src/feed/type' -import { isStrictlyObject } from '../../src/utils/type' -import { fail } from 'assert' -import { expect } from 'chai' -import sinon from 'sinon' +import { assertAllIsDone, downloadDataMock, fetchFeedUpdateMock, MOCK_SERVER_URL, uploadFileMock } from './nock' const TOPIC = 'some=very%nice#topic' const HASHED_TOPIC = makeTopicFromString(TOPIC) @@ -86,7 +84,7 @@ describe('Bee class', () => { reference: testJsonHash, } as ReferenceResponse) - const bee = new Bee(MOCK_SERVER_URL, { defaultHeaders }) + const bee = new Bee(MOCK_SERVER_URL, { headers: defaultHeaders }) const reference = await bee.uploadFile(testBatchId, 'hello world', 'nice.txt') expect(reference).to.include({ @@ -123,7 +121,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.uploadData(testBatchId, '', input as RequestOptions) + return bee.uploadData(testBatchId, '', undefined, input as BeeRequestOptions) }) testDataAssertions(async (input: unknown) => { @@ -149,7 +147,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.downloadData(testChunkHash, input as RequestOptions) + return bee.downloadData(testChunkHash, input as BeeRequestOptions) }) it('should accept valid ENS domain', async function () { @@ -195,7 +193,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.downloadReadableData(testChunkHash, input as RequestOptions) + return bee.downloadReadableData(testChunkHash, input as BeeRequestOptions) }) }) @@ -209,7 +207,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.uploadFile(testBatchId, '', undefined, input as RequestOptions) + return bee.uploadFile(testBatchId, '', undefined, undefined, input as BeeRequestOptions) }) testFileDataAssertions(async (input: unknown) => { @@ -241,7 +239,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.downloadFile(testChunkHash, '', input as RequestOptions) + return bee.downloadFile(testChunkHash, '', input as BeeRequestOptions) }) }) @@ -255,7 +253,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.downloadReadableFile(testChunkHash, '', input as RequestOptions) + return bee.downloadReadableFile(testChunkHash, '', input as BeeRequestOptions) }) }) @@ -284,7 +282,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.uploadFiles(testBatchId, files, input as RequestOptions) + return bee.uploadFiles(testBatchId, files, undefined, input as BeeRequestOptions) }) }) @@ -310,7 +308,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.uploadFilesFromDirectory(testBatchId, './test/data', input as RequestOptions) + return bee.uploadFilesFromDirectory(testBatchId, './test/data', undefined, input as BeeRequestOptions) }) it('should throw exception for bad Dir', async function () { @@ -336,7 +334,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.retrieveTag(0, input as RequestOptions) + return bee.retrieveTag(0, input as BeeRequestOptions) }) it('should throw exception for bad Tag', async function () { @@ -370,7 +368,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.deleteTag(0, input as RequestOptions) + return bee.deleteTag(0, input as BeeRequestOptions) }) it('should throw exception for bad Tag', async function () { @@ -404,7 +402,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.getAllTags(input as RequestOptions) + return bee.getAllTags() }) it('should throw exception for bad options', async function () { @@ -462,7 +460,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.pin(testChunkHash, input as RequestOptions) + return bee.pin(testChunkHash, input as BeeRequestOptions) }) testReferenceAssertions(async (input: unknown) => { @@ -476,7 +474,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.unpin(testChunkHash, input as RequestOptions) + return bee.unpin(testChunkHash, input as BeeRequestOptions) }) testReferenceAssertions(async (input: unknown) => { const bee = new Bee(MOCK_SERVER_URL) @@ -489,7 +487,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.getPin(testChunkHash, input as RequestOptions) + return bee.getPin(testChunkHash, input as BeeRequestOptions) }) testReferenceAssertions(async (input: unknown) => { const bee = new Bee(MOCK_SERVER_URL) @@ -502,7 +500,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.reuploadPinnedData(testChunkHash, input as RequestOptions) + return bee.reuploadPinnedData(testChunkHash, input as BeeRequestOptions) }) testReferenceOrEnsAssertions(async (input: unknown) => { @@ -516,7 +514,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.pssSend(testBatchId, 'topic', '123', 'data', '', input as RequestOptions) + return bee.pssSend(testBatchId, 'topic', '123', 'data', '', input as BeeRequestOptions) }) testBatchIdAssertion(async (input: unknown) => { @@ -595,7 +593,13 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.createFeedManifest(testBatchId, 'epoch', testChunkHash, testIdentity.address, input as RequestOptions) + return bee.createFeedManifest( + testBatchId, + 'epoch', + testChunkHash, + testIdentity.address, + input as BeeRequestOptions, + ) }) testBatchIdAssertion(async (input: unknown) => { @@ -627,7 +631,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.makeFeedReader('epoch', testChunkHash, testIdentity.address, input as RequestOptions) + return bee.makeFeedReader('epoch', testChunkHash, testIdentity.address, input as BeeRequestOptions) }, false) testFeedTypeAssertions(async (input: unknown) => { @@ -653,7 +657,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.makeFeedWriter('epoch', testChunkHash, testIdentity.address, input as RequestOptions) + return bee.makeFeedWriter('epoch', testChunkHash, testIdentity.address, input as BeeRequestOptions) }, false) testFeedTypeAssertions(async (input: unknown) => { @@ -679,18 +683,11 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - let opts - - if (isStrictlyObject(input)) { - opts = { - signer: testIdentity.privateKey, - ...input, - } - } else { - opts = input + const opts = { + signer: testIdentity.privateKey, } - return bee.setJsonFeed(testBatchId, 'epoch', '123', opts as RequestOptions) + return bee.setJsonFeed(testBatchId, 'epoch', '123', opts) }) testBatchIdAssertion(async (input: unknown) => { @@ -722,18 +719,11 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - let opts - - if (isStrictlyObject(input)) { - opts = { - signer: testIdentity.privateKey, - ...input, - } - } else { - opts = input + const opts = { + signer: testIdentity.privateKey, } - return bee.getJsonFeed(TOPIC, opts as RequestOptions) + return bee.getJsonFeed(TOPIC, opts) }) it('should fetch with specified address', async function () { @@ -826,7 +816,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.makeSOCReader(testIdentity.privateKey, input as RequestOptions) + return bee.makeSOCReader(testIdentity.privateKey, input as BeeRequestOptions) }, false) testEthAddressAssertions(async (input: unknown) => { @@ -847,7 +837,7 @@ describe('Bee class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new Bee(MOCK_SERVER_URL, beeOptions) - return bee.makeSOCWriter(testIdentity.privateKey, input as RequestOptions) + return bee.makeSOCWriter(testIdentity.privateKey, input as BeeRequestOptions) }, false) testMakeSignerAssertions(async (input: unknown) => { @@ -863,91 +853,4 @@ describe('Bee class', () => { expect(socReader.owner).to.eql(testIdentity.address) }) }) - - describe('hooks', () => { - it('should call with request', async function () { - const requestSpy = sinon.stub() - const responseSpy = sinon.stub() - - const bee = new Bee(MOCK_SERVER_URL, { onRequest: requestSpy, onResponse: responseSpy }) - - const topic = bee.makeFeedTopic('some-topic') - fetchFeedUpdateMock(testIdentity.address, topic).reply(200, { - reference: testJsonHash, - } as ReferenceResponse) - - const feedReader = bee.makeFeedReader('sequence', topic, testIdentity.address) - const feedUpdate = await feedReader.download() - - expect(feedUpdate.reference).to.eql(testJsonHash) - - expect(requestSpy).to.be.calledWithMatch({ - url: `${MOCK_SERVER_URL}feeds/${testIdentity.address}/${topic}?type=sequence`, - method: 'GET', - headers: { accept: 'application/json, text/plain, */*' }, - }) - - expect(responseSpy).to.be.calledWithMatch({ - status: 200, - statusText: '', - headers: { - 'content-type': 'application/json', - }, - request: { - url: `${MOCK_SERVER_URL}feeds/${testIdentity.address}/${topic}?type=sequence`, - method: 'GET', - headers: { accept: 'application/json, text/plain, */*' }, - }, - }) - assertAllIsDone() - }) - - it('should call with request with correct headers', async function () { - const requestSpy = sinon.stub() - const responseSpy = sinon.stub() - const bee = new Bee(MOCK_SERVER_URL, { onRequest: requestSpy, onResponse: responseSpy }) - - uploadFileMock(testBatchId, 'nice.txt', { encrypt: true }).reply(200, { - reference: testJsonHash, - } as ReferenceResponse) - - const reference = await bee.uploadFile(testBatchId, 'hello world', 'nice.txt', { encrypt: true }) - - expect(reference).to.include({ - reference: testJsonHash, - tagUid: 123, - }) - - expect(reference.cid()).to.eql(testJsonCid) - - expect(requestSpy).to.be.calledWithMatch({ - url: `${MOCK_SERVER_URL}bzz?name=nice.txt`, - method: 'POST', - headers: { - accept: 'application/json, text/plain, */*', - 'swarm-encrypt': 'true', - 'swarm-postage-batch-id': testBatchId, - }, - }) - - expect(responseSpy).to.be.calledWithMatch({ - status: 200, - statusText: '', - headers: { - 'content-type': 'application/json', - }, - request: { - url: `${MOCK_SERVER_URL}bzz?name=nice.txt`, - method: 'POST', - headers: { - accept: 'application/json, text/plain, */*', - 'swarm-encrypt': 'true', - 'swarm-postage-batch-id': testBatchId, - }, - }, - }) - - assertAllIsDone() - }) - }) }) diff --git a/test/unit/bee-debug-class.spec.ts b/test/unit/bee-debug-class.spec.ts index 4bf01be4..92afc547 100644 --- a/test/unit/bee-debug-class.spec.ts +++ b/test/unit/bee-debug-class.spec.ts @@ -1,3 +1,14 @@ +import { fail } from 'assert' +import { expect } from 'chai' +import { BatchId, BeeArgumentError, BeeDebug, BeeRequestOptions, CashoutOptions, PostageBatchOptions } from '../../src' +import { testAddress, testBatchId } from '../utils' +import { + testAddressAssertions, + testBatchIdAssertion, + testPostageBatchOptionsAssertions, + testRequestOptionsAssertions, + testTransactionOptionsAssertions, +} from './assertions' import { assertAllIsDone, cashoutLastChequeMock, @@ -6,17 +17,6 @@ import { MOCK_SERVER_URL, withdrawTokensMock, } from './nock' -import { BatchId, BeeArgumentError, BeeDebug, CashoutOptions, PostageBatchOptions, RequestOptions } from '../../src' -import { testAddress, testBatchId } from '../utils' -import { - testAddressAssertions, - testBatchIdAssertion, - testTransactionOptionsAssertions, - testPostageBatchOptionsAssertions, - testRequestOptionsAssertions, -} from './assertions' -import { fail } from 'assert' -import { expect } from 'chai' const TRANSACTION_HASH = '36b7efd913ca4cf880b8eeac5093fa27b0825906c600685b6abdd6566e6cfe8f' const CASHOUT_RESPONSE = { @@ -54,7 +54,7 @@ describe('BeeDebug class', () => { it('should set default headers and use them if specified', async function () { depositTokensMock('10', undefined, { 'X-Awesome-Header': '123' }).reply(201, CASHOUT_RESPONSE) - const bee = new BeeDebug(MOCK_SERVER_URL, { defaultHeaders: { 'X-Awesome-Header': '123' } }) + const bee = new BeeDebug(MOCK_SERVER_URL, { headers: { 'X-Awesome-Header': '123' } }) await expect(bee.depositTokens('10')).eventually.to.eql(TRANSACTION_HASH) assertAllIsDone() @@ -64,7 +64,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.removePeer(testAddress, input as RequestOptions) + return bee.removePeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -78,7 +78,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.pingPeer(testAddress, input as RequestOptions) + return bee.pingPeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -92,7 +92,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getPeerBalance(testAddress, input as RequestOptions) + return bee.getPeerBalance(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -106,7 +106,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getPastDueConsumptionPeerBalance(testAddress, input as RequestOptions) + return bee.getPastDueConsumptionPeerBalance(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -120,7 +120,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getLastChequesForPeer(testAddress, input as RequestOptions) + return bee.getLastChequesForPeer(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -134,7 +134,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getLastCashoutAction(testAddress, input as RequestOptions) + return bee.getLastCashoutAction(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -148,7 +148,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getSettlements(testAddress, input as RequestOptions) + return bee.getSettlements(testAddress, input as BeeRequestOptions) }) testAddressAssertions(async (input: unknown) => { @@ -162,7 +162,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.cashoutLastCheque(testAddress, input as RequestOptions) + return bee.cashoutLastCheque(testAddress, undefined, input as BeeRequestOptions) }) testTransactionOptionsAssertions(async (input: unknown) => { @@ -211,7 +211,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.withdrawTokens('1', '0', input as RequestOptions) + return bee.withdrawTokens('1', '0', input as BeeRequestOptions) }) it('should not pass headers if no gas price is specified', async function () { @@ -266,7 +266,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.depositTokens('1', '0', input as RequestOptions) + return bee.depositTokens('1', '0', input as BeeRequestOptions) }) it('should not pass headers if no gas price is specified', async function () { @@ -316,7 +316,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.retrieveExtendedTag(0, input as RequestOptions) + return bee.retrieveExtendedTag(0, input as BeeRequestOptions) }) it('should throw exception for bad Tag', async function () { @@ -350,7 +350,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getStake(input as RequestOptions) + return bee.getStake(input as BeeRequestOptions) }) }) @@ -359,13 +359,13 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.depositStake(testStakingAmount, input as RequestOptions) + return bee.depositStake(testStakingAmount, undefined, input as BeeRequestOptions) }) testTransactionOptionsAssertions(async (input: unknown) => { const bee = new BeeDebug(MOCK_SERVER_URL) - return bee.depositStake(testStakingAmount, input as RequestOptions) + return bee.depositStake(testStakingAmount, undefined, input as BeeRequestOptions) }) }) @@ -384,7 +384,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.createPostageBatch('10', 17, input as RequestOptions) + return bee.createPostageBatch('10', 17, undefined, input as BeeRequestOptions) }) it('should not pass headers if no gas price is specified', async function () { @@ -443,7 +443,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getPostageBatch(testBatchId, input as RequestOptions) + return bee.getPostageBatch(testBatchId, input as BeeRequestOptions) }) testBatchIdAssertion(async (input: unknown) => { @@ -457,7 +457,7 @@ describe('BeeDebug class', () => { testRequestOptionsAssertions(async (input: unknown, beeOptions) => { const bee = new BeeDebug(MOCK_SERVER_URL, beeOptions) - return bee.getPostageBatchBuckets(testBatchId, input as RequestOptions) + return bee.getPostageBatchBuckets(testBatchId, input as BeeRequestOptions) }) testBatchIdAssertion(async (input: unknown) => { diff --git a/test/unit/utils/http.spec.ts b/test/unit/utils/http.spec.ts index 6d3a9b15..710ecda1 100644 --- a/test/unit/utils/http.spec.ts +++ b/test/unit/utils/http.spec.ts @@ -1,9 +1,8 @@ -import { MOCK_SERVER_URL } from '../nock' -import { http } from '../../../src/utils/http' -import nock from 'nock' -import { BeeNotAJsonError, BeeResponseError } from '../../../src' import { expect } from 'chai' import { expect as jestExpect } from 'expect' +import nock from 'nock' +import { http } from '../../../src/utils/http' +import { MOCK_SERVER_URL } from '../nock' class ShouldHaveFailedError extends Error {} @@ -12,41 +11,33 @@ describe('http', () => { const HTML_RESPONSE = `

Some error!

` nock(MOCK_SERVER_URL).get('/endpoint').reply(200, HTML_RESPONSE) - const kyOptions = { prefixUrl: MOCK_SERVER_URL } + const kyOptions = { baseURL: MOCK_SERVER_URL } - await expect(http(kyOptions, { path: 'endpoint', responseType: 'json', method: 'get' })).rejectedWith( - BeeNotAJsonError, - ) + await expect(http(kyOptions, { url: 'endpoint', responseType: 'json', method: 'get' })).rejectedWith(Error) }) it('should handle non-json response for 404', async function () { const HTML_RESPONSE = `

Some error!

` nock(MOCK_SERVER_URL).get('/endpoint').reply(404, HTML_RESPONSE) - const kyOptions = { prefixUrl: MOCK_SERVER_URL } + const kyOptions = { baseURL: MOCK_SERVER_URL } - await expect(http(kyOptions, { path: 'endpoint', responseType: 'json', method: 'get' })).rejectedWith( - BeeResponseError, - ) + await expect(http(kyOptions, { url: 'endpoint', responseType: 'json', method: 'get' })).rejectedWith(Error) }) it('should give options when thrown error', async function () { nock(MOCK_SERVER_URL).get('/endpoint').reply(400, 'Some error') - const kyOptions = { prefixUrl: MOCK_SERVER_URL } + const kyOptions = { baseURL: MOCK_SERVER_URL } try { - await http(kyOptions, { path: 'endpoint', method: 'get' }) + await http(kyOptions, { url: 'endpoint', method: 'get' }) throw new ShouldHaveFailedError() - } catch (e) { + } catch (e: any) { if (e instanceof ShouldHaveFailedError) { throw e } - if (!(e instanceof BeeResponseError)) { - throw new Error('Expected error to be instance of BeeResponseError!') - } - - expect(e.requestOptions).to.eql({ path: 'endpoint', method: 'get' }) + expect(e.request.path).to.eql({ path: 'endpoint', method: 'get' }) // Testing only partial Response object for the major functionality jestExpect(e.response).toEqual( diff --git a/test/utils.ts b/test/utils.ts index 8e3fbdaa..c59dd85c 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -1,16 +1,20 @@ +import { System } from 'cafe-utility' import { Readable } from 'stream' import { ReadableStream as ReadableStreamPolyfill } from 'web-streams-polyfill' -// @ts-ignore: Needed TS otherwise complains about importing ESM package in CJS even though they are just typings -import type { Options as KyOptions } from 'ky' - -import type { Address, BatchId, BeeGenericResponse, PlainBytesReference, PostageBatch, Reference } from '../src/types' -import { bytesToHex, HexString } from '../src/utils/hex' import { deleteChunkFromLocalStorage } from '../src/modules/debug/chunk' -import { BeeResponseError } from '../src' -import { assertBytes } from '../src/utils/bytes' import * as stamps from '../src/modules/debug/stamps' -import { sleep } from '../src/utils/sleep' +import type { + Address, + BatchId, + BeeGenericResponse, + BeeRequestOptions, + PlainBytesReference, + PostageBatch, + Reference, +} from '../src/types' +import { assertBytes } from '../src/utils/bytes' +import { bytesToHex, HexString } from '../src/utils/hex' declare global { // eslint-disable-next-line @typescript-eslint/no-namespace @@ -178,8 +182,8 @@ export function beeUrl(): string { return process.env.BEE_API_URL || 'http://127.0.0.1:1633' } -export function beeKyOptions(): KyOptions { - return { prefixUrl: beeUrl(), timeout: false } +export function beeKyOptions(): BeeRequestOptions { + return { baseURL: beeUrl(), timeout: false } } /** @@ -189,8 +193,8 @@ export function beePeerUrl(): string { return process.env.BEE_PEER_API_URL || 'http://127.0.0.1:11633' } -export function beePeerKyOptions(): KyOptions { - return { prefixUrl: beePeerUrl(), timeout: false } +export function beePeerKyOptions(): BeeRequestOptions { + return { baseURL: beePeerUrl(), timeout: false } } /** @@ -226,8 +230,8 @@ export function beeDebugUrl(): string { return process.env.BEE_DEBUG_API_URL || 'http://127.0.0.1:1635' } -export function beeDebugKyOptions(): KyOptions { - return { prefixUrl: beeDebugUrl(), timeout: false } +export function beeDebugKyOptions(): BeeRequestOptions { + return { baseURL: beeDebugUrl(), timeout: false } } /** @@ -237,8 +241,8 @@ export function beePeerDebugUrl(): string { return process.env.BEE_PEER_DEBUG_API_URL || 'http://127.0.0.1:11635' } -export function beePeerDebugKyOptions(): KyOptions { - return { prefixUrl: beePeerDebugUrl(), timeout: false } +export function beePeerDebugKyOptions(): BeeRequestOptions { + return { baseURL: beePeerDebugUrl(), timeout: false } } /** @@ -254,9 +258,9 @@ export async function tryDeleteChunkFromLocalStorage(address: string | PlainByte try { await deleteChunkFromLocalStorage(beeDebugKyOptions(), address) - } catch (e) { + } catch (e: any) { // ignore not found errors - if (e instanceof BeeResponseError && e.status === 404) { + if (e?.response?.status === 404) { return } throw e @@ -280,7 +284,7 @@ export function shorten(inputStr: unknown, len = 17): string { } async function timeout(ms: number, message = 'Execution reached timeout!'): Promise { - await sleep(ms) + await System.sleepMillis(ms) throw new Error(message) } @@ -291,7 +295,7 @@ export async function waitForBatchToBeUsable(batchId: string, pollingInterval = let stamp do { - await sleep(pollingInterval) + await System.sleepMillis(pollingInterval) stamp = await stamps.getPostageBatch(beeDebugKyOptions(), batchId as BatchId) } while (!stamp.usable) },