diff --git a/apps/js-sdk/firecrawl/src/global.d.ts b/apps/js-sdk/firecrawl/src/global.d.ts new file mode 100644 index 000000000..bf9177ded --- /dev/null +++ b/apps/js-sdk/firecrawl/src/global.d.ts @@ -0,0 +1,5 @@ +export {}; + +declare global { + const __WEBSOCKET_LOADER__: string; +} \ No newline at end of file diff --git a/apps/js-sdk/firecrawl/src/index.ts b/apps/js-sdk/firecrawl/src/index.ts index 29fabf5d6..c1cc53955 100644 --- a/apps/js-sdk/firecrawl/src/index.ts +++ b/apps/js-sdk/firecrawl/src/index.ts @@ -1,9 +1,16 @@ import axios, { type AxiosResponse, type AxiosRequestHeaders, AxiosError } from "axios"; import type * as zt from "zod"; import { zodToJsonSchema } from "zod-to-json-schema"; -import { WebSocket } from "isows"; +import { WebSocket as IsowsWebSocket } from "isows"; import { TypedEventTarget } from "typescript-event-target"; + +let WebSocket: typeof IsowsWebSocket; + +if (typeof __WEBSOCKET_LOADER__ === 'string') { + WebSocket = new Function('return ' + __WEBSOCKET_LOADER__)(); +} + /** * Configuration interface for FirecrawlApp. * @param apiKey - Optional API key for authentication. @@ -950,6 +957,11 @@ export class CrawlWatcher extends TypedEventTarget { constructor(id: string, app: FirecrawlApp) { super(); this.id = id; + console.log('typeof WebSocket', typeof WebSocket) + // @ts-ignore + if (typeof WebSocket === "function" && WebSocket.prototype.then) { + throw new Error("WebSocket behaves like a Promise, which is unexpected."); + } this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey); this.status = "scraping"; this.data = []; diff --git a/apps/js-sdk/firecrawl/tsup.config.ts b/apps/js-sdk/firecrawl/tsup.config.ts index b3b7e42d5..4d4c80aca 100644 --- a/apps/js-sdk/firecrawl/tsup.config.ts +++ b/apps/js-sdk/firecrawl/tsup.config.ts @@ -6,4 +6,13 @@ export default defineConfig({ dts: true, outDir: "dist", clean: true, + esbuildOptions(options, context) { + options.define = { + __WEBSOCKET_LOADER__: JSON.stringify( + context.format === 'cjs' + ? `const { WebSocket } = require('isows'); WebSocket` + : `import('isows').then(m => m.WebSocket)` + ) + }; + }, }); \ No newline at end of file