import { createParser } from "eventsource-parser";
import { getTemporaryAuthToken } from "./auth";
import { getConfig } from "./config";
import { buildUrl } from "./function";
import { dispatchRequest } from "./request";
import { ApiError, defaultResponseHandler } from "./response";
import { storageImpl } from "./storage";
export type StreamingConnectionMode = "client" | "server";
/**
* The stream API options. It requires the API input and also
* offers configuration options.
*/
type StreamOptions = {
/**
* The endpoint URL. If not provided, it will be generated from the
* `endpointId` and the `queryParams`.
*/
readonly url?: string;
/**
* The API input payload.
*/
readonly input?: Input;
/**
* The query parameters to be sent with the request.
*/
readonly queryParams?: Record;
/**
* The maximum time interval in milliseconds between stream chunks. Defaults to 15s.
*/
readonly timeout?: number;
/**
* Whether it should auto-upload File-like types to fal's storage
* or not.
*/
readonly autoUpload?: boolean;
/**
* The HTTP method, defaults to `post`;
*/
readonly method?: "get" | "post" | "put" | "delete" | string;
/**
* The content type the client accepts as response.
* By default this is set to `text/event-stream`.
*/
readonly accept?: string;
/**
* The streaming connection mode. This is used to determine
* whether the streaming will be done from the browser itself (client)
* or through your own server, either when running on NodeJS or when
* using a proxy that supports streaming.
*
* It defaults to `server`. Set to `client` if your server proxy doesn't
* support streaming.
*/
readonly connectionMode?: StreamingConnectionMode;
};
const EVENT_STREAM_TIMEOUT = 15 * 1000;
type FalStreamEventType = "data" | "error" | "done";
type EventHandler = (event: T) => void;
/**
* The class representing a streaming response. With t
*/
export class FalStream {
// properties
endpointId: string;
url: string;
options: StreamOptions;
// support for event listeners
private listeners: Map = new Map();
private buffer: Output[] = [];
// local state
private currentData: Output | undefined = undefined;
private lastEventTimestamp = 0;
private streamClosed = false;
private donePromise: Promise