diff --git a/src/core/client.ts b/src/core/client.ts index f707a593..807be506 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -241,6 +241,13 @@ class ApiClient { ) { const apiRoot = options.apiRoot ?? "https://api.telegram.org"; const environment = options.environment ?? "prod"; + + // In an ideal world, `fetch` is independent of the context being called, + // but in a Cloudflare worker, any context other than global throws an error. + // That is why we need to call custom fetch or fetch without context. + const { fetch: customFetch } = options; + const fetchFn = customFetch ?? fetch; + this.options = { apiRoot, environment, @@ -252,7 +259,9 @@ class ApiClient { }, canUseWebhookReply: options.canUseWebhookReply ?? (() => false), sensitiveLogs: options.sensitiveLogs ?? false, - fetch: options.fetch ?? fetch, + fetch: + ((...args: Parameters) => + fetchFn(...args)) as typeof fetch, }; this.fetch = this.options.fetch; if (this.options.apiRoot.endsWith("/")) {