diff --git a/mod.ts b/mod.ts index b125024..661ec9d 100644 --- a/mod.ts +++ b/mod.ts @@ -30,6 +30,16 @@ * ); * ``` * + * ## `fetch` API in Node.js + * + * Node.js v18 has a native browser-like fetch interface. Versions + * below are normally using [`node-fetch`](https://github.com/node-fetch/node-fetch) + * to circumvent this issue. + * + * For environments using Node v18 and earlier, Tpy uses the native + * fetch without requiring the package. Environments containing earlier + * versions of Node will require the package. + * * @module */ diff --git a/node/package.json b/node/package.json index f53569e..fb319a8 100644 --- a/node/package.json +++ b/node/package.json @@ -1,6 +1,6 @@ { "name": "tpy", - "version": "v1.0.0-pre-release-4", + "version": "v1.0.0-pre-release-5", "description": "🔑 A strongly typed Pylon API client.", "license": "MIT", "type": "commonjs", @@ -30,14 +30,17 @@ "bugs": { "url": "https://github.com/insyri/tpy/issues" }, - "dependencies": { + "peerDependencies": { "@types/node": "18.11.3", - "discord-api-types": "0.37.14" + "discord-api-types": "0.37.14", + "node-fetch": "3.2.10" + }, + "peerDependenciesMeta": { + "node-fetch": { + "optional": true + } }, "devDependencies": { "typescript": "4.8.4" - }, - "optionalDependencies": { - "node-fetch": "3.2.10" } } diff --git a/src/fetch_polyfill.ts b/src/fetch_polyfill.ts index 420bcd4..4f4bc3d 100644 --- a/src/fetch_polyfill.ts +++ b/src/fetch_polyfill.ts @@ -1,19 +1,13 @@ -import fetch, { - Blob, - blobFrom, - blobFromSync, - File, - fileFrom, - fileFromSync, - FormData, - Headers, - Request, - Response, -} from 'node-fetch'; +// This file is meant to be read by Node.js, Deno stops at line 5. +// If Deno extension enabled, ignore errors. -if (!globalThis.fetch) { - Object.defineProperty(globalThis, 'fetch', fetch); - Object.defineProperty(globalThis, 'Headers', Headers); - Object.defineProperty(globalThis, 'Request', Request); - Object.defineProperty(globalThis, 'Response', Response); +if ( + 'process' in globalThis && // If Node + Number(globalThis.process.version.substring(1, 3)) < 18 +) { + Object.defineProperty( + globalThis, + 'fetch', + require('node-fetch'), + ); } diff --git a/src/tpy.ts b/src/tpy.ts index ec3e90a..4387124 100644 --- a/src/tpy.ts +++ b/src/tpy.ts @@ -12,7 +12,7 @@ import TpyWs from './ws.ts'; import TpyKV from './kv.ts'; import Context from './context.ts'; -if (!Deno) await import('./fetch_polyfill.ts'); +import './fetch_polyfill.ts'; /** * The central entity for interacting with the Pylon API; the entrypoint.