Skip to content

Commit

Permalink
dynamic import of whatwg-fetch to allow environments without it
Browse files Browse the repository at this point in the history
  • Loading branch information
BruceMacD committed Aug 13, 2024
1 parent c03ea59 commit 7b5d0e9
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/browser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as utils from './utils.js'
import { AbortableAsyncIterator, parseJSON, post } from './utils.js'
import 'whatwg-fetch'

import type {
ChatRequest,
Expand Down Expand Up @@ -39,9 +38,24 @@ export class Ollama {
this.config.host = utils.formatHost(config?.host ?? 'http://127.0.0.1:11434')
}

this.fetch = fetch
if (config?.fetch != null) {
this.fetch = config.fetch
this.fetch = config?.fetch || this.getFetch();
}

private getFetch(): Fetch {
if (typeof window !== 'undefined' && window.fetch) {
return window.fetch.bind(window);
}

if (typeof global !== 'undefined' && global.fetch) {
return global.fetch;
}

try {
// Use dynamic import to allow for environments where whatwg-fetch is not available
return require('whatwg-fetch');
} catch (error) {
console.error('Failed to import whatwg-fetch:', error);
throw new Error('Fetch is not available. Please provide a fetch implementation in the config.');
}
}

Expand Down

0 comments on commit 7b5d0e9

Please sign in to comment.