Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(js-sdk): Add CJS-compatible WebSocket loading #1021

Closed
wants to merge 5 commits into from
Closed
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions apps/js-sdk/firecrawl/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
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 { TypedEventTarget } from "typescript-event-target";

/**
Expand Down Expand Up @@ -942,18 +941,39 @@ interface CrawlWatcherEvents {
}

export class CrawlWatcher extends TypedEventTarget<CrawlWatcherEvents> {
private ws: WebSocket;
private ws!: WebSocket;
private initialized: Promise<void>;
public data: FirecrawlDocument<undefined>[];
public status: CrawlStatusResponse["status"];
public id: string;

private static async loadWebSocket() {
try {
if (typeof require !== 'undefined') {
return require('isows').WebSocket;
} else {
const module = await import('isows');
return module.WebSocket;
}
} catch (e) {
throw new FirecrawlError('Failed to load WebSocket implementation', 500);
}
}

constructor(id: string, app: FirecrawlApp) {
super();
this.id = id;
this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey);
this.status = "scraping";
this.data = [];

this.initialized = CrawlWatcher.loadWebSocket()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont think this is good enough, cause ws is not initialized when the constructor is called but later async, so there can be a race condition.

.then((WebSocket) => {
this.ws = new WebSocket(`${app.apiUrl}/v1/crawl/${id}`, app.apiKey);
this.initializeWebSocket();
});
}

private initializeWebSocket() {
type ErrorMessage = {
type: "error",
error: string,
Expand Down Expand Up @@ -1050,6 +1070,8 @@ export class CrawlWatcher extends TypedEventTarget<CrawlWatcherEvents> {
}

close() {
this.ws.close();
this.initialized.then(() => {
this.ws.close();
});
}
}
Loading