@imgly/plugin-autocaption-web 1.69.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/middleware.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/headers.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/response.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/utils.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/retry.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/node_modules/@fal-ai/client/package.json", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/runtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/config.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/request.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/storage.ts", "../../../../node_modules/.pnpm/eventsource-parser@1.1.2/node_modules/eventsource-parser/src/parse.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/auth.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/streaming.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/queue.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/utils/utf8.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/ExtData.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/DecodeError.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/utils/int.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/timestamp.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/ExtensionCodec.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/utils/typedArrays.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/Encoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/encode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/utils/prettyByte.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/Decoder.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/decode.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/utils/stream.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/decodeAsync.ts", "../../../../node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/src/index.ts", "../../../../node_modules/.pnpm/robot3@0.4.1/node_modules/robot3/dist/machine.js", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/realtime.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/client.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/types/common.ts", "../../../../node_modules/.pnpm/@fal-ai+client@1.9.0/libs/client/src/index.ts", "../../src/wordsToSrt.ts", "../../src/fal-ai/createFalClient.ts", "../../src/fal-ai/ElevenLabsScribeV2.ts"],
4
+ "sourcesContent": ["/**\n * A request configuration object.\n *\n * **Note:** This is a simplified version of the `RequestConfig` type from the\n * `fetch` API. It contains only the properties that are relevant for the\n * fal client. It also works around the fact that the `fetch` API `Request`\n * does not support mutability, its clone method has critical limitations\n * to our use case.\n */\nexport type RequestConfig = {\n url: string;\n method: string;\n headers?: Record<string, string | string[]>;\n};\n\nexport type RequestMiddleware = (\n request: RequestConfig,\n) => Promise<RequestConfig>;\n\n/**\n * Setup a execution chain of middleware functions.\n *\n * @param middlewares one or more middleware functions.\n * @returns a middleware function that executes the given middlewares in order.\n */\nexport function withMiddleware(\n ...middlewares: RequestMiddleware[]\n): RequestMiddleware {\n const isDefined = (middleware: RequestMiddleware): boolean =>\n typeof middleware === \"function\";\n\n return async (config: RequestConfig) => {\n let currentConfig = { ...config };\n for (const middleware of middlewares.filter(isDefined)) {\n currentConfig = await middleware(currentConfig);\n }\n return currentConfig;\n };\n}\n\nexport type RequestProxyConfig = {\n targetUrl: string;\n};\n\nexport const TARGET_URL_HEADER = \"x-fal-target-url\";\n\nexport function withProxy(config: RequestProxyConfig): RequestMiddleware {\n const passthrough = (requestConfig: RequestConfig) =>\n Promise.resolve(requestConfig);\n // when running on the server, we don't need to proxy the request\n if (typeof window === \"undefined\") {\n return passthrough;\n }\n // if x-fal-target-url is already set, we skip it\n return (requestConfig) =>\n requestConfig.headers && TARGET_URL_HEADER in requestConfig\n ? passthrough(requestConfig)\n : Promise.resolve({\n ...requestConfig,\n url: config.targetUrl,\n headers: {\n ...(requestConfig.headers || {}),\n [TARGET_URL_HEADER]: requestConfig.url,\n },\n });\n}\n", "/**\n * Minimum allowed request timeout in seconds.\n * Matches the Python client's MIN_REQUEST_TIMEOUT_SECONDS.\n */\nexport const MIN_REQUEST_TIMEOUT_SECONDS = 1;\n\n/**\n * Header name for server-side request timeout.\n */\nexport const REQUEST_TIMEOUT_HEADER = \"x-fal-request-timeout\";\n\n/**\n * Header name for timeout type (user vs infrastructure).\n */\nexport const REQUEST_TIMEOUT_TYPE_HEADER = \"x-fal-request-timeout-type\";\n\n/**\n * Header name for queue priority.\n */\nexport const QUEUE_PRIORITY_HEADER = \"x-fal-queue-priority\";\n\n/**\n * Header name for runner hint.\n */\nexport const RUNNER_HINT_HEADER = \"x-fal-runner-hint\";\n\n/**\n * Validates the timeout and returns the header value as a string.\n * Throws an error if the timeout is invalid.\n *\n * @param timeout - The timeout value in seconds (must be > MIN_REQUEST_TIMEOUT_SECONDS)\n * @returns The timeout as a string suitable for the header value\n * @throws Error if timeout is not a valid number or is <= MIN_REQUEST_TIMEOUT_SECONDS\n */\nexport function validateTimeoutHeader(timeout: number): string {\n if (typeof timeout !== \"number\" || isNaN(timeout)) {\n throw new Error(`Timeout must be a number, got ${timeout}`);\n }\n\n if (timeout <= MIN_REQUEST_TIMEOUT_SECONDS) {\n throw new Error(\n `Timeout must be greater than ${MIN_REQUEST_TIMEOUT_SECONDS} seconds`,\n );\n }\n\n return timeout.toString();\n}\n\n/**\n * Creates headers object with the timeout header if timeout is provided.\n * Returns an empty object if timeout is undefined.\n *\n * @param timeout - Optional timeout value in seconds\n * @returns Headers object with REQUEST_TIMEOUT_HEADER if timeout is provided\n */\nexport function buildTimeoutHeaders(timeout?: number): Record<string, string> {\n if (timeout === undefined) {\n return {};\n }\n\n return {\n [REQUEST_TIMEOUT_HEADER]: validateTimeoutHeader(timeout),\n };\n}\n", "import { RequiredConfig } from \"./config\";\nimport { REQUEST_TIMEOUT_TYPE_HEADER } from \"./headers\";\nimport { Result, ValidationErrorInfo } from \"./types/common\";\n\nexport type ResponseHandler<Output> = (response: Response) => Promise<Output>;\n\nconst REQUEST_ID_HEADER = \"x-fal-request-id\";\n\nexport type ResponseHandlerCreator<Output> = (\n config: RequiredConfig,\n) => ResponseHandler<Output>;\n\ntype ApiErrorArgs = {\n message: string;\n status: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body?: any;\n requestId?: string;\n /**\n * The type of timeout that occurred. If \"user\", this was a user-specified\n * timeout via startTimeout and should NOT be retried.\n */\n timeoutType?: string;\n};\n\nexport class ApiError<Body> extends Error {\n public readonly status: number;\n public readonly body: Body;\n public readonly requestId: string;\n public readonly timeoutType?: string;\n constructor({ message, status, body, requestId, timeoutType }: ApiErrorArgs) {\n super(message);\n this.name = \"ApiError\";\n this.status = status;\n this.body = body;\n this.requestId = requestId || \"\";\n this.timeoutType = timeoutType;\n }\n\n /**\n * Returns true if this error was caused by a user-specified timeout\n * (via startTimeout parameter). These errors should NOT be retried.\n */\n get isUserTimeout(): boolean {\n return this.status === 504 && this.timeoutType === \"user\";\n }\n}\n\ntype ValidationErrorBody = {\n detail: ValidationErrorInfo[];\n};\n\nexport class ValidationError extends ApiError<ValidationErrorBody> {\n constructor(args: ApiErrorArgs) {\n super(args);\n this.name = \"ValidationError\";\n }\n\n get fieldErrors(): ValidationErrorInfo[] {\n // NOTE: this is a hack to support both FastAPI/Pydantic errors\n // and some custom 422 errors that might not be in the Pydantic format.\n if (typeof this.body.detail === \"string\") {\n return [\n {\n loc: [\"body\"],\n msg: this.body.detail,\n type: \"value_error\",\n },\n ];\n }\n return this.body.detail || [];\n }\n\n getFieldErrors(field: string): ValidationErrorInfo[] {\n return this.fieldErrors.filter(\n (error) => error.loc[error.loc.length - 1] === field,\n );\n }\n}\n\nexport async function defaultResponseHandler<Output>(\n response: Response,\n): Promise<Output> {\n const { status, statusText } = response;\n const contentType = response.headers.get(\"Content-Type\") ?? \"\";\n const requestId = response.headers.get(REQUEST_ID_HEADER) || undefined;\n const timeoutType =\n response.headers.get(REQUEST_TIMEOUT_TYPE_HEADER) || undefined;\n if (!response.ok) {\n if (contentType.includes(\"application/json\")) {\n const body = await response.json();\n const ErrorType = status === 422 ? ValidationError : ApiError;\n throw new ErrorType({\n message: body.message || statusText,\n status,\n body,\n requestId,\n timeoutType,\n });\n }\n throw new ApiError({\n message: `HTTP ${status}: ${statusText}`,\n status,\n requestId,\n timeoutType,\n });\n }\n if (contentType.includes(\"application/json\")) {\n return response.json() as Promise<Output>;\n }\n if (contentType.includes(\"text/html\")) {\n return response.text() as Promise<Output>;\n }\n if (contentType.includes(\"application/octet-stream\")) {\n return response.arrayBuffer() as Promise<Output>;\n }\n // TODO convert to either number or bool automatically\n return response.text() as Promise<Output>;\n}\n\nexport async function resultResponseHandler<Output>(\n response: Response,\n): Promise<Result<Output>> {\n const data = await defaultResponseHandler<Output>(response);\n return {\n data,\n requestId: response.headers.get(REQUEST_ID_HEADER) || \"\",\n } satisfies Result<Output>;\n}\n", "export function ensureEndpointIdFormat(id: string): string {\n const parts = id.split(\"/\");\n if (parts.length > 1) {\n return id;\n }\n const [, appOwner, appId] = /^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(id) || [];\n if (appOwner && appId) {\n return `${appOwner}/${appId}`;\n }\n throw new Error(\n `Invalid app id: ${id}. Must be in the format <appOwner>/<appId>`,\n );\n}\n\nconst ENDPOINT_NAMESPACES = [\"workflows\", \"comfy\"] as const;\n\ntype EndpointNamespace = (typeof ENDPOINT_NAMESPACES)[number];\n\nexport type EndpointId = {\n readonly owner: string;\n readonly alias: string;\n readonly path?: string;\n readonly namespace?: EndpointNamespace;\n};\n\nexport function parseEndpointId(id: string): EndpointId {\n const normalizedId = ensureEndpointIdFormat(id);\n const parts = normalizedId.split(\"/\");\n if (ENDPOINT_NAMESPACES.includes(parts[0] as any)) {\n return {\n owner: parts[1],\n alias: parts[2],\n path: parts.slice(3).join(\"/\") || undefined,\n namespace: parts[0] as EndpointNamespace,\n };\n }\n return {\n owner: parts[0],\n alias: parts[1],\n path: parts.slice(2).join(\"/\") || undefined,\n };\n}\n\nexport function isValidUrl(url: string) {\n try {\n const { host } = new URL(url);\n return /(fal\\.(ai|run))$/.test(host);\n } catch (_) {\n return false;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function throttle<T extends (...args: any[]) => any>(\n func: T,\n limit: number,\n leading = false,\n): (...funcArgs: Parameters<T>) => ReturnType<T> | void {\n let lastFunc: NodeJS.Timeout | null;\n let lastRan: number;\n\n return (...args: Parameters<T>): ReturnType<T> | void => {\n if (!lastRan && leading) {\n func(...args);\n lastRan = Date.now();\n } else {\n if (lastFunc) {\n clearTimeout(lastFunc);\n }\n\n lastFunc = setTimeout(\n () => {\n if (Date.now() - lastRan >= limit) {\n func(...args);\n lastRan = Date.now();\n }\n },\n limit - (Date.now() - lastRan),\n );\n }\n };\n}\n\nlet isRunningInReact: boolean | undefined;\n\n/**\n * Not really the most optimal way to detect if we're running in React,\n * but the idea here is that we can support multiple rendering engines\n * (starting with React), with all their peculiarities, without having\n * to add a dependency or creating custom integrations (e.g. custom hooks).\n *\n * Yes, a bit of magic to make things works out-of-the-box.\n * @returns `true` if running in React, `false` otherwise.\n */\nexport function isReact() {\n if (isRunningInReact === undefined) {\n const stack = new Error().stack;\n isRunningInReact =\n !!stack &&\n (stack.includes(\"node_modules/react-dom/\") ||\n stack.includes(\"node_modules/next/\"));\n }\n return isRunningInReact;\n}\n\n/**\n * Check if a value is a plain object.\n * @param value - The value to check.\n * @returns `true` if the value is a plain object, `false` otherwise.\n */\nexport function isPlainObject(value: any): boolean {\n return !!value && Object.getPrototypeOf(value) === Object.prototype;\n}\n\n/**\n * Utility function to sleep for a given number of milliseconds\n */\nexport async function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n", "import { ApiError } from \"./response\";\nimport { sleep } from \"./utils\";\n\nexport type RetryOptions = {\n maxRetries: number;\n baseDelay: number;\n maxDelay: number;\n backoffMultiplier: number;\n retryableStatusCodes: number[];\n enableJitter: boolean;\n};\n\n/**\n * Base retryable status codes for most requests\n */\nexport const DEFAULT_RETRYABLE_STATUS_CODES = [429, 502, 503, 504];\n\nexport const DEFAULT_RETRY_OPTIONS: RetryOptions = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n retryableStatusCodes: DEFAULT_RETRYABLE_STATUS_CODES,\n enableJitter: true,\n};\n\n/**\n * Determines if an error is retryable based on the status code.\n * User-specified timeouts (504 with X-Fal-Request-Timeout-Type: user) are NOT retryable.\n */\nexport function isRetryableError(\n error: any,\n retryableStatusCodes: number[],\n): boolean {\n if (!(error instanceof ApiError)) {\n return false;\n }\n // User-specified timeouts should NOT be retried\n if (error.isUserTimeout) {\n return false;\n }\n return retryableStatusCodes.includes(error.status);\n}\n\n/**\n * Calculates the backoff delay for a given attempt using exponential backoff\n */\nexport function calculateBackoffDelay(\n attempt: number,\n baseDelay: number,\n maxDelay: number,\n backoffMultiplier: number,\n enableJitter: boolean,\n): number {\n const exponentialDelay = Math.min(\n baseDelay * Math.pow(backoffMultiplier, attempt),\n maxDelay,\n );\n\n if (enableJitter) {\n // Add ±25% jitter to prevent thundering herd\n const jitter = 0.25 * exponentialDelay * (Math.random() * 2 - 1);\n return Math.max(0, exponentialDelay + jitter);\n }\n\n return exponentialDelay;\n}\n\n/**\n * Retry metrics for tracking retry attempts\n */\nexport interface RetryMetrics {\n totalAttempts: number;\n totalDelay: number;\n lastError?: any;\n}\n\n/**\n * Executes an operation with retry logic and returns both result and metrics\n */\nexport async function executeWithRetry<T>(\n operation: () => Promise<T>,\n options: RetryOptions,\n onRetry?: (attempt: number, error: any, delay: number) => void,\n): Promise<{ result: T; metrics: RetryMetrics }> {\n const metrics: RetryMetrics = {\n totalAttempts: 0,\n totalDelay: 0,\n };\n\n let lastError: any;\n\n for (let attempt = 0; attempt <= options.maxRetries; attempt++) {\n metrics.totalAttempts++;\n\n try {\n const result = await operation();\n return { result, metrics };\n } catch (error) {\n lastError = error;\n metrics.lastError = error;\n\n if (\n attempt === options.maxRetries ||\n !isRetryableError(error, options.retryableStatusCodes)\n ) {\n throw error;\n }\n\n const delay = calculateBackoffDelay(\n attempt,\n options.baseDelay,\n options.maxDelay,\n options.backoffMultiplier,\n options.enableJitter,\n );\n\n metrics.totalDelay += delay;\n\n if (onRetry) {\n onRetry(attempt + 1, error, delay);\n }\n\n await sleep(delay);\n }\n }\n\n throw lastError;\n}\n", "{\n \"name\": \"@fal-ai/client\",\n \"description\": \"The fal.ai client for JavaScript and TypeScript\",\n \"version\": \"1.9.0\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/fal-ai/fal-js.git\",\n \"directory\": \"libs/client\"\n },\n \"keywords\": [\n \"fal\",\n \"client\",\n \"ai\",\n \"ml\",\n \"typescript\"\n ],\n \"exports\": {\n \".\": \"./src/index.js\",\n \"./endpoints\": \"./src/types/endpoints.js\"\n },\n \"typesVersions\": {\n \"*\": {\n \"endpoints\": [\n \"src/types/endpoints.d.ts\"\n ]\n }\n },\n \"main\": \"./src/index.js\",\n \"types\": \"./src/index.d.ts\",\n \"dependencies\": {\n \"@msgpack/msgpack\": \"^3.0.0-beta2\",\n \"eventsource-parser\": \"^1.1.2\",\n \"robot3\": \"^0.4.1\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"type\": \"commonjs\"\n}\n", "/* eslint-disable @typescript-eslint/no-var-requires */\n\nexport function isBrowser(): boolean {\n return (\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n );\n}\n\nlet memoizedUserAgent: string | null = null;\n\nexport function getUserAgent(): string {\n if (memoizedUserAgent !== null) {\n return memoizedUserAgent;\n }\n const packageInfo = require(\"../package.json\");\n memoizedUserAgent = `${packageInfo.name}/${packageInfo.version}`;\n return memoizedUserAgent;\n}\n", "import {\n withMiddleware,\n withProxy,\n type RequestMiddleware,\n} from \"./middleware\";\nimport type { ResponseHandler } from \"./response\";\nimport { defaultResponseHandler } from \"./response\";\nimport { DEFAULT_RETRY_OPTIONS, type RetryOptions } from \"./retry\";\nimport { isBrowser } from \"./runtime\";\n\nexport type CredentialsResolver = () => string | undefined;\n\ntype FetchType = typeof fetch;\n\nexport function resolveDefaultFetch(): FetchType {\n if (typeof fetch === \"undefined\") {\n throw new Error(\n \"Your environment does not support fetch. Please provide your own fetch implementation.\",\n );\n }\n return fetch;\n}\n\nexport type Config = {\n /**\n * The credentials to use for the fal client. When using the\n * client in the browser, it's recommended to use a proxy server to avoid\n * exposing the credentials in the client's environment.\n *\n * By default it tries to use the `FAL_KEY` environment variable, when\n * `process.env` is defined.\n *\n * @see https://fal.ai/docs/model-endpoints/server-side\n * @see #suppressLocalCredentialsWarning\n */\n credentials?: undefined | string | CredentialsResolver;\n /**\n * Suppresses the warning when the fal credentials are exposed in the\n * browser's environment. Make sure you understand the security implications\n * before enabling this option.\n */\n suppressLocalCredentialsWarning?: boolean;\n /**\n * The URL of the proxy server to use for the client requests. The proxy\n * server should forward the requests to the fal api.\n */\n proxyUrl?: string;\n /**\n * The request middleware to use for the client requests. By default it\n * doesn't apply any middleware.\n */\n requestMiddleware?: RequestMiddleware;\n /**\n * The response handler to use for the client requests. By default it uses\n * a built-in response handler that returns the JSON response.\n */\n responseHandler?: ResponseHandler<any>;\n /**\n * The fetch implementation to use for the client requests. By default it uses\n * the global `fetch` function.\n */\n fetch?: FetchType;\n /**\n * Retry configuration for handling transient errors like rate limiting and server errors.\n * When not specified, a default retry configuration is used.\n */\n retry?: Partial<RetryOptions>;\n};\n\nexport type RequiredConfig = Required<Config>;\n\n/**\n * Checks if the required FAL environment variables are set.\n *\n * @returns `true` if the required environment variables are set,\n * `false` otherwise.\n */\nfunction hasEnvVariables(): boolean {\n return (\n typeof process !== \"undefined\" &&\n process.env &&\n (typeof process.env.FAL_KEY !== \"undefined\" ||\n (typeof process.env.FAL_KEY_ID !== \"undefined\" &&\n typeof process.env.FAL_KEY_SECRET !== \"undefined\"))\n );\n}\n\nexport const credentialsFromEnv: CredentialsResolver = () => {\n if (!hasEnvVariables()) {\n return undefined;\n }\n\n if (typeof process.env.FAL_KEY !== \"undefined\") {\n return process.env.FAL_KEY;\n }\n\n return process.env.FAL_KEY_ID\n ? `${process.env.FAL_KEY_ID}:${process.env.FAL_KEY_SECRET}`\n : undefined;\n};\n\nconst DEFAULT_CONFIG: Partial<Config> = {\n credentials: credentialsFromEnv,\n suppressLocalCredentialsWarning: false,\n requestMiddleware: (request) => Promise.resolve(request),\n responseHandler: defaultResponseHandler,\n retry: DEFAULT_RETRY_OPTIONS,\n};\n\n/**\n * Configures the fal client.\n *\n * @param config the new configuration.\n */\nexport function createConfig(config: Config): RequiredConfig {\n let configuration = {\n ...DEFAULT_CONFIG,\n ...config,\n fetch: config.fetch ?? resolveDefaultFetch(),\n // Merge retry configuration with defaults\n retry: {\n ...DEFAULT_RETRY_OPTIONS,\n ...(config.retry || {}),\n },\n } as RequiredConfig;\n if (config.proxyUrl) {\n configuration = {\n ...configuration,\n requestMiddleware: withMiddleware(\n configuration.requestMiddleware,\n withProxy({ targetUrl: config.proxyUrl }),\n ),\n };\n }\n const { credentials: resolveCredentials, suppressLocalCredentialsWarning } =\n configuration;\n const credentials =\n typeof resolveCredentials === \"function\"\n ? resolveCredentials()\n : resolveCredentials;\n if (isBrowser() && credentials && !suppressLocalCredentialsWarning) {\n console.warn(\n \"The fal credentials are exposed in the browser's environment. \" +\n \"That's not recommended for production use cases.\",\n );\n }\n return configuration;\n}\n\n/**\n * @returns the URL of the fal REST api endpoint.\n */\nexport function getRestApiUrl(): string {\n return \"https://rest.alpha.fal.ai\";\n}\n", "import { RequiredConfig } from \"./config\";\nimport { ResponseHandler } from \"./response\";\nimport {\n calculateBackoffDelay,\n isRetryableError,\n type RetryOptions,\n} from \"./retry\";\nimport { getUserAgent, isBrowser } from \"./runtime\";\nimport { RunOptions, UrlOptions } from \"./types/common\";\nimport { ensureEndpointIdFormat, isValidUrl, sleep } from \"./utils\";\n\nconst isCloudflareWorkers =\n typeof navigator !== \"undefined\" &&\n navigator?.userAgent === \"Cloudflare-Workers\";\n\ntype RequestOptions = {\n responseHandler?: ResponseHandler<any>;\n /**\n * Retry configuration for this specific request.\n * If not specified, uses the default retry configuration from the client config.\n */\n retry?: Partial<RetryOptions>;\n};\n\ntype RequestParams<Input = any> = {\n method?: string;\n targetUrl: string;\n input?: Input;\n config: RequiredConfig;\n options?: RequestOptions & RequestInit;\n headers?: Record<string, string>;\n};\n\nexport async function dispatchRequest<Input, Output>(\n params: RequestParams<Input>,\n): Promise<Output> {\n const { targetUrl, input, config, options = {} } = params;\n const {\n credentials: credentialsValue,\n requestMiddleware,\n responseHandler,\n fetch,\n } = config;\n\n const retryOptions: RetryOptions = {\n ...config.retry,\n ...(options.retry || {}),\n } as RetryOptions;\n\n const executeRequest = async (): Promise<Output> => {\n const userAgent = isBrowser() ? {} : { \"User-Agent\": getUserAgent() };\n const credentials =\n typeof credentialsValue === \"function\"\n ? credentialsValue()\n : credentialsValue;\n\n const { method, url, headers } = await requestMiddleware({\n method: (params.method ?? options.method ?? \"post\").toUpperCase(),\n url: targetUrl,\n headers: params.headers,\n });\n const authHeader = credentials\n ? { Authorization: `Key ${credentials}` }\n : {};\n const requestHeaders = {\n ...authHeader,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n ...userAgent,\n ...(headers ?? {}),\n } as HeadersInit;\n\n const {\n responseHandler: customResponseHandler,\n retry: _,\n ...requestInit\n } = options;\n const response = await fetch(url, {\n ...requestInit,\n method,\n headers: {\n ...requestHeaders,\n ...(requestInit.headers ?? {}),\n },\n ...(!isCloudflareWorkers && { mode: \"cors\" }),\n signal: options.signal,\n body:\n method.toLowerCase() !== \"get\" && input\n ? JSON.stringify(input)\n : undefined,\n });\n const handleResponse = customResponseHandler ?? responseHandler;\n return await handleResponse(response);\n };\n\n let lastError: any;\n for (let attempt = 0; attempt <= retryOptions.maxRetries; attempt++) {\n try {\n return await executeRequest();\n } catch (error) {\n lastError = error;\n\n const shouldNotRetry =\n attempt === retryOptions.maxRetries ||\n !isRetryableError(error, retryOptions.retryableStatusCodes) ||\n options.signal?.aborted;\n if (shouldNotRetry) {\n throw error;\n }\n\n const delay = calculateBackoffDelay(\n attempt,\n retryOptions.baseDelay,\n retryOptions.maxDelay,\n retryOptions.backoffMultiplier,\n retryOptions.enableJitter,\n );\n\n await sleep(delay);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Builds the final url to run the function based on its `id` or alias and\n * a the options from `RunOptions<Input>`.\n *\n * @private\n * @param id the function id or alias\n * @param options the run options\n * @returns the final url to run the function\n */\nexport function buildUrl<Input>(\n id: string,\n options: RunOptions<Input> & UrlOptions = {},\n): string {\n const method = (options.method ?? \"post\").toLowerCase();\n const path = (options.path ?? \"\").replace(/^\\//, \"\").replace(/\\/{2,}/, \"/\");\n const input = options.input;\n const params = {\n ...(options.query || {}),\n ...(method === \"get\" ? input : {}),\n };\n\n const queryParams =\n Object.keys(params).length > 0\n ? `?${new URLSearchParams(params).toString()}`\n : \"\";\n\n // if a fal url is passed, just use it\n if (isValidUrl(id)) {\n const url = id.endsWith(\"/\") ? id : `${id}/`;\n return `${url}${path}${queryParams}`;\n }\n\n const appId = ensureEndpointIdFormat(id);\n const subdomain = options.subdomain ? `${options.subdomain}.` : \"\";\n const url = `https://${subdomain}fal.run/${appId}/${path}`;\n return `${url.replace(/\\/$/, \"\")}${queryParams}`;\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { isPlainObject } from \"./utils\";\n\ntype ObjectExpiration =\n | \"never\"\n | \"immediate\"\n | \"1h\"\n | \"1d\"\n | \"7d\"\n | \"30d\"\n | \"1y\"\n | number;\n\nexport const OBJECT_LIFECYCYLE_PREFERENCE_HEADER =\n \"x-fal-object-lifecycle-preference\";\n\n/**\n * Configuration for object lifecycle and storage behavior.\n */\nexport interface StorageSettings {\n /**\n * The expiration time for the stored files (images, videos, etc.). You can specify one of the enumerated values or a number of seconds.\n */\n expiresIn: ObjectExpiration;\n}\n\ntype UploadLifecycleConfig = {\n /**\n * Duration in seconds before the object expires and is deleted.\n * Set to a large value (e.g., 31536000000) for effectively unlimited storage.\n *\n * Common values:\n * - 604800: 7 days\n * - 2592000: 30 days\n * - 31536000: 1 year\n */\n expiration_duration_seconds?: number;\n\n /**\n * Whether to allow I/O storage for this object.\n * @default undefined (uses account default)\n */\n allow_io_storage?: boolean;\n};\n\nconst EXPIRATION_VALUES: Record<ObjectExpiration, number | undefined> = {\n never: 3153600000, // 100 years\n immediate: undefined,\n \"1h\": 3600,\n \"1d\": 86400,\n \"7d\": 604800,\n \"30d\": 2592000,\n \"1y\": 31536000,\n};\n\n/**\n * Converts an `StorageSettings` to the expiration duration in seconds.\n * @param lifecycle the lifecycle preference\n * @returns the expiration duration in seconds, or undefined if not applicable\n */\nexport function getExpirationDurationSeconds(\n lifecycle: StorageSettings,\n): number | undefined {\n const { expiresIn } = lifecycle;\n return typeof expiresIn === \"number\"\n ? expiresIn\n : EXPIRATION_VALUES[expiresIn];\n}\n\n/**\n * Builds the headers for the Object Lifecycle preference to be used in API requests.\n * This is used by the queue and run APIs to control the lifecycle of generated objects.\n *\n * @param lifecycle the lifecycle preference\n * @returns a record with the `X-Fal-Object-Lifecycle-Preference` header\n */\nexport function buildObjectLifecycleHeaders(\n lifecycle: StorageSettings | undefined,\n): Record<string, string> {\n if (!lifecycle) {\n return {};\n }\n const expirationDurationSeconds = getExpirationDurationSeconds(lifecycle);\n if (expirationDurationSeconds === undefined) {\n return {};\n }\n return {\n [OBJECT_LIFECYCYLE_PREFERENCE_HEADER]: JSON.stringify({\n expiration_duration_seconds: expirationDurationSeconds,\n }),\n };\n}\n\n/**\n * Options for uploading a file.\n */\nexport type UploadOptions = {\n /**\n * Custom lifecycle configuration for the uploaded file.\n * This object will be sent as the X-Fal-Object-Lifecycle header.\n */\n lifecycle?: StorageSettings;\n};\n\n/**\n * File support for the client. This interface establishes the contract for\n * uploading files to the server and transforming the input to replace file\n * objects with URLs.\n */\nexport interface StorageClient {\n /**\n * Upload a file to the server. Returns the URL of the uploaded file.\n * @param file the file to upload\n * @param options optional parameters, such as lifecycle configuration\n * @returns the URL of the uploaded file\n */\n upload: (file: Blob, options?: UploadOptions) => Promise<string>;\n\n /**\n * Transform the input to replace file objects with URLs. This is used\n * to transform the input before sending it to the server and ensures\n * that the server receives URLs instead of file objects.\n *\n * @param input the input to transform.\n * @returns the transformed input.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: (input: Record<string, any>) => Promise<Record<string, any>>;\n}\n\ntype InitiateUploadResult = {\n file_url: string;\n upload_url: string;\n};\n\ntype InitiateUploadData = {\n file_name: string;\n content_type: string | null;\n};\n\n/**\n * Get the file extension from the content type. This is used to generate\n * a file name if the file name is not provided.\n *\n * @param contentType the content type of the file.\n * @returns the file extension or `bin` if the content type is not recognized.\n */\nfunction getExtensionFromContentType(contentType: string): string {\n const [, fileType] = contentType.split(\"/\");\n return fileType.split(/[-;]/)[0] ?? \"bin\";\n}\n\n/**\n * Initiate the upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n lifecycle?: StorageSettings,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n const headers: Record<string, string> = {};\n if (lifecycle) {\n const lifecycleConfig: UploadLifecycleConfig = {\n expiration_duration_seconds: getExpirationDurationSeconds(lifecycle),\n allow_io_storage: lifecycle.expiresIn !== \"immediate\",\n };\n headers[\"X-Fal-Object-Lifecycle\"] = JSON.stringify(lifecycleConfig);\n }\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n // NOTE: We want to test V3 without making it the default at the API level\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n headers,\n });\n}\n\n/**\n * Initiate the multipart upload of a file to the server. This returns the URL to upload\n * the file to and the URL of the file once it is uploaded.\n */\nasync function initiateMultipartUpload(\n file: Blob,\n config: RequiredConfig,\n contentType: string,\n lifecycle?: StorageSettings,\n): Promise<InitiateUploadResult> {\n const filename =\n file.name || `${Date.now()}.${getExtensionFromContentType(contentType)}`;\n\n const headers: Record<string, string> = {};\n if (lifecycle) {\n headers[\"X-Fal-Object-Lifecycle\"] = JSON.stringify(lifecycle);\n }\n\n return await dispatchRequest<InitiateUploadData, InitiateUploadResult>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,\n input: {\n content_type: contentType,\n file_name: filename,\n },\n config,\n headers,\n });\n}\n\ntype MultipartObject = {\n partNumber: number;\n etag: string;\n};\n\nasync function partUploadRetries(\n uploadUrl: string,\n chunk: Blob,\n config: RequiredConfig,\n tries = 3,\n): Promise<MultipartObject> {\n if (tries === 0) {\n throw new Error(\"Part upload failed, retries exhausted\");\n }\n\n const { fetch, responseHandler } = config;\n\n try {\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: chunk,\n });\n\n return (await responseHandler(response)) as MultipartObject;\n } catch (error) {\n return await partUploadRetries(uploadUrl, chunk, config, tries - 1);\n }\n}\n\nasync function multipartUpload(\n file: Blob,\n config: RequiredConfig,\n lifecycle?: StorageSettings,\n): Promise<string> {\n const { fetch, responseHandler } = config;\n const contentType = file.type || \"application/octet-stream\";\n const { upload_url: uploadUrl, file_url: url } =\n await initiateMultipartUpload(file, config, contentType, lifecycle);\n\n // Break the file into 10MB chunks\n const chunkSize = 10 * 1024 * 1024;\n const chunks = Math.ceil(file.size / chunkSize);\n\n const parsedUrl = new URL(uploadUrl);\n\n const responses: MultipartObject[] = [];\n\n for (let i = 0; i < chunks; i++) {\n const start = i * chunkSize;\n const end = Math.min(start + chunkSize, file.size);\n\n const chunk = file.slice(start, end);\n\n const partNumber = i + 1;\n // {uploadUrl}/{part_number}?uploadUrlParams=...\n const partUploadUrl = `${parsedUrl.origin}${parsedUrl.pathname}/${partNumber}${parsedUrl.search}`;\n\n responses.push(await partUploadRetries(partUploadUrl, chunk, config));\n }\n\n // Complete the upload\n const completeUrl = `${parsedUrl.origin}${parsedUrl.pathname}/complete${parsedUrl.search}`;\n const response = await fetch(completeUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n parts: responses.map((mpart) => ({\n partNumber: mpart.partNumber,\n etag: mpart.etag,\n })),\n }),\n });\n await responseHandler(response);\n\n return url;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype KeyValuePair = [string, any];\n\ntype StorageClientDependencies = {\n config: RequiredConfig;\n};\n\nexport function createStorageClient({\n config,\n}: StorageClientDependencies): StorageClient {\n const ref: StorageClient = {\n upload: async (file: Blob, options?: UploadOptions) => {\n const lifecycle = options?.lifecycle;\n\n // Check for 90+ MB file size to do multipart upload\n if (file.size > 90 * 1024 * 1024) {\n return await multipartUpload(file, config, lifecycle);\n }\n\n const contentType = file.type || \"application/octet-stream\";\n\n const { fetch, responseHandler } = config;\n const { upload_url: uploadUrl, file_url: url } = await initiateUpload(\n file,\n config,\n contentType,\n lifecycle,\n );\n const response = await fetch(uploadUrl, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": file.type || \"application/octet-stream\",\n },\n });\n await responseHandler(response);\n return url;\n },\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n transformInput: async (input: any): Promise<any> => {\n if (Array.isArray(input)) {\n return Promise.all(input.map((item) => ref.transformInput(item)));\n } else if (input instanceof Blob) {\n return await ref.upload(input);\n } else if (isPlainObject(input)) {\n const inputObject = input as Record<string, any>;\n const promises = Object.entries(inputObject).map(\n async ([key, value]): Promise<KeyValuePair> => {\n return [key, await ref.transformInput(value)];\n },\n );\n const results = await Promise.all(promises);\n return Object.fromEntries(results);\n }\n // Return the input as is if it's neither an object nor a file/blob/data URI\n return input;\n },\n };\n return ref;\n}\n", "/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n *\n * Based on code from the {@link https://github.com/EventSource/eventsource | EventSource module},\n * which is licensed under the MIT license. And copyrighted the EventSource GitHub organisation.\n */\nimport type {EventSourceParseCallback, EventSourceParser} from './types.js'\n\n/**\n * Creates a new EventSource parser.\n *\n * @param onParse - Callback to invoke when a new event is parsed, or a new reconnection interval\n * has been sent from the server\n *\n * @returns A new EventSource parser, with `parse` and `reset` methods.\n * @public\n */\nexport function createParser(onParse: EventSourceParseCallback): EventSourceParser {\n // Processing state\n let isFirstChunk: boolean\n let buffer: string\n let startingPosition: number\n let startingFieldLength: number\n\n // Event state\n let eventId: string | undefined\n let eventName: string | undefined\n let data: string\n\n reset()\n return {feed, reset}\n\n function reset(): void {\n isFirstChunk = true\n buffer = ''\n startingPosition = 0\n startingFieldLength = -1\n\n eventId = undefined\n eventName = undefined\n data = ''\n }\n\n function feed(chunk: string): void {\n buffer = buffer ? buffer + chunk : chunk\n\n // Strip any UTF8 byte order mark (BOM) at the start of the stream.\n // Note that we do not strip any non - UTF8 BOM, as eventsource streams are\n // always decoded as UTF8 as per the specification.\n if (isFirstChunk && hasBom(buffer)) {\n buffer = buffer.slice(BOM.length)\n }\n\n isFirstChunk = false\n\n // Set up chunk-specific processing state\n const length = buffer.length\n let position = 0\n let discardTrailingNewline = false\n\n // Read the current buffer byte by byte\n while (position < length) {\n // EventSource allows for carriage return + line feed, which means we\n // need to ignore a linefeed character if the previous character was a\n // carriage return\n // @todo refactor to reduce nesting, consider checking previous byte?\n // @todo but consider multiple chunks etc\n if (discardTrailingNewline) {\n if (buffer[position] === '\\n') {\n ++position\n }\n discardTrailingNewline = false\n }\n\n let lineLength = -1\n let fieldLength = startingFieldLength\n let character: string\n\n for (let index = startingPosition; lineLength < 0 && index < length; ++index) {\n character = buffer[index]\n if (character === ':' && fieldLength < 0) {\n fieldLength = index - position\n } else if (character === '\\r') {\n discardTrailingNewline = true\n lineLength = index - position\n } else if (character === '\\n') {\n lineLength = index - position\n }\n }\n\n if (lineLength < 0) {\n startingPosition = length - position\n startingFieldLength = fieldLength\n break\n } else {\n startingPosition = 0\n startingFieldLength = -1\n }\n\n parseEventStreamLine(buffer, position, fieldLength, lineLength)\n\n position += lineLength + 1\n }\n\n if (position === length) {\n // If we consumed the entire buffer to read the event, reset the buffer\n buffer = ''\n } else if (position > 0) {\n // If there are bytes left to process, set the buffer to the unprocessed\n // portion of the buffer only\n buffer = buffer.slice(position)\n }\n }\n\n function parseEventStreamLine(\n lineBuffer: string,\n index: number,\n fieldLength: number,\n lineLength: number,\n ) {\n if (lineLength === 0) {\n // We reached the last line of this event\n if (data.length > 0) {\n onParse({\n type: 'event',\n id: eventId,\n event: eventName || undefined,\n data: data.slice(0, -1), // remove trailing newline\n })\n\n data = ''\n eventId = undefined\n }\n eventName = undefined\n return\n }\n\n const noValue = fieldLength < 0\n const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength))\n let step = 0\n\n if (noValue) {\n step = lineLength\n } else if (lineBuffer[index + fieldLength + 1] === ' ') {\n step = fieldLength + 2\n } else {\n step = fieldLength + 1\n }\n\n const position = index + step\n const valueLength = lineLength - step\n const value = lineBuffer.slice(position, position + valueLength).toString()\n\n if (field === 'data') {\n data += value ? `${value}\\n` : '\\n'\n } else if (field === 'event') {\n eventName = value\n } else if (field === 'id' && !value.includes('\\u0000')) {\n eventId = value\n } else if (field === 'retry') {\n const retry = parseInt(value, 10)\n if (!Number.isNaN(retry)) {\n onParse({type: 'reconnect-interval', value: retry})\n }\n }\n }\n}\n\nconst BOM = [239, 187, 191]\n\nfunction hasBom(buffer: string) {\n return BOM.every((charCode: number, index: number) => buffer.charCodeAt(index) === charCode)\n}\n", "import { getRestApiUrl, RequiredConfig } from \"./config\";\nimport { dispatchRequest } from \"./request\";\nimport { parseEndpointId } from \"./utils\";\n\n/**\n * A function that provides a temporary authentication token.\n * @param app - The app/endpoint identifier\n * @returns A promise that resolves to the token string\n */\nexport type TokenProvider = (app: string) => Promise<string>;\n\nexport const TOKEN_EXPIRATION_SECONDS = 120;\n\n/**\n * Get a token to connect to the realtime endpoint.\n */\nexport async function getTemporaryAuthToken(\n app: string,\n config: RequiredConfig,\n): Promise<string> {\n const appId = parseEndpointId(app);\n const token: string | object = await dispatchRequest<any, string>({\n method: \"POST\",\n targetUrl: `${getRestApiUrl()}/tokens/`,\n config,\n input: {\n allowed_apps: [appId.alias],\n token_expiration: TOKEN_EXPIRATION_SECONDS,\n },\n });\n // keep this in case the response was wrapped (old versions of the proxy do that)\n // should be safe to remove in the future\n if (typeof token !== \"string\" && token[\"detail\"]) {\n return token[\"detail\"];\n }\n return token;\n}\n", "import { createParser } from \"eventsource-parser\";\nimport { type TokenProvider, getTemporaryAuthToken } from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { ApiError, defaultResponseHandler } from \"./response\";\nimport { type StorageClient } from \"./storage\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\n\nexport type StreamingConnectionMode = \"client\" | \"server\";\n\nconst CONTENT_TYPE_EVENT_STREAM = \"text/event-stream\";\n\n/**\n * The stream API options. It requires the API input and also\n * offers configuration options.\n */\nexport type StreamOptions<Input> = {\n /**\n * The endpoint URL. If not provided, it will be generated from the\n * `endpointId` and the `queryParams`.\n */\n readonly url?: string;\n\n /**\n * The API input payload.\n */\n readonly input?: Input;\n\n /**\n * The query parameters to be sent with the request.\n */\n readonly queryParams?: Record<string, string>;\n\n /**\n * The maximum time interval in milliseconds between stream chunks. Defaults to 15s.\n */\n readonly timeout?: number;\n\n /**\n * Whether it should auto-upload File-like types to fal's storage\n * or not.\n */\n readonly autoUpload?: boolean;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The content type the client accepts as response.\n * By default this is set to `text/event-stream`.\n */\n readonly accept?: string;\n\n /**\n * The streaming connection mode. This is used to determine\n * whether the streaming will be done from the browser itself (client)\n * or through your own server, either when running on NodeJS or when\n * using a proxy that supports streaming.\n *\n * It defaults to `server`. Set to `client` if your server proxy doesn't\n * support streaming.\n */\n readonly connectionMode?: StreamingConnectionMode;\n\n /**\n * The signal to abort the request.\n */\n readonly signal?: AbortSignal;\n\n /**\n * A custom token provider function. Only used when `connectionMode` is `\"client\"`.\n * When provided, this function will be used to fetch authentication tokens\n * instead of the default internal token fetching mechanism.\n */\n readonly tokenProvider?: TokenProvider;\n};\n\nconst EVENT_STREAM_TIMEOUT = 15 * 1000;\n\ntype FalStreamEventType = \"data\" | \"error\" | \"done\";\n\ntype EventHandler<T = any> = (event: T) => void;\n\n/**\n * The class representing a streaming response. With t\n */\nexport class FalStream<Input, Output> {\n // properties\n config: RequiredConfig;\n endpointId: string;\n url: string;\n options: StreamOptions<Input>;\n\n // support for event listeners\n private listeners: Map<FalStreamEventType, EventHandler[]> = new Map();\n private buffer: Output[] = [];\n\n // local state\n private currentData: Output | undefined = undefined;\n private lastEventTimestamp = 0;\n private streamClosed = false;\n private _requestId: string | null = null;\n private donePromise: Promise<Output>;\n\n private abortController = new AbortController();\n\n constructor(\n endpointId: string,\n config: RequiredConfig,\n options: StreamOptions<Input>,\n ) {\n this.endpointId = endpointId;\n this.config = config;\n this.url =\n options.url ??\n buildUrl(endpointId, {\n path: \"/stream\",\n query: options.queryParams,\n });\n this.options = options;\n this.donePromise = new Promise<Output>((resolve, reject) => {\n if (this.streamClosed) {\n reject(\n new ApiError({\n message: \"Streaming connection is already closed.\",\n status: 400,\n body: undefined,\n requestId: this._requestId || undefined,\n }),\n );\n }\n this.signal.addEventListener(\"abort\", () => {\n resolve(this.currentData ?? ({} as Output));\n });\n this.on(\"done\", (data) => {\n this.streamClosed = true;\n resolve(data);\n });\n this.on(\"error\", (error) => {\n this.streamClosed = true;\n reject(error);\n });\n });\n // if a abort signal was passed, sync it with the internal one\n if (options.signal) {\n options.signal.addEventListener(\"abort\", () => {\n this.abortController.abort();\n });\n }\n\n // start the streaming request\n this.start().catch(this.handleError);\n }\n\n private start = async () => {\n const { endpointId, options } = this;\n const {\n input,\n method = \"post\",\n connectionMode = \"server\",\n tokenProvider,\n } = options;\n try {\n if (connectionMode === \"client\") {\n // if we are in the browser, we need to get a temporary token\n // to authenticate the request\n const fetchToken = tokenProvider\n ? () => tokenProvider(endpointId)\n : () => {\n console.warn(\n \"[fal.stream] Using the default token provider is deprecated. \" +\n 'Please provide a `tokenProvider` function when using `connectionMode: \"client\"`. ' +\n \"See https://docs.fal.ai/fal-client/authentication for more information.\",\n );\n return getTemporaryAuthToken(endpointId, this.config);\n };\n\n const token = await fetchToken();\n const { fetch } = this.config;\n const parsedUrl = new URL(this.url);\n parsedUrl.searchParams.set(\"fal_jwt_token\", token);\n const response = await fetch(parsedUrl.toString(), {\n method: method.toUpperCase(),\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n \"content-type\": \"application/json\",\n },\n body: input && method !== \"get\" ? JSON.stringify(input) : undefined,\n signal: this.abortController.signal,\n });\n this._requestId = response.headers.get(\"x-fal-request-id\");\n return await this.handleResponse(response);\n }\n return await dispatchRequest({\n method: method.toUpperCase(),\n targetUrl: this.url,\n input,\n config: this.config,\n options: {\n headers: {\n accept: options.accept ?? CONTENT_TYPE_EVENT_STREAM,\n },\n responseHandler: async (response) => {\n this._requestId = response.headers.get(\"x-fal-request-id\");\n return await this.handleResponse(response);\n },\n signal: this.abortController.signal,\n },\n });\n } catch (error) {\n this.handleError(error);\n }\n };\n\n private handleResponse = async (response: Response) => {\n if (!response.ok) {\n try {\n // we know the response failed, call the response handler\n // so the exception gets converted to ApiError correctly\n await defaultResponseHandler(response);\n } catch (error) {\n this.emit(\"error\", error);\n }\n return;\n }\n\n const body = response.body;\n if (!body) {\n this.emit(\n \"error\",\n new ApiError({\n message: \"Response body is empty.\",\n status: 400,\n body: undefined,\n requestId: this._requestId || undefined,\n }),\n );\n return;\n }\n\n const isEventStream = (\n response.headers.get(\"content-type\") ?? \"\"\n ).startsWith(CONTENT_TYPE_EVENT_STREAM);\n // any response that is not a text/event-stream will be handled as a binary stream\n if (!isEventStream) {\n const reader = body.getReader();\n const emitRawChunk = () => {\n reader.read().then(({ done, value }) => {\n if (done) {\n this.emit(\"done\", this.currentData);\n return;\n }\n this.buffer.push(value as Output);\n this.currentData = value as Output;\n this.emit(\"data\", value);\n emitRawChunk();\n });\n };\n emitRawChunk();\n return;\n }\n\n const decoder = new TextDecoder(\"utf-8\");\n const reader = response.body.getReader();\n\n const parser = createParser((event) => {\n if (event.type === \"event\") {\n const data = event.data;\n\n try {\n const parsedData = JSON.parse(data);\n this.buffer.push(parsedData);\n this.currentData = parsedData;\n this.emit(\"data\", parsedData);\n\n // also emit 'message'for backwards compatibility\n this.emit(\"message\" as any, parsedData);\n } catch (e) {\n this.emit(\"error\", e);\n }\n }\n });\n\n const timeout = this.options.timeout ?? EVENT_STREAM_TIMEOUT;\n\n const readPartialResponse = async () => {\n const { value, done } = await reader.read();\n this.lastEventTimestamp = Date.now();\n\n parser.feed(decoder.decode(value));\n\n if (Date.now() - this.lastEventTimestamp > timeout) {\n this.emit(\n \"error\",\n new ApiError({\n message: `Event stream timed out after ${(timeout / 1000).toFixed(0)} seconds with no messages.`,\n status: 408,\n requestId: this._requestId || undefined,\n }),\n );\n }\n\n if (!done) {\n readPartialResponse().catch(this.handleError);\n } else {\n this.emit(\"done\", this.currentData);\n }\n };\n\n readPartialResponse().catch(this.handleError);\n return;\n };\n\n private handleError = (error: any) => {\n // In case AbortError is thrown but the signal is marked as aborted\n // it means the user called abort() and we should not emit an error\n // as it's expected behavior\n // See note on: https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort\n if (error.name === \"AbortError\" || this.signal.aborted) {\n return;\n }\n const apiError =\n error instanceof ApiError\n ? error\n : new ApiError({\n message: error.message ?? \"An unknown error occurred\",\n status: 500,\n requestId: this._requestId || undefined,\n });\n this.emit(\"error\", apiError);\n return;\n };\n\n public on = (type: FalStreamEventType, listener: EventHandler) => {\n if (!this.listeners.has(type)) {\n this.listeners.set(type, []);\n }\n this.listeners.get(type)?.push(listener);\n };\n\n private emit = (type: FalStreamEventType, event: any) => {\n const listeners = this.listeners.get(type) || [];\n for (const listener of listeners) {\n listener(event);\n }\n };\n\n async *[Symbol.asyncIterator]() {\n let running = true;\n const stopAsyncIterator = () => (running = false);\n this.on(\"error\", stopAsyncIterator);\n this.on(\"done\", stopAsyncIterator);\n while (running || this.buffer.length > 0) {\n const data = this.buffer.shift();\n if (data) {\n yield data;\n }\n\n // the short timeout ensures the while loop doesn't block other\n // frames getting executed concurrently\n await new Promise((resolve) => setTimeout(resolve, 16));\n }\n }\n\n /**\n * Gets a reference to the `Promise` that indicates whether the streaming\n * is done or not. Developers should always call this in their apps to ensure\n * the request is over.\n *\n * An alternative to this, is to use `on('done')` in case your application\n * architecture works best with event listeners.\n *\n * @returns the promise that resolves when the request is done.\n */\n public done = async () => this.donePromise;\n\n /**\n * Aborts the streaming request.\n *\n * **Note:** This method is noop in case the request is already done.\n *\n * @param reason optional cause for aborting the request.\n */\n public abort = (reason?: string | Error) => {\n if (!this.streamClosed) {\n this.abortController.abort(reason);\n }\n };\n\n /**\n * Gets the `AbortSignal` instance that can be used to listen for abort events.\n *\n * **Note:** this signal is internal to the `FalStream` instance. If you pass your\n * own abort signal, the `FalStream` will listen to it and abort it appropriately.\n *\n * @returns the `AbortSignal` instance.\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n public get signal() {\n return this.abortController.signal;\n }\n\n /**\n * Gets the request id of the streaming request.\n *\n * @returns the request id.\n */\n public get requestId() {\n return this._requestId;\n }\n}\n\n/**\n * The streaming client interface.\n */\nexport interface StreamingClient {\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ): Promise<FalStream<InputType<Id>, OutputType<Id>>>;\n}\n\ntype StreamingClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport function createStreamingClient({\n config,\n storage,\n}: StreamingClientDependencies): StreamingClient {\n return {\n async stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return new FalStream<InputType<Id>, OutputType<Id>>(endpointId, config, {\n ...options,\n input: input as InputType<Id>,\n });\n },\n };\n}\n", "import { RequiredConfig } from \"./config\";\nimport {\n buildTimeoutHeaders,\n QUEUE_PRIORITY_HEADER,\n RUNNER_HINT_HEADER,\n} from \"./headers\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport { DEFAULT_RETRYABLE_STATUS_CODES, RetryOptions } from \"./retry\";\nimport { buildObjectLifecycleHeaders, StorageClient } from \"./storage\";\nimport { FalStream, StreamingConnectionMode } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport {\n CompletedQueueStatus,\n InQueueQueueStatus,\n QueueStatus,\n RequestLog,\n Result,\n RunOptions,\n} from \"./types/common\";\nimport { parseEndpointId } from \"./utils\";\n\nexport type QueuePriority = \"low\" | \"normal\";\nexport type QueueStatusSubscriptionOptions = QueueStatusOptions &\n QueueModeOptions &\n Omit<QueueCommonSubscribeOptions, \"onEnqueue\" | \"webhookUrl\">;\n\ntype TimeoutId = ReturnType<typeof setTimeout> | undefined;\n\nconst DEFAULT_POLL_INTERVAL = 500;\n\ntype QueueModeOptions =\n | {\n mode?: \"polling\";\n /**\n * The interval (in milliseconds) at which to poll for updates.\n * If not provided, a default value of `500` will be used.\n *\n * This value is ignored if `mode` is set to `streaming`.\n */\n pollInterval?: number;\n }\n | {\n mode: \"streaming\";\n\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n };\n\ntype QueueCommonSubscribeOptions = {\n /**\n * The mode to use for subscribing to updates. It defaults to `polling`.\n * You can also use client-side streaming by setting it to `streaming`.\n *\n * **Note:** Streaming is currently experimental and once stable, it will\n * be the default mode.\n *\n * @see pollInterval\n */\n mode?: \"polling\" | \"streaming\";\n\n /**\n * Callback function that is called when a request is enqueued.\n * @param requestId - The unique identifier for the enqueued request.\n */\n onEnqueue?: (requestId: string) => void;\n\n /**\n * Callback function that is called when the status of the queue changes.\n * @param status - The current status of the queue.\n */\n onQueueUpdate?: (status: QueueStatus) => void;\n\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n\n /**\n * The timeout (in milliseconds) for the request. If the request is not\n * completed within this time, the subscription will be cancelled.\n *\n * Keep in mind that although the client resolves the function on a timeout,\n * and will try to cancel the request on the server, the server might not be\n * able to cancel the request if it's already running.\n *\n * Note: currently, the timeout is not enforced and the default is `undefined`.\n * This behavior might change in the future.\n */\n timeout?: number;\n\n /**\n * Server-side request timeout in seconds. Limits total time spent waiting\n * before processing starts (includes queue wait, retries, and routing).\n * Does not apply once the application begins processing.\n *\n * This will be sent as the `x-fal-request-timeout` header.\n */\n startTimeout?: number;\n\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * This will be sent as the `x-fal-queue-priority` header.\n *\n * @see QueuePriority\n */\n priority?: QueuePriority;\n\n /**\n * Additional HTTP headers to include in the submit request.\n * Note: `priority`, `hint`, `startTimeout`, and `objectLifecycle` will override the following headers:\n * - `x-fal-queue-priority`\n * - `x-fal-runner-hint`\n * - `x-fal-request-timeout`\n * - `x-fal-object-lifecycle-preference`\n */\n headers?: Record<string, string>;\n};\n\n/**\n * Options for subscribing to the request queue.\n */\nexport type QueueSubscribeOptions = QueueCommonSubscribeOptions &\n QueueModeOptions;\n\n/**\n * Options for submitting a request to the queue.\n */\nexport type SubmitOptions<Input> = RunOptions<Input> & {\n /**\n * The URL to send a webhook notification to when the request is completed.\n * @see WebHookResponse\n */\n webhookUrl?: string;\n\n /**\n * The priority of the request. It defaults to `normal`.\n * This will be sent as the `x-fal-queue-priority` header.\n *\n * @see QueuePriority\n */\n priority?: QueuePriority;\n\n /**\n * A hint for the runner to use when processing the request.\n * This will be sent as the `x-fal-runner-hint` header.\n */\n hint?: string;\n\n /**\n * Server-side request timeout in seconds. Limits total time spent waiting\n * before processing starts (includes queue wait, retries, and routing).\n * Does not apply once the application begins processing.\n *\n * This will be sent as the `x-fal-request-timeout` header.\n */\n startTimeout?: number;\n\n /**\n * Additional HTTP headers to include in the submit request.\n *\n * Note: `priority`, `hint`, `startTimeout`, and `objectLifecycle` will override the following headers:\n * - `x-fal-queue-priority`\n * - `x-fal-runner-hint`\n * - `x-fal-request-timeout`\n * - `x-fal-object-lifecycle-preference`\n */\n headers?: Record<string, string>;\n};\n\ntype BaseQueueOptions = {\n /**\n * The unique identifier for the enqueued request.\n */\n requestId: string;\n\n /**\n * The signal to abort the request.\n */\n abortSignal?: AbortSignal;\n};\n\nexport type QueueStatusOptions = BaseQueueOptions & {\n /**\n * If `true`, the response will include the logs for the request.\n * Defaults to `false`.\n */\n logs?: boolean;\n};\n\nexport type QueueStatusStreamOptions = QueueStatusOptions & {\n /**\n * The connection mode to use for streaming updates. It defaults to `server`.\n * Set to `client` if your server proxy doesn't support streaming.\n */\n connectionMode?: StreamingConnectionMode;\n};\n\n// Queue operations benefit from more aggressive retry policies\nconst QUEUE_RETRY_CONFIG: Partial<RetryOptions> = {\n maxRetries: 3,\n baseDelay: 1000,\n maxDelay: 60000,\n retryableStatusCodes: DEFAULT_RETRYABLE_STATUS_CODES,\n};\n\n// Status checking can be retried more aggressively since it's read-only\nconst QUEUE_STATUS_RETRY_CONFIG: Partial<RetryOptions> = {\n maxRetries: 5,\n baseDelay: 1000,\n maxDelay: 30000,\n retryableStatusCodes: [...DEFAULT_RETRYABLE_STATUS_CODES, 500],\n};\n\n/**\n * Represents a request queue with methods for submitting requests,\n * checking their status, retrieving results, and subscribing to updates.\n */\nexport interface QueueClient {\n /**\n * Submits a request to the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of enqueuing the request.\n */\n submit<Id extends EndpointType>(\n endpointId: Id,\n options: SubmitOptions<InputType<Id>>,\n ): Promise<InQueueQueueStatus>;\n\n /**\n * Retrieves the status of a specific request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the status of the request.\n */\n status(endpointId: string, options: QueueStatusOptions): Promise<QueueStatus>;\n\n /**\n * Subscribes to updates for a specific request in the queue using HTTP streaming events.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns The streaming object that can be used to listen for updates.\n */\n streamStatus(\n endpointId: string,\n options: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>>;\n\n /**\n * Subscribes to updates for a specific request in the queue using polling or streaming.\n * See `options.mode` for more details.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the final status of the request.\n */\n subscribeToStatus(\n endpointId: string,\n options: QueueStatusSubscriptionOptions,\n ): Promise<CompletedQueueStatus>;\n\n /**\n * Retrieves the result of a specific request from the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request is run.\n * @returns A promise that resolves to the result of the request.\n */\n result<Id extends EndpointType>(\n endpointId: Id,\n options: BaseQueueOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Cancels a request in the queue.\n *\n * @param endpointId - The ID of the function web endpoint.\n * @param options - Options to configure how the request\n * is run and how updates are received.\n * @returns A promise that resolves once the request is cancelled.\n * @throws {Error} If the request cannot be cancelled.\n */\n cancel(endpointId: string, options: BaseQueueOptions): Promise<void>;\n}\n\ntype QueueClientDependencies = {\n config: RequiredConfig;\n storage: StorageClient;\n};\n\nexport const createQueueClient = ({\n config,\n storage,\n}: QueueClientDependencies): QueueClient => {\n const ref: QueueClient = {\n async submit<Input>(\n endpointId: string,\n options: SubmitOptions<Input>,\n ): Promise<InQueueQueueStatus> {\n const {\n webhookUrl,\n priority,\n hint,\n startTimeout,\n headers,\n storageSettings,\n ...runOptions\n } = options;\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n const extraHeaders = Object.fromEntries(\n Object.entries(headers ?? {}).map(([key, value]) => [\n key.toLowerCase(),\n value,\n ]),\n );\n return dispatchRequest<Input, InQueueQueueStatus>({\n method: options.method,\n targetUrl: buildUrl(endpointId, {\n ...runOptions,\n subdomain: \"queue\",\n query: webhookUrl ? { fal_webhook: webhookUrl } : undefined,\n }),\n headers: {\n ...extraHeaders,\n ...buildObjectLifecycleHeaders(storageSettings),\n [QUEUE_PRIORITY_HEADER]: priority ?? \"normal\",\n ...(hint && { [RUNNER_HINT_HEADER]: hint }),\n ...buildTimeoutHeaders(startTimeout),\n },\n input: input as Input,\n config,\n options: {\n signal: options.abortSignal,\n retry: QUEUE_RETRY_CONFIG,\n },\n });\n },\n async status(\n endpointId: string,\n { requestId, logs = false, abortSignal }: QueueStatusOptions,\n ): Promise<QueueStatus> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, QueueStatus>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n query: { logs: logs ? \"1\" : \"0\" },\n path: `/requests/${requestId}/status`,\n }),\n config,\n options: {\n signal: abortSignal,\n retry: QUEUE_STATUS_RETRY_CONFIG,\n },\n });\n },\n\n async streamStatus(\n endpointId: string,\n { requestId, logs = false, connectionMode }: QueueStatusStreamOptions,\n ): Promise<FalStream<unknown, QueueStatus>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n\n const queryParams = {\n logs: logs ? \"1\" : \"0\",\n };\n\n const url = buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/status/stream`,\n query: queryParams,\n });\n\n return new FalStream<unknown, QueueStatus>(endpointId, config, {\n url,\n method: \"get\",\n connectionMode,\n queryParams,\n });\n },\n\n async subscribeToStatus(\n endpointId,\n options,\n ): Promise<CompletedQueueStatus> {\n const requestId = options.requestId;\n const timeout = options.timeout;\n let timeoutId: TimeoutId = undefined;\n\n const handleCancelError = () => {\n // Ignore errors as the client will follow through with the timeout\n // regardless of the server response. In case cancelation fails, we\n // still want to reject the promise and consider the client call canceled.\n };\n if (options.mode === \"streaming\") {\n const status = await ref.streamStatus(endpointId, {\n requestId,\n logs: options.logs,\n connectionMode:\n \"connectionMode\" in options\n ? (options.connectionMode as StreamingConnectionMode)\n : undefined,\n });\n const logs: RequestLog[] = [];\n if (timeout) {\n timeoutId = setTimeout(() => {\n status.abort();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n // TODO this error cannot bubble up to the user since it's thrown in\n // a closure in the global scope due to setTimeout behavior.\n // User will get a platform error instead. We should find a way to\n // make this behavior aligned with polling.\n throw new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n );\n }, timeout);\n }\n status.on(\"data\", (data: QueueStatus) => {\n if (options.onQueueUpdate) {\n // accumulate logs to match previous polling behavior\n if (\n \"logs\" in data &&\n Array.isArray(data.logs) &&\n data.logs.length > 0\n ) {\n logs.push(...data.logs);\n }\n options.onQueueUpdate(\"logs\" in data ? { ...data, logs } : data);\n }\n });\n const doneStatus = await status.done();\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n return doneStatus as CompletedQueueStatus;\n }\n // default to polling until status streaming is stable and faster\n return new Promise<CompletedQueueStatus>((resolve, reject) => {\n let pollingTimeoutId: TimeoutId;\n // type resolution isn't great in this case, so check for its presence\n // and and type so the typechecker behaves as expected\n const pollInterval =\n \"pollInterval\" in options && typeof options.pollInterval === \"number\"\n ? (options.pollInterval ?? DEFAULT_POLL_INTERVAL)\n : DEFAULT_POLL_INTERVAL;\n\n const clearScheduledTasks = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (pollingTimeoutId) {\n clearTimeout(pollingTimeoutId);\n }\n };\n if (timeout) {\n timeoutId = setTimeout(() => {\n clearScheduledTasks();\n ref.cancel(endpointId, { requestId }).catch(handleCancelError);\n reject(\n new Error(\n `Client timed out waiting for the request to complete after ${timeout}ms`,\n ),\n );\n }, timeout);\n }\n const poll = async () => {\n try {\n const requestStatus = await ref.status(endpointId, {\n requestId,\n logs: options.logs ?? false,\n abortSignal: options.abortSignal,\n });\n if (options.onQueueUpdate) {\n options.onQueueUpdate(requestStatus);\n }\n if (requestStatus.status === \"COMPLETED\") {\n clearScheduledTasks();\n resolve(requestStatus);\n return;\n }\n pollingTimeoutId = setTimeout(poll, pollInterval);\n } catch (error) {\n clearScheduledTasks();\n reject(error);\n }\n };\n poll().catch(reject);\n });\n },\n\n async result<Output>(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<Result<Output>> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n return dispatchRequest<unknown, Result<Output>>({\n method: \"get\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}`,\n }),\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: abortSignal,\n retry: QUEUE_RETRY_CONFIG,\n },\n });\n },\n\n async cancel(\n endpointId: string,\n { requestId, abortSignal }: BaseQueueOptions,\n ): Promise<void> {\n const appId = parseEndpointId(endpointId);\n const prefix = appId.namespace ? `${appId.namespace}/` : \"\";\n await dispatchRequest<unknown, void>({\n method: \"put\",\n targetUrl: buildUrl(`${prefix}${appId.owner}/${appId.alias}`, {\n subdomain: \"queue\",\n path: `/requests/${requestId}/cancel`,\n }),\n config,\n options: {\n signal: abortSignal,\n },\n });\n },\n };\n return ref;\n};\n", "export function utf8Count(str: string): number {\n const strLength = str.length;\n\n let byteLength = 0;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n byteLength++;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n byteLength += 2;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n byteLength += 3;\n } else {\n // 4-byte\n byteLength += 4;\n }\n }\n }\n return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n const strLength = str.length;\n let offset = outputOffset;\n let pos = 0;\n while (pos < strLength) {\n let value = str.charCodeAt(pos++);\n\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n output[offset++] = value;\n continue;\n } else if ((value & 0xfffff800) === 0) {\n // 2-bytes\n output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n } else {\n // handle surrogate pair\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < strLength) {\n const extra = str.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n }\n\n if ((value & 0xffff0000) === 0) {\n // 3-byte\n output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n } else {\n // 4-byte\n output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n }\n }\n\n output[offset++] = (value & 0x3f) | 0x80;\n }\n}\n\n// TextEncoder and TextDecoder are standardized in whatwg encoding:\n// https://encoding.spec.whatwg.org/\n// and available in all the modern browsers:\n// https://caniuse.com/textencoder\n// They are available in Node.js since v12 LTS as well:\n// https://nodejs.org/api/globals.html#textencoder\n\nconst sharedTextEncoder = new TextEncoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/encode-string.ts` for details.\nconst TEXT_ENCODER_THRESHOLD = 50;\n\nexport function utf8EncodeTE(str: string, output: Uint8Array, outputOffset: number): void {\n sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport function utf8Encode(str: string, output: Uint8Array, outputOffset: number): void {\n if (str.length > TEXT_ENCODER_THRESHOLD) {\n utf8EncodeTE(str, output, outputOffset);\n } else {\n utf8EncodeJs(str, output, outputOffset);\n }\n}\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n let offset = inputOffset;\n const end = offset + byteLength;\n\n const units: Array<number> = [];\n let result = \"\";\n while (offset < end) {\n const byte1 = bytes[offset++]!;\n if ((byte1 & 0x80) === 0) {\n // 1 byte\n units.push(byte1);\n } else if ((byte1 & 0xe0) === 0xc0) {\n // 2 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 6) | byte2);\n } else if ((byte1 & 0xf0) === 0xe0) {\n // 3 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n } else if ((byte1 & 0xf8) === 0xf0) {\n // 4 bytes\n const byte2 = bytes[offset++]! & 0x3f;\n const byte3 = bytes[offset++]! & 0x3f;\n const byte4 = bytes[offset++]! & 0x3f;\n let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (unit > 0xffff) {\n unit -= 0x10000;\n units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n unit = 0xdc00 | (unit & 0x3ff);\n }\n units.push(unit);\n } else {\n units.push(byte1);\n }\n\n if (units.length >= CHUNK_SIZE) {\n result += String.fromCharCode(...units);\n units.length = 0;\n }\n }\n\n if (units.length > 0) {\n result += String.fromCharCode(...units);\n }\n\n return result;\n}\n\nconst sharedTextDecoder = new TextDecoder();\n\n// This threshold should be determined by benchmarking, which might vary in engines and input data.\n// Run `npx ts-node benchmark/decode-string.ts` for details.\nconst TEXT_DECODER_THRESHOLD = 200;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n return sharedTextDecoder.decode(stringBytes);\n}\n\nexport function utf8Decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n if (byteLength > TEXT_DECODER_THRESHOLD) {\n return utf8DecodeTD(bytes, inputOffset, byteLength);\n } else {\n return utf8DecodeJs(bytes, inputOffset, byteLength);\n }\n}\n", "/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n readonly type: number;\n readonly data: Uint8Array | ((pos: number) => Uint8Array);\n\n constructor(type: number, data: Uint8Array | ((pos: number) => Uint8Array)) {\n this.type = type;\n this.data = data;\n }\n}\n", "export class DecodeError extends Error {\n constructor(message: string) {\n super(message);\n\n // fix the prototype chain in a cross-platform way\n const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n Object.setPrototypeOf(this, proto);\n\n Object.defineProperty(this, \"name\", {\n configurable: true,\n enumerable: false,\n value: DecodeError.name,\n });\n }\n}\n", "// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n const high = value / 0x1_0000_0000;\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n const high = Math.floor(value / 0x1_0000_0000);\n const low = value; // high bits are truncated by DataView\n view.setUint32(offset, high);\n view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n const high = view.getInt32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n const high = view.getUint32(offset);\n const low = view.getUint32(offset + 4);\n return high * 0x1_0000_0000 + low;\n}\n", "// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError.ts\";\nimport { getInt64, setInt64 } from \"./utils/int.ts\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n sec: number;\n nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n // Here sec >= 0 && nsec >= 0\n if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n // timestamp 32 = { sec32 (unsigned) }\n const rv = new Uint8Array(4);\n const view = new DataView(rv.buffer);\n view.setUint32(0, sec);\n return rv;\n } else {\n // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n const secHigh = sec / 0x100000000;\n const secLow = sec & 0xffffffff;\n const rv = new Uint8Array(8);\n const view = new DataView(rv.buffer);\n // nsec30 | secHigh2\n view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n // secLow32\n view.setUint32(4, secLow);\n return rv;\n }\n } else {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n const rv = new Uint8Array(12);\n const view = new DataView(rv.buffer);\n view.setUint32(0, nsec);\n setInt64(view, 4, sec);\n return rv;\n }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n const msec = date.getTime();\n const sec = Math.floor(msec / 1e3);\n const nsec = (msec - sec * 1e3) * 1e6;\n\n // Normalizes { sec, nsec } to ensure nsec is unsigned.\n const nsecInSec = Math.floor(nsec / 1e9);\n return {\n sec: sec + nsecInSec,\n nsec: nsec - nsecInSec * 1e9,\n };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n if (object instanceof Date) {\n const timeSpec = encodeDateToTimeSpec(object);\n return encodeTimeSpecToTimestamp(timeSpec);\n } else {\n return null;\n }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n // data may be 32, 64, or 96 bits\n switch (data.byteLength) {\n case 4: {\n // timestamp 32 = { sec32 }\n const sec = view.getUint32(0);\n const nsec = 0;\n return { sec, nsec };\n }\n case 8: {\n // timestamp 64 = { nsec30, sec34 }\n const nsec30AndSecHigh2 = view.getUint32(0);\n const secLow32 = view.getUint32(4);\n const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n const nsec = nsec30AndSecHigh2 >>> 2;\n return { sec, nsec };\n }\n case 12: {\n // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n const sec = getInt64(view, 4);\n const nsec = view.getUint32(0);\n return { sec, nsec };\n }\n default:\n throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n const timeSpec = decodeTimestampToTimeSpec(data);\n return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n type: EXT_TIMESTAMP,\n encode: encodeTimestampExtension,\n decode: decodeTimestampExtension,\n};\n", "// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData.ts\";\nimport { timestampExtension } from \"./timestamp.ts\";\n\nexport type ExtensionDecoderType<ContextType> = (\n data: Uint8Array,\n extensionType: number,\n context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (\n input: unknown,\n context: ContextType,\n) => Uint8Array | ((dataPos: number) => Uint8Array) | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n tryToEncode(object: unknown, context: ContextType): ExtData | null;\n decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n // this will make type errors a lot more clear\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __brand?: ContextType;\n\n // built-in extensions\n private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n // custom extensions\n private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n public constructor() {\n this.register(timestampExtension);\n }\n\n public register({\n type,\n encode,\n decode,\n }: {\n type: number;\n encode: ExtensionEncoderType<ContextType>;\n decode: ExtensionDecoderType<ContextType>;\n }): void {\n if (type >= 0) {\n // custom extensions\n this.encoders[type] = encode;\n this.decoders[type] = decode;\n } else {\n // built-in extensions\n const index = -1 - type;\n this.builtInEncoders[index] = encode;\n this.builtInDecoders[index] = decode;\n }\n }\n\n public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n // built-in extensions\n for (let i = 0; i < this.builtInEncoders.length; i++) {\n const encodeExt = this.builtInEncoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = -1 - i;\n return new ExtData(type, data);\n }\n }\n }\n\n // custom extensions\n for (let i = 0; i < this.encoders.length; i++) {\n const encodeExt = this.encoders[i];\n if (encodeExt != null) {\n const data = encodeExt(object, context);\n if (data != null) {\n const type = i;\n return new ExtData(type, data);\n }\n }\n }\n\n if (object instanceof ExtData) {\n // to keep ExtData as is\n return object;\n }\n return null;\n }\n\n public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n if (decodeExt) {\n return decodeExt(data, type, context);\n } else {\n // decode() does not fail, returns ExtData instead.\n return new ExtData(type, data);\n }\n }\n}\n", "function isArrayBufferLike(buffer: unknown): buffer is ArrayBufferLike {\n return (\n buffer instanceof ArrayBuffer || (typeof SharedArrayBuffer !== \"undefined\" && buffer instanceof SharedArrayBuffer)\n );\n}\n\nexport function ensureUint8Array(\n buffer: ArrayLike<number> | Uint8Array<ArrayBufferLike> | ArrayBufferView | ArrayBufferLike,\n): Uint8Array<ArrayBufferLike> {\n if (buffer instanceof Uint8Array) {\n return buffer;\n } else if (ArrayBuffer.isView(buffer)) {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n } else if (isArrayBufferLike(buffer)) {\n return new Uint8Array(buffer);\n } else {\n // ArrayLike<number>\n return Uint8Array.from(buffer);\n }\n}\n", "import { utf8Count, utf8Encode } from \"./utils/utf8.ts\";\nimport { ExtensionCodec } from \"./ExtensionCodec.ts\";\nimport { setInt64, setUint64 } from \"./utils/int.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport type { ExtData } from \"./ExtData.ts\";\nimport type { ContextOf } from \"./context.ts\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec.ts\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport type EncoderOptions<ContextType = undefined> = Partial<\n Readonly<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Encodes bigint as Int64 or Uint64 if it's set to true.\n * {@link forceIntegerToFloat} does not affect bigint.\n * Depends on ES2020's {@link DataView#setBigInt64} and\n * {@link DataView#setBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * The maximum depth in nested objects and arrays.\n *\n * Defaults to 100.\n */\n maxDepth: number;\n\n /**\n * The initial size of the internal buffer.\n *\n * Defaults to 2048.\n */\n initialBufferSize: number;\n\n /**\n * If `true`, the keys of an object is sorted. In other words, the encoded\n * binary is canonical and thus comparable to another encoded binary.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n sortKeys: boolean;\n /**\n * If `true`, non-integer numbers are encoded in float32, not in float64 (the default).\n *\n * Only use it if precisions don't matter.\n *\n * Defaults to `false`.\n */\n forceFloat32: boolean;\n\n /**\n * If `true`, an object property with `undefined` value are ignored.\n * e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.\n *\n * Defaults to `false`. If enabled, it spends more time in encoding objects.\n */\n ignoreUndefined: boolean;\n\n /**\n * If `true`, integer numbers are encoded as floating point numbers,\n * with the `forceFloat32` option taken into account.\n *\n * Defaults to `false`.\n */\n forceIntegerToFloat: boolean;\n }>\n> &\n ContextOf<ContextType>;\n\nexport class Encoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly maxDepth: number;\n private readonly initialBufferSize: number;\n private readonly sortKeys: boolean;\n private readonly forceFloat32: boolean;\n private readonly ignoreUndefined: boolean;\n private readonly forceIntegerToFloat: boolean;\n\n private pos: number;\n private view: DataView<ArrayBuffer>;\n private bytes: Uint8Array<ArrayBuffer>;\n\n private entered = false;\n\n public constructor(options?: EncoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;\n this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;\n this.sortKeys = options?.sortKeys ?? false;\n this.forceFloat32 = options?.forceFloat32 ?? false;\n this.ignoreUndefined = options?.ignoreUndefined ?? false;\n this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;\n\n this.pos = 0;\n this.view = new DataView(new ArrayBuffer(this.initialBufferSize));\n this.bytes = new Uint8Array(this.view.buffer);\n }\n\n private clone() {\n // Because of slightly special argument `context`,\n // type assertion is needed.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Encoder<ContextType>({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n maxDepth: this.maxDepth,\n initialBufferSize: this.initialBufferSize,\n sortKeys: this.sortKeys,\n forceFloat32: this.forceFloat32,\n ignoreUndefined: this.ignoreUndefined,\n forceIntegerToFloat: this.forceIntegerToFloat,\n } as any);\n }\n\n private reinitializeState() {\n this.pos = 0;\n }\n\n /**\n * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n *\n * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n */\n public encodeSharedRef(object: unknown): Uint8Array<ArrayBuffer> {\n if (this.entered) {\n const instance = this.clone();\n return instance.encodeSharedRef(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.subarray(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n /**\n * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n */\n public encode(object: unknown): Uint8Array<ArrayBuffer> {\n if (this.entered) {\n const instance = this.clone();\n return instance.encode(object);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.doEncode(object, 1);\n return this.bytes.slice(0, this.pos);\n } finally {\n this.entered = false;\n }\n }\n\n private doEncode(object: unknown, depth: number): void {\n if (depth > this.maxDepth) {\n throw new Error(`Too deep objects in depth ${depth}`);\n }\n\n if (object == null) {\n this.encodeNil();\n } else if (typeof object === \"boolean\") {\n this.encodeBoolean(object);\n } else if (typeof object === \"number\") {\n if (!this.forceIntegerToFloat) {\n this.encodeNumber(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else if (typeof object === \"string\") {\n this.encodeString(object);\n } else if (this.useBigInt64 && typeof object === \"bigint\") {\n this.encodeBigInt64(object);\n } else {\n this.encodeObject(object, depth);\n }\n }\n\n private ensureBufferSizeToWrite(sizeToWrite: number) {\n const requiredSize = this.pos + sizeToWrite;\n\n if (this.view.byteLength < requiredSize) {\n this.resizeBuffer(requiredSize * 2);\n }\n }\n\n private resizeBuffer(newSize: number) {\n const newBuffer = new ArrayBuffer(newSize);\n const newBytes = new Uint8Array(newBuffer);\n const newView = new DataView(newBuffer);\n\n newBytes.set(this.bytes);\n\n this.view = newView;\n this.bytes = newBytes;\n }\n\n private encodeNil() {\n this.writeU8(0xc0);\n }\n\n private encodeBoolean(object: boolean) {\n if (object === false) {\n this.writeU8(0xc2);\n } else {\n this.writeU8(0xc3);\n }\n }\n\n private encodeNumber(object: number): void {\n if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {\n if (object >= 0) {\n if (object < 0x80) {\n // positive fixint\n this.writeU8(object);\n } else if (object < 0x100) {\n // uint 8\n this.writeU8(0xcc);\n this.writeU8(object);\n } else if (object < 0x10000) {\n // uint 16\n this.writeU8(0xcd);\n this.writeU16(object);\n } else if (object < 0x100000000) {\n // uint 32\n this.writeU8(0xce);\n this.writeU32(object);\n } else if (!this.useBigInt64) {\n // uint 64\n this.writeU8(0xcf);\n this.writeU64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n } else {\n if (object >= -0x20) {\n // negative fixint\n this.writeU8(0xe0 | (object + 0x20));\n } else if (object >= -0x80) {\n // int 8\n this.writeU8(0xd0);\n this.writeI8(object);\n } else if (object >= -0x8000) {\n // int 16\n this.writeU8(0xd1);\n this.writeI16(object);\n } else if (object >= -0x80000000) {\n // int 32\n this.writeU8(0xd2);\n this.writeI32(object);\n } else if (!this.useBigInt64) {\n // int 64\n this.writeU8(0xd3);\n this.writeI64(object);\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n } else {\n this.encodeNumberAsFloat(object);\n }\n }\n\n private encodeNumberAsFloat(object: number): void {\n if (this.forceFloat32) {\n // float 32\n this.writeU8(0xca);\n this.writeF32(object);\n } else {\n // float 64\n this.writeU8(0xcb);\n this.writeF64(object);\n }\n }\n\n private encodeBigInt64(object: bigint): void {\n if (object >= BigInt(0)) {\n // uint 64\n this.writeU8(0xcf);\n this.writeBigUint64(object);\n } else {\n // int 64\n this.writeU8(0xd3);\n this.writeBigInt64(object);\n }\n }\n\n private writeStringHeader(byteLength: number) {\n if (byteLength < 32) {\n // fixstr\n this.writeU8(0xa0 + byteLength);\n } else if (byteLength < 0x100) {\n // str 8\n this.writeU8(0xd9);\n this.writeU8(byteLength);\n } else if (byteLength < 0x10000) {\n // str 16\n this.writeU8(0xda);\n this.writeU16(byteLength);\n } else if (byteLength < 0x100000000) {\n // str 32\n this.writeU8(0xdb);\n this.writeU32(byteLength);\n } else {\n throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n }\n }\n\n private encodeString(object: string) {\n const maxHeaderSize = 1 + 4;\n\n const byteLength = utf8Count(object);\n this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n this.writeStringHeader(byteLength);\n utf8Encode(object, this.bytes, this.pos);\n this.pos += byteLength;\n }\n\n private encodeObject(object: unknown, depth: number) {\n // try to encode objects with custom codec first of non-primitives\n const ext = this.extensionCodec.tryToEncode(object, this.context);\n if (ext != null) {\n this.encodeExtension(ext);\n } else if (Array.isArray(object)) {\n this.encodeArray(object, depth);\n } else if (ArrayBuffer.isView(object)) {\n this.encodeBinary(object);\n } else if (typeof object === \"object\") {\n this.encodeMap(object as Record<string, unknown>, depth);\n } else {\n // symbol, function and other special object come here unless extensionCodec handles them.\n throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n }\n }\n\n private encodeBinary(object: ArrayBufferView) {\n const size = object.byteLength;\n if (size < 0x100) {\n // bin 8\n this.writeU8(0xc4);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // bin 16\n this.writeU8(0xc5);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // bin 32\n this.writeU8(0xc6);\n this.writeU32(size);\n } else {\n throw new Error(`Too large binary: ${size}`);\n }\n const bytes = ensureUint8Array(object);\n this.writeU8a(bytes);\n }\n\n private encodeArray(object: Array<unknown>, depth: number) {\n const size = object.length;\n if (size < 16) {\n // fixarray\n this.writeU8(0x90 + size);\n } else if (size < 0x10000) {\n // array 16\n this.writeU8(0xdc);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // array 32\n this.writeU8(0xdd);\n this.writeU32(size);\n } else {\n throw new Error(`Too large array: ${size}`);\n }\n for (const item of object) {\n this.doEncode(item, depth + 1);\n }\n }\n\n private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n let count = 0;\n\n for (const key of keys) {\n if (object[key] !== undefined) {\n count++;\n }\n }\n\n return count;\n }\n\n private encodeMap(object: Record<string, unknown>, depth: number) {\n const keys = Object.keys(object);\n if (this.sortKeys) {\n keys.sort();\n }\n\n const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n if (size < 16) {\n // fixmap\n this.writeU8(0x80 + size);\n } else if (size < 0x10000) {\n // map 16\n this.writeU8(0xde);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // map 32\n this.writeU8(0xdf);\n this.writeU32(size);\n } else {\n throw new Error(`Too large map object: ${size}`);\n }\n\n for (const key of keys) {\n const value = object[key];\n\n if (!(this.ignoreUndefined && value === undefined)) {\n this.encodeString(key);\n this.doEncode(value, depth + 1);\n }\n }\n }\n\n private encodeExtension(ext: ExtData) {\n if (typeof ext.data === \"function\") {\n const data = ext.data(this.pos + 6);\n const size = data.length;\n\n if (size >= 0x100000000) {\n throw new Error(`Too large extension object: ${size}`);\n }\n\n this.writeU8(0xc9);\n this.writeU32(size);\n this.writeI8(ext.type);\n this.writeU8a(data);\n return;\n }\n\n const size = ext.data.length;\n if (size === 1) {\n // fixext 1\n this.writeU8(0xd4);\n } else if (size === 2) {\n // fixext 2\n this.writeU8(0xd5);\n } else if (size === 4) {\n // fixext 4\n this.writeU8(0xd6);\n } else if (size === 8) {\n // fixext 8\n this.writeU8(0xd7);\n } else if (size === 16) {\n // fixext 16\n this.writeU8(0xd8);\n } else if (size < 0x100) {\n // ext 8\n this.writeU8(0xc7);\n this.writeU8(size);\n } else if (size < 0x10000) {\n // ext 16\n this.writeU8(0xc8);\n this.writeU16(size);\n } else if (size < 0x100000000) {\n // ext 32\n this.writeU8(0xc9);\n this.writeU32(size);\n } else {\n throw new Error(`Too large extension object: ${size}`);\n }\n this.writeI8(ext.type);\n this.writeU8a(ext.data);\n }\n\n private writeU8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setUint8(this.pos, value);\n this.pos++;\n }\n\n private writeU8a(values: ArrayLike<number>) {\n const size = values.length;\n this.ensureBufferSizeToWrite(size);\n\n this.bytes.set(values, this.pos);\n this.pos += size;\n }\n\n private writeI8(value: number) {\n this.ensureBufferSizeToWrite(1);\n\n this.view.setInt8(this.pos, value);\n this.pos++;\n }\n\n private writeU16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setUint16(this.pos, value);\n this.pos += 2;\n }\n\n private writeI16(value: number) {\n this.ensureBufferSizeToWrite(2);\n\n this.view.setInt16(this.pos, value);\n this.pos += 2;\n }\n\n private writeU32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setUint32(this.pos, value);\n this.pos += 4;\n }\n\n private writeI32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setInt32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF32(value: number) {\n this.ensureBufferSizeToWrite(4);\n\n this.view.setFloat32(this.pos, value);\n this.pos += 4;\n }\n\n private writeF64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setFloat64(this.pos, value);\n this.pos += 8;\n }\n\n private writeU64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setUint64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeI64(value: number) {\n this.ensureBufferSizeToWrite(8);\n\n setInt64(this.view, this.pos, value);\n this.pos += 8;\n }\n\n private writeBigUint64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigUint64(this.pos, value);\n this.pos += 8;\n }\n\n private writeBigInt64(value: bigint) {\n this.ensureBufferSizeToWrite(8);\n\n this.view.setBigInt64(this.pos, value);\n this.pos += 8;\n }\n}\n", "import { Encoder } from \"./Encoder.ts\";\nimport type { EncoderOptions } from \"./Encoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode<ContextType = undefined>(\n value: unknown,\n options?: EncoderOptions<SplitUndefined<ContextType>>,\n): Uint8Array<ArrayBuffer> {\n const encoder = new Encoder(options);\n return encoder.encodeSharedRef(value);\n}\n", "export function prettyByte(byte: number): string {\n return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n", "import { utf8DecodeJs } from \"./utils/utf8.ts\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n canBeCached(byteLength: number): boolean;\n decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n readonly bytes: Uint8Array;\n readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n hit = 0;\n miss = 0;\n private readonly caches: Array<Array<KeyCacheRecord>>;\n readonly maxKeyLength: number;\n readonly maxLengthPerKey: number;\n\n constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n this.maxKeyLength = maxKeyLength;\n this.maxLengthPerKey = maxLengthPerKey;\n\n // avoid `new Array(N)`, which makes a sparse array,\n // because a sparse array is typically slower than a non-sparse array.\n this.caches = [];\n for (let i = 0; i < this.maxKeyLength; i++) {\n this.caches.push([]);\n }\n }\n\n public canBeCached(byteLength: number): boolean {\n return byteLength > 0 && byteLength <= this.maxKeyLength;\n }\n\n private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n const records = this.caches[byteLength - 1]!;\n\n FIND_CHUNK: for (const record of records) {\n const recordBytes = record.bytes;\n\n for (let j = 0; j < byteLength; j++) {\n if (recordBytes[j] !== bytes[inputOffset + j]) {\n continue FIND_CHUNK;\n }\n }\n return record.str;\n }\n return null;\n }\n\n private store(bytes: Uint8Array, value: string) {\n const records = this.caches[bytes.length - 1]!;\n const record: KeyCacheRecord = { bytes, str: value };\n\n if (records.length >= this.maxLengthPerKey) {\n // `records` are full!\n // Set `record` to an arbitrary position.\n records[(Math.random() * records.length) | 0] = record;\n } else {\n records.push(record);\n }\n }\n\n public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n const cachedValue = this.find(bytes, inputOffset, byteLength);\n if (cachedValue != null) {\n this.hit++;\n return cachedValue;\n }\n this.miss++;\n\n const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n // Ensure to copy a slice of bytes because the bytes may be a NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n this.store(slicedCopyOfBytes, str);\n return str;\n }\n}\n", "import { prettyByte } from \"./utils/prettyByte.ts\";\nimport { ExtensionCodec } from \"./ExtensionCodec.ts\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int.ts\";\nimport { utf8Decode } from \"./utils/utf8.ts\";\nimport { ensureUint8Array } from \"./utils/typedArrays.ts\";\nimport { CachedKeyDecoder } from \"./CachedKeyDecoder.ts\";\nimport { DecodeError } from \"./DecodeError.ts\";\nimport type { ContextOf } from \"./context.ts\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec.ts\";\nimport type { KeyDecoder } from \"./CachedKeyDecoder.ts\";\n\nexport type DecoderOptions<ContextType = undefined> = Readonly<\n Partial<{\n extensionCodec: ExtensionCodecType<ContextType>;\n\n /**\n * Decodes Int64 and Uint64 as bigint if it's set to true.\n * Depends on ES2020's {@link DataView#getBigInt64} and\n * {@link DataView#getBigUint64}.\n *\n * Defaults to false.\n */\n useBigInt64: boolean;\n\n /**\n * By default, string values will be decoded as UTF-8 strings. However, if this option is true,\n * string values will be returned as Uint8Arrays without additional decoding.\n *\n * This is useful if the strings may contain invalid UTF-8 sequences.\n *\n * Note that this option only applies to string values, not map keys. Additionally, when\n * enabled, raw string length is limited by the maxBinLength option.\n */\n rawStrings: boolean;\n\n /**\n * Maximum string length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxStrLength: number;\n /**\n * Maximum binary length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxBinLength: number;\n /**\n * Maximum array length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxArrayLength: number;\n /**\n * Maximum map length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxMapLength: number;\n /**\n * Maximum extension length.\n *\n * Defaults to 4_294_967_295 (UINT32_MAX).\n */\n maxExtLength: number;\n\n /**\n * An object key decoder. Defaults to the shared instance of {@link CachedKeyDecoder}.\n * `null` is a special value to disable the use of the key decoder at all.\n */\n keyDecoder: KeyDecoder | null;\n\n /**\n * A function to convert decoded map key to a valid JS key type.\n *\n * Defaults to a function that throws an error if the key is not a string or a number.\n */\n mapKeyConverter: (key: unknown) => MapKeyType;\n }>\n> &\n ContextOf<ContextType>;\n\nconst STATE_ARRAY = \"array\";\nconst STATE_MAP_KEY = \"map_key\";\nconst STATE_MAP_VALUE = \"map_value\";\n\ntype MapKeyType = string | number;\n\nconst mapKeyConverter = (key: unknown): MapKeyType => {\n if (typeof key === \"string\" || typeof key === \"number\") {\n return key;\n }\n throw new DecodeError(\"The type of key must be string or number but \" + typeof key);\n};\n\ntype StackMapState = {\n type: typeof STATE_MAP_KEY | typeof STATE_MAP_VALUE;\n size: number;\n key: MapKeyType | null;\n readCount: number;\n map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n type: typeof STATE_ARRAY;\n size: number;\n array: Array<unknown>;\n position: number;\n};\n\nclass StackPool {\n private readonly stack: Array<StackState> = [];\n private stackHeadPosition = -1;\n\n public get length(): number {\n return this.stackHeadPosition + 1;\n }\n\n public top(): StackState | undefined {\n return this.stack[this.stackHeadPosition];\n }\n\n public pushArrayState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackArrayState;\n\n state.type = STATE_ARRAY;\n state.position = 0;\n state.size = size;\n state.array = new Array(size);\n }\n\n public pushMapState(size: number) {\n const state = this.getUninitializedStateFromPool() as StackMapState;\n\n state.type = STATE_MAP_KEY;\n state.readCount = 0;\n state.size = size;\n state.map = {};\n }\n\n private getUninitializedStateFromPool() {\n this.stackHeadPosition++;\n\n if (this.stackHeadPosition === this.stack.length) {\n const partialState: Partial<StackState> = {\n type: undefined,\n size: 0,\n array: undefined,\n position: 0,\n readCount: 0,\n map: undefined,\n key: null,\n };\n\n this.stack.push(partialState as StackState);\n }\n\n return this.stack[this.stackHeadPosition];\n }\n\n public release(state: StackState): void {\n const topStackState = this.stack[this.stackHeadPosition];\n\n if (topStackState !== state) {\n throw new Error(\"Invalid stack state. Released state is not on top of the stack.\");\n }\n\n if (state.type === STATE_ARRAY) {\n const partialState = state as Partial<StackArrayState>;\n partialState.size = 0;\n partialState.array = undefined;\n partialState.position = 0;\n partialState.type = undefined;\n }\n\n if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {\n const partialState = state as Partial<StackMapState>;\n partialState.size = 0;\n partialState.map = undefined;\n partialState.readCount = 0;\n partialState.type = undefined;\n }\n\n this.stackHeadPosition--;\n }\n\n public reset(): void {\n this.stack.length = 0;\n this.stackHeadPosition = -1;\n }\n}\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView<ArrayBufferLike>(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array<ArrayBufferLike>(EMPTY_VIEW.buffer);\n\ntry {\n // IE11: The spec says it should throw RangeError,\n // IE11: but in IE11 it throws TypeError.\n EMPTY_VIEW.getInt8(0);\n} catch (e) {\n if (!(e instanceof RangeError)) {\n throw new Error(\n \"This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access\",\n );\n }\n}\n\nconst MORE_DATA = new RangeError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n private readonly extensionCodec: ExtensionCodecType<ContextType>;\n private readonly context: ContextType;\n private readonly useBigInt64: boolean;\n private readonly rawStrings: boolean;\n private readonly maxStrLength: number;\n private readonly maxBinLength: number;\n private readonly maxArrayLength: number;\n private readonly maxMapLength: number;\n private readonly maxExtLength: number;\n private readonly keyDecoder: KeyDecoder | null;\n private readonly mapKeyConverter: (key: unknown) => MapKeyType;\n\n private totalPos = 0;\n private pos = 0;\n\n private view = EMPTY_VIEW;\n private bytes = EMPTY_BYTES;\n private headByte = HEAD_BYTE_REQUIRED;\n private readonly stack = new StackPool();\n\n private entered = false;\n\n public constructor(options?: DecoderOptions<ContextType>) {\n this.extensionCodec = options?.extensionCodec ?? (ExtensionCodec.defaultCodec as ExtensionCodecType<ContextType>);\n this.context = (options as { context: ContextType } | undefined)?.context as ContextType; // needs a type assertion because EncoderOptions has no context property when ContextType is undefined\n\n this.useBigInt64 = options?.useBigInt64 ?? false;\n this.rawStrings = options?.rawStrings ?? false;\n this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;\n this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;\n this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;\n this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;\n this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;\n this.keyDecoder = options?.keyDecoder !== undefined ? options.keyDecoder : sharedCachedKeyDecoder;\n this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;\n }\n\n private clone(): Decoder<ContextType> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return new Decoder({\n extensionCodec: this.extensionCodec,\n context: this.context,\n useBigInt64: this.useBigInt64,\n rawStrings: this.rawStrings,\n maxStrLength: this.maxStrLength,\n maxBinLength: this.maxBinLength,\n maxArrayLength: this.maxArrayLength,\n maxMapLength: this.maxMapLength,\n maxExtLength: this.maxExtLength,\n keyDecoder: this.keyDecoder,\n } as any);\n }\n\n private reinitializeState() {\n this.totalPos = 0;\n this.headByte = HEAD_BYTE_REQUIRED;\n this.stack.reset();\n\n // view, bytes, and pos will be re-initialized in setBuffer()\n }\n\n private setBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n const bytes = ensureUint8Array(buffer);\n this.bytes = bytes;\n this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n this.pos = 0;\n }\n\n private appendBuffer(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): void {\n if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n this.setBuffer(buffer);\n } else {\n const remainingData = this.bytes.subarray(this.pos);\n const newData = ensureUint8Array(buffer);\n\n // concat remainingData + newData\n const newBuffer = new Uint8Array(remainingData.length + newData.length);\n newBuffer.set(remainingData);\n newBuffer.set(newData, remainingData.length);\n this.setBuffer(newBuffer);\n }\n }\n\n private hasRemaining(size: number) {\n return this.view.byteLength - this.pos >= size;\n }\n\n private createExtraByteError(posToShow: number): Error {\n const { view, pos } = this;\n return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n }\n\n /**\n * @throws {@link DecodeError}\n * @throws {@link RangeError}\n */\n public decode(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): unknown {\n if (this.entered) {\n const instance = this.clone();\n return instance.decode(buffer);\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n const object = this.doDecodeSync();\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.pos);\n }\n return object;\n } finally {\n this.entered = false;\n }\n }\n\n public *decodeMulti(buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike): Generator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMulti(buffer);\n return;\n }\n\n try {\n this.entered = true;\n\n this.reinitializeState();\n this.setBuffer(buffer);\n\n while (this.hasRemaining(1)) {\n yield this.doDecodeSync();\n }\n } finally {\n this.entered = false;\n }\n }\n\n public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): Promise<unknown> {\n if (this.entered) {\n const instance = this.clone();\n return instance.decodeAsync(stream);\n }\n\n try {\n this.entered = true;\n\n let decoded = false;\n let object: unknown;\n for await (const buffer of stream) {\n if (decoded) {\n this.entered = false;\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n try {\n object = this.doDecodeSync();\n decoded = true;\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n\n if (decoded) {\n if (this.hasRemaining(1)) {\n throw this.createExtraByteError(this.totalPos);\n }\n return object;\n }\n\n const { headByte, pos, totalPos } = this;\n throw new RangeError(\n `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n );\n } finally {\n this.entered = false;\n }\n }\n\n public decodeArrayStream(\n stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>,\n ): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, true);\n }\n\n public decodeStream(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>): AsyncGenerator<unknown, void, unknown> {\n return this.decodeMultiAsync(stream, false);\n }\n\n private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | ArrayBufferView | ArrayBufferLike>, isArray: boolean): AsyncGenerator<unknown, void, unknown> {\n if (this.entered) {\n const instance = this.clone();\n yield* instance.decodeMultiAsync(stream, isArray);\n return;\n }\n\n try {\n this.entered = true;\n\n let isArrayHeaderRequired = isArray;\n let arrayItemsLeft = -1;\n\n for await (const buffer of stream) {\n if (isArray && arrayItemsLeft === 0) {\n throw this.createExtraByteError(this.totalPos);\n }\n\n this.appendBuffer(buffer);\n\n if (isArrayHeaderRequired) {\n arrayItemsLeft = this.readArraySize();\n isArrayHeaderRequired = false;\n this.complete();\n }\n\n try {\n while (true) {\n yield this.doDecodeSync();\n if (--arrayItemsLeft === 0) {\n break;\n }\n }\n } catch (e) {\n if (!(e instanceof RangeError)) {\n throw e; // rethrow\n }\n // fallthrough\n }\n this.totalPos += this.pos;\n }\n } finally {\n this.entered = false;\n }\n }\n\n private doDecodeSync(): unknown {\n DECODE: while (true) {\n const headByte = this.readHeadByte();\n let object: unknown;\n\n if (headByte >= 0xe0) {\n // negative fixint (111x xxxx) 0xe0 - 0xff\n object = headByte - 0x100;\n } else if (headByte < 0xc0) {\n if (headByte < 0x80) {\n // positive fixint (0xxx xxxx) 0x00 - 0x7f\n object = headByte;\n } else if (headByte < 0x90) {\n // fixmap (1000 xxxx) 0x80 - 0x8f\n const size = headByte - 0x80;\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte < 0xa0) {\n // fixarray (1001 xxxx) 0x90 - 0x9f\n const size = headByte - 0x90;\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else {\n // fixstr (101x xxxx) 0xa0 - 0xbf\n const byteLength = headByte - 0xa0;\n object = this.decodeString(byteLength, 0);\n }\n } else if (headByte === 0xc0) {\n // nil\n object = null;\n } else if (headByte === 0xc2) {\n // false\n object = false;\n } else if (headByte === 0xc3) {\n // true\n object = true;\n } else if (headByte === 0xca) {\n // float 32\n object = this.readF32();\n } else if (headByte === 0xcb) {\n // float 64\n object = this.readF64();\n } else if (headByte === 0xcc) {\n // uint 8\n object = this.readU8();\n } else if (headByte === 0xcd) {\n // uint 16\n object = this.readU16();\n } else if (headByte === 0xce) {\n // uint 32\n object = this.readU32();\n } else if (headByte === 0xcf) {\n // uint 64\n if (this.useBigInt64) {\n object = this.readU64AsBigInt();\n } else {\n object = this.readU64();\n }\n } else if (headByte === 0xd0) {\n // int 8\n object = this.readI8();\n } else if (headByte === 0xd1) {\n // int 16\n object = this.readI16();\n } else if (headByte === 0xd2) {\n // int 32\n object = this.readI32();\n } else if (headByte === 0xd3) {\n // int 64\n if (this.useBigInt64) {\n object = this.readI64AsBigInt();\n } else {\n object = this.readI64();\n }\n } else if (headByte === 0xd9) {\n // str 8\n const byteLength = this.lookU8();\n object = this.decodeString(byteLength, 1);\n } else if (headByte === 0xda) {\n // str 16\n const byteLength = this.lookU16();\n object = this.decodeString(byteLength, 2);\n } else if (headByte === 0xdb) {\n // str 32\n const byteLength = this.lookU32();\n object = this.decodeString(byteLength, 4);\n } else if (headByte === 0xdc) {\n // array 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xdd) {\n // array 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushArrayState(size);\n this.complete();\n continue DECODE;\n } else {\n object = [];\n }\n } else if (headByte === 0xde) {\n // map 16\n const size = this.readU16();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xdf) {\n // map 32\n const size = this.readU32();\n if (size !== 0) {\n this.pushMapState(size);\n this.complete();\n continue DECODE;\n } else {\n object = {};\n }\n } else if (headByte === 0xc4) {\n // bin 8\n const size = this.lookU8();\n object = this.decodeBinary(size, 1);\n } else if (headByte === 0xc5) {\n // bin 16\n const size = this.lookU16();\n object = this.decodeBinary(size, 2);\n } else if (headByte === 0xc6) {\n // bin 32\n const size = this.lookU32();\n object = this.decodeBinary(size, 4);\n } else if (headByte === 0xd4) {\n // fixext 1\n object = this.decodeExtension(1, 0);\n } else if (headByte === 0xd5) {\n // fixext 2\n object = this.decodeExtension(2, 0);\n } else if (headByte === 0xd6) {\n // fixext 4\n object = this.decodeExtension(4, 0);\n } else if (headByte === 0xd7) {\n // fixext 8\n object = this.decodeExtension(8, 0);\n } else if (headByte === 0xd8) {\n // fixext 16\n object = this.decodeExtension(16, 0);\n } else if (headByte === 0xc7) {\n // ext 8\n const size = this.lookU8();\n object = this.decodeExtension(size, 1);\n } else if (headByte === 0xc8) {\n // ext 16\n const size = this.lookU16();\n object = this.decodeExtension(size, 2);\n } else if (headByte === 0xc9) {\n // ext 32\n const size = this.lookU32();\n object = this.decodeExtension(size, 4);\n } else {\n throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n }\n\n this.complete();\n\n const stack = this.stack;\n while (stack.length > 0) {\n // arrays and maps\n const state = stack.top()!;\n if (state.type === STATE_ARRAY) {\n state.array[state.position] = object;\n state.position++;\n if (state.position === state.size) {\n object = state.array;\n stack.release(state);\n } else {\n continue DECODE;\n }\n } else if (state.type === STATE_MAP_KEY) {\n if (object === \"__proto__\") {\n throw new DecodeError(\"The key __proto__ is not allowed\");\n }\n\n state.key = this.mapKeyConverter(object);\n state.type = STATE_MAP_VALUE;\n continue DECODE;\n } else {\n // it must be `state.type === State.MAP_VALUE` here\n\n state.map[state.key!] = object;\n state.readCount++;\n\n if (state.readCount === state.size) {\n object = state.map;\n stack.release(state);\n } else {\n state.key = null;\n state.type = STATE_MAP_KEY;\n continue DECODE;\n }\n }\n }\n\n return object;\n }\n }\n\n private readHeadByte(): number {\n if (this.headByte === HEAD_BYTE_REQUIRED) {\n this.headByte = this.readU8();\n // console.log(\"headByte\", prettyByte(this.headByte));\n }\n\n return this.headByte;\n }\n\n private complete(): void {\n this.headByte = HEAD_BYTE_REQUIRED;\n }\n\n private readArraySize(): number {\n const headByte = this.readHeadByte();\n\n switch (headByte) {\n case 0xdc:\n return this.readU16();\n case 0xdd:\n return this.readU32();\n default: {\n if (headByte < 0xa0) {\n return headByte - 0x90;\n } else {\n throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n }\n }\n }\n }\n\n private pushMapState(size: number) {\n if (size > this.maxMapLength) {\n throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n }\n\n this.stack.pushMapState(size);\n }\n\n private pushArrayState(size: number) {\n if (size > this.maxArrayLength) {\n throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n }\n\n this.stack.pushArrayState(size);\n }\n\n private decodeString(byteLength: number, headerOffset: number): string | Uint8Array {\n if (!this.rawStrings || this.stateIsMapKey()) {\n return this.decodeUtf8String(byteLength, headerOffset);\n }\n return this.decodeBinary(byteLength, headerOffset);\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeUtf8String(byteLength: number, headerOffset: number): string {\n if (byteLength > this.maxStrLength) {\n throw new DecodeError(\n `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n );\n }\n\n if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headerOffset;\n let object: string;\n if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n } else {\n object = utf8Decode(this.bytes, offset, byteLength);\n }\n this.pos += headerOffset + byteLength;\n return object;\n }\n\n private stateIsMapKey(): boolean {\n if (this.stack.length > 0) {\n const state = this.stack.top()!;\n return state.type === STATE_MAP_KEY;\n }\n return false;\n }\n\n /**\n * @throws {@link RangeError}\n */\n private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n if (byteLength > this.maxBinLength) {\n throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n }\n\n if (!this.hasRemaining(byteLength + headOffset)) {\n throw MORE_DATA;\n }\n\n const offset = this.pos + headOffset;\n const object = this.bytes.subarray(offset, offset + byteLength);\n this.pos += headOffset + byteLength;\n return object;\n }\n\n private decodeExtension(size: number, headOffset: number): unknown {\n if (size > this.maxExtLength) {\n throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n }\n\n const extType = this.view.getInt8(this.pos + headOffset);\n const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n return this.extensionCodec.decode(data, extType, this.context);\n }\n\n private lookU8() {\n return this.view.getUint8(this.pos);\n }\n\n private lookU16() {\n return this.view.getUint16(this.pos);\n }\n\n private lookU32() {\n return this.view.getUint32(this.pos);\n }\n\n private readU8(): number {\n const value = this.view.getUint8(this.pos);\n this.pos++;\n return value;\n }\n\n private readI8(): number {\n const value = this.view.getInt8(this.pos);\n this.pos++;\n return value;\n }\n\n private readU16(): number {\n const value = this.view.getUint16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readI16(): number {\n const value = this.view.getInt16(this.pos);\n this.pos += 2;\n return value;\n }\n\n private readU32(): number {\n const value = this.view.getUint32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readI32(): number {\n const value = this.view.getInt32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readU64(): number {\n const value = getUint64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64(): number {\n const value = getInt64(this.view, this.pos);\n this.pos += 8;\n return value;\n }\n\n private readU64AsBigInt(): bigint {\n const value = this.view.getBigUint64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readI64AsBigInt(): bigint {\n const value = this.view.getBigInt64(this.pos);\n this.pos += 8;\n return value;\n }\n\n private readF32() {\n const value = this.view.getFloat32(this.pos);\n this.pos += 4;\n return value;\n }\n\n private readF64() {\n const value = this.view.getFloat64(this.pos);\n this.pos += 8;\n return value;\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync}, {@link decodeMultiStream}, or {@link decodeArrayStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n buffer: ArrayLike<number> | ArrayBufferView | ArrayBufferLike,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): unknown {\n const decoder = new Decoder(options);\n return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n buffer: ArrayLike<number> | BufferSource,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Generator<unknown, void, unknown> {\n const decoder = new Decoder(options);\n return decoder.decodeMulti(buffer);\n}\n", "// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n return (object as any)[Symbol.asyncIterator] != null;\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n const reader = stream.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n return;\n }\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n if (isAsyncIterable(streamLike)) {\n return streamLike;\n } else {\n return asyncIterableFromStream(streamLike);\n }\n}\n", "import { Decoder } from \"./Decoder.ts\";\nimport { ensureAsyncIterable } from \"./utils/stream.ts\";\nimport type { DecoderOptions } from \"./Decoder.ts\";\nimport type { ReadableStreamLike } from \"./utils/stream.ts\";\nimport type { SplitUndefined } from \"./context.ts\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport async function decodeAsync<ContextType = undefined>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): Promise<unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeArrayStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n options?: DecoderOptions<SplitUndefined<ContextType>>,\n): AsyncGenerator<unknown, void, unknown> {\n const stream = ensureAsyncIterable(streamLike);\n const decoder = new Decoder(options);\n return decoder.decodeStream(stream);\n}\n", "// Main Functions:\n\nimport { encode } from \"./encode.ts\";\nexport { encode };\n\nimport { decode, decodeMulti } from \"./decode.ts\";\nexport { decode, decodeMulti };\n\nimport { decodeAsync, decodeArrayStream, decodeMultiStream } from \"./decodeAsync.ts\";\nexport { decodeAsync, decodeArrayStream, decodeMultiStream };\n\nimport { Decoder } from \"./Decoder.ts\";\nexport { Decoder };\nimport type { DecoderOptions } from \"./Decoder.ts\";\nexport type { DecoderOptions };\nimport { DecodeError } from \"./DecodeError.ts\";\nexport { DecodeError };\n\nimport { Encoder } from \"./Encoder.ts\";\nexport { Encoder };\nimport type { EncoderOptions } from \"./Encoder.ts\";\nexport type { EncoderOptions };\n\n// Utilities for Extension Types:\n\nimport { ExtensionCodec } from \"./ExtensionCodec.ts\";\nexport { ExtensionCodec };\nimport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType } from \"./ExtensionCodec.ts\";\nexport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType };\nimport { ExtData } from \"./ExtData.ts\";\nexport { ExtData };\n\nimport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n} from \"./timestamp.ts\";\nexport {\n EXT_TIMESTAMP,\n encodeDateToTimeSpec,\n encodeTimeSpecToTimestamp,\n decodeTimestampToTimeSpec,\n encodeTimestampExtension,\n decodeTimestampExtension,\n};\n", "'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction valueEnumerable(value) {\n return { enumerable: true, value };\n}\n\nfunction valueEnumerableWritable(value) {\n return { enumerable: true, writable: true, value };\n}\n\nlet d = {};\nlet truthy = () => true;\nlet empty = () => ({});\nlet identity = a => a;\nlet callBoth = (par, fn, self, args) => par.apply(self, args) && fn.apply(self, args);\nlet callForward = (par, fn, self, [a, b]) => fn.call(self, par.call(self, a, b), b);\nlet create = (a, b) => Object.freeze(Object.create(a, b));\n\nfunction stack(fns, def, caller) {\n return fns.reduce((par, fn) => {\n return function(...args) {\n return caller(par, fn, this, args);\n };\n }, def);\n}\n\nfunction fnType(fn) {\n return create(this, { fn: valueEnumerable(fn) });\n}\n\nlet reduceType = {};\nlet reduce = fnType.bind(reduceType);\nlet action = fn => reduce((ctx, ev) => !!~fn(ctx, ev) && ctx);\n\nlet guardType = {};\nlet guard = fnType.bind(guardType);\n\nfunction filter(Type, arr) {\n return arr.filter(value => Type.isPrototypeOf(value));\n}\n\nfunction makeTransition(from, to, ...args) {\n let guards = stack(filter(guardType, args).map(t => t.fn), truthy, callBoth);\n let reducers = stack(filter(reduceType, args).map(t => t.fn), identity, callForward);\n return create(this, {\n from: valueEnumerable(from),\n to: valueEnumerable(to),\n guards: valueEnumerable(guards),\n reducers: valueEnumerable(reducers)\n });\n}\n\nlet transitionType = {};\nlet immediateType = {};\nlet transition = makeTransition.bind(transitionType);\nlet immediate = makeTransition.bind(immediateType, null);\n\nfunction enterImmediate(machine, service, event) {\n return transitionTo(service, machine, event, this.immediates) || machine;\n}\n\nfunction transitionsToMap(transitions) {\n let m = new Map();\n for(let t of transitions) {\n if(!m.has(t.from)) m.set(t.from, []);\n m.get(t.from).push(t);\n }\n return m;\n}\n\nlet stateType = { enter: identity };\nfunction state(...args) {\n let transitions = filter(transitionType, args);\n let immediates = filter(immediateType, args);\n let desc = {\n final: valueEnumerable(args.length === 0),\n transitions: valueEnumerable(transitionsToMap(transitions))\n };\n if(immediates.length) {\n desc.immediates = valueEnumerable(immediates);\n desc.enter = valueEnumerable(enterImmediate);\n }\n return create(stateType, desc);\n}\n\nlet invokeFnType = {\n enter(machine2, service, event) {\n let rn = this.fn.call(service, service.context, event);\n if(machine.isPrototypeOf(rn))\n return create(invokeMachineType, {\n machine: valueEnumerable(rn),\n transitions: valueEnumerable(this.transitions)\n }).enter(machine2, service, event)\n rn.then(data => service.send({ type: 'done', data }))\n .catch(error => service.send({ type: 'error', error }));\n return machine2;\n }\n};\nlet invokeMachineType = {\n enter(machine, service, event) {\n service.child = interpret(this.machine, s => {\n service.onChange(s);\n if(service.child == s && s.machine.state.value.final) {\n delete service.child;\n service.send({ type: 'done', data: s.context });\n }\n }, service.context, event);\n if(service.child.machine.state.value.final) {\n let data = service.child.context;\n delete service.child;\n return transitionTo(service, machine, { type: 'done', data }, this.transitions.get('done'));\n }\n return machine;\n }\n};\nfunction invoke(fn, ...transitions) {\n let t = valueEnumerable(transitionsToMap(transitions));\n return machine.isPrototypeOf(fn) ?\n create(invokeMachineType, {\n machine: valueEnumerable(fn),\n transitions: t\n }) :\n create(invokeFnType, {\n fn: valueEnumerable(fn),\n transitions: t\n });\n}\n\nlet machine = {\n get state() {\n return {\n name: this.current,\n value: this.states[this.current]\n };\n }\n};\n\nfunction createMachine(current, states, contextFn = empty) {\n if(typeof current !== 'string') {\n contextFn = states || empty;\n states = current;\n current = Object.keys(states)[0];\n }\n if(d._create) d._create(current, states);\n return create(machine, {\n context: valueEnumerable(contextFn),\n current: valueEnumerable(current),\n states: valueEnumerable(states)\n });\n}\n\nfunction transitionTo(service, machine, fromEvent, candidates) {\n let { context } = service;\n for(let { to, guards, reducers } of candidates) { \n if(guards(context, fromEvent)) {\n service.context = reducers.call(service, context, fromEvent);\n\n let original = machine.original || machine;\n let newMachine = create(original, {\n current: valueEnumerable(to),\n original: { value: original }\n });\n\n if (d._onEnter) d._onEnter(machine, to, service.context, context, fromEvent);\n let state = newMachine.state.value;\n return state.enter(newMachine, service, fromEvent);\n }\n }\n}\n\nfunction send(service, event) {\n let eventName = event.type || event;\n let { machine } = service;\n let { value: state, name: currentStateName } = machine.state;\n \n if(state.transitions.has(eventName)) {\n return transitionTo(service, machine, event, state.transitions.get(eventName)) || machine;\n } else {\n if(d._send) d._send(eventName, currentStateName);\n }\n return machine;\n}\n\nlet service = {\n send(event) {\n this.machine = send(this, event);\n \n // TODO detect change\n this.onChange(this);\n }\n};\n\nfunction interpret(machine, onChange, initialContext, event) {\n let s = Object.create(service, {\n machine: valueEnumerableWritable(machine),\n context: valueEnumerableWritable(machine.context(initialContext, event)),\n onChange: valueEnumerable(onChange)\n });\n s.send = s.send.bind(s);\n s.machine = s.machine.state.value.enter(s.machine, s, event);\n return s;\n}\n\nexports.action = action;\nexports.createMachine = createMachine;\nexports.d = d;\nexports.guard = guard;\nexports.immediate = immediate;\nexports.interpret = interpret;\nexports.invoke = invoke;\nexports.reduce = reduce;\nexports.state = state;\nexports.transition = transition;\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { decode, encode } from \"@msgpack/msgpack\";\nimport {\n ContextFunction,\n InterpretOnChangeFunction,\n Service,\n createMachine,\n guard,\n immediate,\n interpret,\n reduce,\n state,\n transition,\n} from \"robot3\";\nimport {\n TOKEN_EXPIRATION_SECONDS,\n type TokenProvider,\n getTemporaryAuthToken,\n} from \"./auth\";\nimport { RequiredConfig } from \"./config\";\nimport { ApiError } from \"./response\";\nimport { isBrowser } from \"./runtime\";\nimport { ensureEndpointIdFormat, isReact, throttle } from \"./utils\";\n\n// Define the context\ninterface Context {\n token?: string;\n enqueuedMessage?: any;\n websocket?: WebSocket;\n error?: Error;\n}\n\nconst initialState: ContextFunction<Context> = () => ({\n enqueuedMessage: undefined,\n});\n\ntype SendEvent = { type: \"send\"; message: any };\ntype AuthenticatedEvent = { type: \"authenticated\"; token: string };\ntype InitiateAuthEvent = { type: \"initiateAuth\" };\ntype UnauthorizedEvent = { type: \"unauthorized\"; error: Error };\ntype ConnectedEvent = { type: \"connected\"; websocket: WebSocket };\ntype ConnectionClosedEvent = {\n type: \"connectionClosed\";\n code: number;\n reason: string;\n};\n\ntype Event =\n | SendEvent\n | AuthenticatedEvent\n | InitiateAuthEvent\n | UnauthorizedEvent\n | ConnectedEvent\n | ConnectionClosedEvent;\n\nfunction hasToken(context: Context): boolean {\n return context.token !== undefined;\n}\n\nfunction noToken(context: Context): boolean {\n return !hasToken(context);\n}\n\nfunction enqueueMessage(context: Context, event: SendEvent): Context {\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction closeConnection(context: Context): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n context.websocket.close();\n }\n return {\n ...context,\n websocket: undefined,\n };\n}\n\nfunction sendMessage(context: Context, event: SendEvent): Context {\n if (context.websocket && context.websocket.readyState === WebSocket.OPEN) {\n if (event.message instanceof Uint8Array) {\n context.websocket.send(event.message);\n } else if (typeof event.message === \"string\") {\n context.websocket.send(event.message);\n } else {\n context.websocket.send(encode(event.message));\n }\n\n return {\n ...context,\n enqueuedMessage: undefined,\n };\n }\n return {\n ...context,\n enqueuedMessage: event.message,\n };\n}\n\nfunction expireToken(context: Context): Context {\n return {\n ...context,\n token: undefined,\n };\n}\n\nfunction setToken(context: Context, event: AuthenticatedEvent): Context {\n return {\n ...context,\n token: event.token,\n };\n}\n\nfunction connectionEstablished(\n context: Context,\n event: ConnectedEvent,\n): Context {\n return {\n ...context,\n websocket: event.websocket,\n };\n}\n\n// State machine\nconst connectionStateMachine = createMachine(\n \"idle\",\n {\n idle: state(\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"expireToken\", \"idle\", reduce(expireToken)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n connecting: state(\n transition(\"connecting\", \"connecting\"),\n transition(\"connected\", \"active\", reduce(connectionEstablished)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"send\", \"connecting\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n immediate(\"authRequired\", guard(noToken)),\n ),\n authRequired: state(\n transition(\"initiateAuth\", \"authInProgress\"),\n transition(\"send\", \"authRequired\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n authInProgress: state(\n transition(\"authenticated\", \"connecting\", reduce(setToken)),\n transition(\n \"unauthorized\",\n \"idle\",\n reduce(expireToken),\n reduce(closeConnection),\n ),\n transition(\"send\", \"authInProgress\", reduce(enqueueMessage)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n active: state(\n transition(\"send\", \"active\", reduce(sendMessage)),\n transition(\"unauthorized\", \"idle\", reduce(expireToken)),\n transition(\"connectionClosed\", \"idle\", reduce(closeConnection)),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n failed: state(\n transition(\"send\", \"failed\"),\n transition(\"close\", \"idle\", reduce(closeConnection)),\n ),\n },\n initialState,\n);\n\ntype WithRequestId = {\n request_id: string;\n};\n\n/**\n * A connection object that allows you to `send` request payloads to a\n * realtime endpoint.\n */\nexport interface RealtimeConnection<Input> {\n send(input: Input & Partial<WithRequestId>): void;\n\n close(): void;\n}\n\n/**\n * Options for connecting to the realtime endpoint.\n */\nexport interface RealtimeConnectionHandler<Output> {\n /**\n * The connection key. This is used to reuse the same connection\n * across multiple calls to `connect`. This is particularly useful in\n * contexts where the connection is established as part of a component\n * lifecycle (e.g. React) and the component is re-rendered multiple times.\n */\n connectionKey?: string;\n\n /**\n * If `true`, the connection will only be established on the client side.\n * This is useful for frameworks that reuse code for both server-side\n * rendering and client-side rendering (e.g. Next.js).\n *\n * This is set to `true` by default when running on React in the server.\n * Otherwise, it is set to `false`.\n *\n * Note that more SSR frameworks might be automatically detected\n * in the future. In the meantime, you can set this to `true` when needed.\n */\n clientOnly?: boolean;\n\n /**\n * The throtle duration in milliseconds. This is used to throtle the\n * calls to the `send` function. Realtime apps usually react to user\n * input, which can be very frequent (e.g. fast typing or mouse/drag movements).\n *\n * The default value is `128` milliseconds.\n */\n throttleInterval?: number;\n\n /**\n * Configures the maximum amount of frames to store in memory before starting to drop\n * old ones for in favor of the newer ones. It must be between `1` and `60`.\n *\n * The recommended is `2`. The default is `undefined` so it can be determined\n * by the app (normally is set to the recommended setting).\n */\n maxBuffering?: number;\n\n /**\n * Optional path to append after the app id. Defaults to `/realtime`.\n */\n path?: string;\n\n /**\n * Optional encoder for outgoing messages. Defaults to msgpack.\n * Should return either a `Uint8Array` (binary) or string (text frame).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n encodeMessage?: (input: any) => Uint8Array | string;\n\n /**\n * Optional decoder for incoming messages. Defaults to msgpack with JSON\n * support for string payloads.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n decodeMessage?: (data: any) => Promise<any> | any;\n\n /**\n * Callback function that is called when a result is received.\n * @param result - The result of the request.\n */\n onResult(result: Output & WithRequestId): void;\n\n /**\n * Callback function that is called when an error occurs.\n * @param error - The error that occurred.\n */\n onError?(error: ApiError<any>): void;\n\n /**\n * A custom token provider function. When provided, this function will be\n * used to fetch authentication tokens instead of the default internal\n * token fetching mechanism.\n *\n * This is useful when you want to fetch tokens through your own backend proxy.\n * If not provided, the default `getTemporaryAuthToken` will be used.\n */\n tokenProvider?: TokenProvider;\n\n /**\n * The token expiration time in seconds. This is used to determine when to\n * refresh the token. The token will be refreshed at 90% of this value.\n *\n * Only relevant when using a custom `tokenProvider`. If a custom `tokenProvider`\n * is used without specifying this value, automatic token refresh will be disabled.\n */\n tokenExpirationSeconds?: number;\n}\n\nexport interface RealtimeClient {\n /**\n * Connect to the realtime endpoint. The default implementation uses\n * WebSockets to connect to fal function endpoints that support WSS.\n *\n * @param app the app alias or identifier.\n * @param handler the connection handler.\n */\n connect<Input = any, Output = any>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input>;\n}\n\ntype RealtimeUrlParams = {\n token: string;\n maxBuffering?: number;\n path?: string;\n};\n\nfunction buildRealtimeUrl(\n app: string,\n { token, maxBuffering, path }: RealtimeUrlParams,\n): string {\n if (maxBuffering !== undefined && (maxBuffering < 1 || maxBuffering > 60)) {\n throw new Error(\"The `maxBuffering` must be between 1 and 60 (inclusive)\");\n }\n const queryParams = new URLSearchParams({\n fal_jwt_token: token,\n });\n if (maxBuffering !== undefined) {\n queryParams.set(\"max_buffering\", maxBuffering.toFixed(0));\n }\n const appId = ensureEndpointIdFormat(app);\n const normalizedPath = path ? `/${path.replace(/^\\/+/, \"\")}` : \"/realtime\";\n return `wss://fal.run/${appId}${normalizedPath}?${queryParams.toString()}`;\n}\n\nconst DEFAULT_THROTTLE_INTERVAL = 128;\n\nfunction isUnauthorizedError(message: any): boolean {\n // TODO we need better protocol definition with error codes\n return message[\"status\"] === \"error\" && message[\"error\"] === \"Unauthorized\";\n}\n\n/**\n * See https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1\n */\nconst WebSocketErrorCodes = {\n NORMAL_CLOSURE: 1000,\n GOING_AWAY: 1001,\n};\n\ntype ConnectionStateMachine = Service<typeof connectionStateMachine> & {\n throttledSend: (\n event: Event,\n payload?: any,\n ) => void | Promise<void> | undefined;\n};\n\ntype ConnectionOnChange = InterpretOnChangeFunction<\n typeof connectionStateMachine\n>;\n\ntype RealtimeConnectionCallback = Pick<\n RealtimeConnectionHandler<any>,\n \"onResult\" | \"onError\" | \"decodeMessage\"\n>;\n\nconst connectionCache = new Map<string, ConnectionStateMachine>();\nconst connectionCallbacks = new Map<string, RealtimeConnectionCallback>();\nfunction reuseInterpreter(\n key: string,\n throttleInterval: number,\n onChange: ConnectionOnChange,\n) {\n if (!connectionCache.has(key)) {\n const machine = interpret(connectionStateMachine, onChange);\n connectionCache.set(key, {\n ...machine,\n throttledSend:\n throttleInterval > 0\n ? throttle(machine.send, throttleInterval, true)\n : machine.send,\n });\n }\n return connectionCache.get(key) as ConnectionStateMachine;\n}\n\nconst noop = () => {\n /* No-op */\n};\n\n/**\n * A no-op connection that does not send any message.\n * Useful on the frameworks that reuse code for both ssr and csr (e.g. Next)\n * so the call when doing ssr has no side-effects.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NoOpConnection: RealtimeConnection<any> = {\n send: noop,\n close: noop,\n};\n\nfunction isSuccessfulResult(data: any): boolean {\n return (\n data.status !== \"error\" &&\n data.type !== \"x-fal-message\" &&\n !isFalErrorResult(data)\n );\n}\n\ntype FalErrorResult = {\n type: \"x-fal-error\";\n error: string;\n reason: string;\n};\n\nfunction isFalErrorResult(data: any): data is FalErrorResult {\n return data.type === \"x-fal-error\";\n}\n\ntype RealtimeClientDependencies = {\n config: RequiredConfig;\n};\n\nasync function decodeRealtimeMessage(data: any): Promise<any> {\n if (typeof data === \"string\") {\n return JSON.parse(data);\n }\n\n const toUint8Array = async (\n value: ArrayBuffer | Uint8Array | Blob,\n ): Promise<Uint8Array> => {\n if (value instanceof Uint8Array) {\n return value;\n }\n if (value instanceof Blob) {\n return new Uint8Array(await value.arrayBuffer());\n }\n return new Uint8Array(value);\n };\n\n if (data instanceof ArrayBuffer || data instanceof Uint8Array) {\n return decode(await toUint8Array(data));\n }\n if (data instanceof Blob) {\n return decode(await toUint8Array(data));\n }\n\n return data;\n}\n\nfunction encodeRealtimeMessage(input: any): Uint8Array | string {\n if (input instanceof Uint8Array) {\n return input;\n }\n if (typeof input === \"string\") {\n return encode(input);\n }\n return encode(input);\n}\n\ntype HandleRealtimeMessageParams = {\n data: any;\n decodeMessage: RealtimeConnectionCallback[\"decodeMessage\"];\n onResult: RealtimeConnectionCallback[\"onResult\"];\n onError: NonNullable<RealtimeConnectionCallback[\"onError\"]> | typeof noop;\n send: ConnectionStateMachine[\"send\"];\n};\n\nfunction handleRealtimeMessage({\n data,\n decodeMessage,\n onResult,\n onError,\n send,\n}: HandleRealtimeMessageParams) {\n const handleDecoded = (decoded: any) => {\n // Drop messages that are not related to the actual result.\n // In the future, we might want to handle other types of messages.\n // TODO: specify the fal ws protocol format\n if (isUnauthorizedError(decoded)) {\n send({\n type: \"unauthorized\",\n error: new Error(\"Unauthorized\"),\n });\n return;\n }\n if (isSuccessfulResult(decoded)) {\n onResult(decoded);\n return;\n }\n if (isFalErrorResult(decoded)) {\n if (decoded.error === \"TIMEOUT\") {\n // Timeout error messages just indicate that the connection hasn't\n // received an incoming message for a while. We don't need to\n // handle them as errors.\n return;\n }\n onError(\n new ApiError({\n message: `${decoded.error}: ${decoded.reason}`,\n // TODO better error status code\n status: 400,\n body: decoded,\n }),\n );\n return;\n }\n };\n\n Promise.resolve(decodeMessage ? decodeMessage(data) : data)\n .then(handleDecoded)\n .catch((error) => {\n onError(\n new ApiError({\n message:\n (error as Error)?.message ?? \"Failed to decode realtime message\",\n status: 400,\n }),\n );\n });\n}\n\nexport function createRealtimeClient({\n config,\n}: RealtimeClientDependencies): RealtimeClient {\n return {\n connect<Input, Output>(\n app: string,\n handler: RealtimeConnectionHandler<Output>,\n ): RealtimeConnection<Input> {\n const {\n // if running on React in the server, set clientOnly to true by default\n clientOnly = isReact() && !isBrowser(),\n connectionKey = crypto.randomUUID(),\n maxBuffering,\n path,\n throttleInterval = DEFAULT_THROTTLE_INTERVAL,\n encodeMessage: encodeMessageOverride,\n decodeMessage: decodeMessageOverride,\n tokenProvider,\n tokenExpirationSeconds,\n } = handler;\n if (clientOnly && !isBrowser()) {\n return NoOpConnection;\n }\n\n const encodeMessageFn =\n encodeMessageOverride ?? ((input: any) => encodeRealtimeMessage(input));\n const decodeMessageFn =\n decodeMessageOverride ?? ((data: any) => decodeRealtimeMessage(data));\n\n let previousState: string | undefined;\n let latestEnqueuedMessage: any;\n\n // Although the state machine is cached so we don't open multiple connections,\n // we still need to update the callbacks so we can call the correct references\n // when the state machine is reused. This is needed because the callbacks\n // are passed as part of the handler object, which can be different across\n // different calls to `connect`.\n connectionCallbacks.set(connectionKey, {\n decodeMessage: decodeMessageFn,\n onError: handler.onError,\n onResult: handler.onResult,\n });\n const getCallbacks = () =>\n connectionCallbacks.get(connectionKey) as RealtimeConnectionCallback;\n const stateMachine = reuseInterpreter(\n connectionKey,\n throttleInterval,\n ({ context, machine, send }) => {\n const { enqueuedMessage, token, websocket } = context;\n latestEnqueuedMessage = enqueuedMessage;\n if (\n machine.current === \"active\" &&\n enqueuedMessage &&\n websocket?.readyState === WebSocket.OPEN\n ) {\n send({ type: \"send\", message: enqueuedMessage });\n }\n if (\n machine.current === \"authRequired\" &&\n token === undefined &&\n previousState !== machine.current\n ) {\n send({ type: \"initiateAuth\" });\n // Use custom tokenProvider if provided, otherwise use default\n const fetchToken = tokenProvider\n ? () => tokenProvider(app)\n : () => {\n console.warn(\n \"[fal.realtime] Using the default token provider is deprecated. \" +\n \"Please provide a `tokenProvider` function to `fal.realtime.connect()`. \" +\n \"See https://docs.fal.ai/fal-client/authentication for more information.\",\n );\n return getTemporaryAuthToken(app, config);\n };\n\n fetchToken()\n .then((token) => {\n send({ type: \"authenticated\", token });\n // Only schedule token refresh if we know the expiration time.\n // For custom tokenProvider without tokenExpirationSeconds, skip auto-refresh.\n const effectiveExpiration = tokenProvider\n ? tokenExpirationSeconds\n : TOKEN_EXPIRATION_SECONDS;\n if (effectiveExpiration !== undefined) {\n const tokenRefreshInterval = Math.round(\n effectiveExpiration * 0.9 * 1000,\n );\n setTimeout(() => {\n send({ type: \"expireToken\" });\n }, tokenRefreshInterval);\n }\n })\n .catch((error) => {\n send({ type: \"unauthorized\", error });\n });\n }\n if (\n machine.current === \"connecting\" &&\n previousState !== machine.current &&\n token !== undefined\n ) {\n const ws = new WebSocket(\n buildRealtimeUrl(app, { token, maxBuffering, path }),\n );\n ws.onopen = () => {\n send({ type: \"connected\", websocket: ws });\n const queued =\n (stateMachine as any).context?.enqueuedMessage ??\n latestEnqueuedMessage;\n if (queued) {\n ws.send(encodeMessageFn(queued));\n (stateMachine as any).context = {\n ...(stateMachine as any).context,\n enqueuedMessage: undefined,\n };\n }\n };\n ws.onclose = (event) => {\n if (event.code !== WebSocketErrorCodes.NORMAL_CLOSURE) {\n const { onError = noop } = getCallbacks();\n onError(\n new ApiError({\n message: `Error closing the connection: ${event.reason}`,\n status: event.code,\n }),\n );\n }\n send({ type: \"connectionClosed\", code: event.code });\n };\n ws.onerror = (event) => {\n // TODO specify error protocol for identified errors\n const { onError = noop } = getCallbacks();\n onError(new ApiError({ message: \"Unknown error\", status: 500 }));\n };\n ws.onmessage = (event) => {\n const {\n decodeMessage = decodeMessageFn,\n onResult,\n onError = noop,\n } = getCallbacks();\n\n handleRealtimeMessage({\n data: event.data,\n decodeMessage,\n onResult,\n onError,\n send,\n });\n };\n }\n previousState = machine.current;\n },\n );\n\n const send = (input: Input & Partial<WithRequestId>) => {\n // Use throttled send to avoid sending too many messages\n stateMachine.throttledSend({\n type: \"send\",\n message: encodeMessageFn(input),\n });\n };\n\n const close = () => {\n stateMachine.send({ type: \"close\" });\n };\n\n return {\n send,\n close,\n };\n },\n };\n}\n", "import { Config, createConfig } from \"./config\";\nimport { buildTimeoutHeaders } from \"./headers\";\nimport { createQueueClient, QueueClient, QueueSubscribeOptions } from \"./queue\";\nimport { createRealtimeClient, RealtimeClient } from \"./realtime\";\nimport { buildUrl, dispatchRequest } from \"./request\";\nimport { resultResponseHandler } from \"./response\";\nimport {\n buildObjectLifecycleHeaders,\n createStorageClient,\n StorageClient,\n} from \"./storage\";\nimport { createStreamingClient, StreamingClient } from \"./streaming\";\nimport { EndpointType, InputType, OutputType } from \"./types/client\";\nimport { Result, RunOptions } from \"./types/common\";\n\n/**\n * The main client type, it provides access to simple API model usage,\n * as well as access to the `queue` and `storage` APIs.\n *\n * @see createFalClient\n */\nexport interface FalClient {\n /**\n * The queue client to interact with the queue API.\n */\n readonly queue: QueueClient;\n\n /**\n * The realtime client to interact with the realtime API\n * and receive updates in real-time.\n * @see #RealtimeClient\n * @see #RealtimeClient.connect\n */\n readonly realtime: RealtimeClient;\n\n /**\n * The storage client to interact with the storage API.\n */\n readonly storage: StorageClient;\n\n /**\n * The streaming client to interact with the streaming API.\n * @see #stream\n */\n readonly streaming: StreamingClient;\n\n /**\n * Runs a fal endpoint identified by its `endpointId`.\n *\n * @param endpointId The endpoint id, e.g. `fal-ai/fast-sdxl`.\n * @param options The request options, including the input payload.\n * @returns A promise that resolves to the result of the request once it's completed.\n *\n * @note\n * We **do not recommend** this use for most use cases as it will block the client\n * until the response is received. Moreover, if the connection is closed before\n * the response is received, the request will be lost. Instead, we recommend\n * using the `subscribe` method for most use cases.\n */\n run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Subscribes to updates for a specific request in the queue.\n *\n * @param endpointId - The ID of the API endpoint.\n * @param options - Options to configure how the request is run and how updates are received.\n * @returns A promise that resolves to the result of the request once it's completed.\n */\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> & QueueSubscribeOptions,\n ): Promise<Result<OutputType<Id>>>;\n\n /**\n * Calls a fal app that supports streaming and provides a streaming-capable\n * object as a result, that can be used to get partial results through either\n * `AsyncIterator` or through an event listener.\n *\n * @param endpointId the endpoint id, e.g. `fal-ai/llavav15-13b`.\n * @param options the request options, including the input payload.\n * @returns the `FalStream` instance.\n */\n stream: StreamingClient[\"stream\"];\n}\n\n/**\n * Creates a new reference of the `FalClient`.\n * @param userConfig Optional configuration to override the default settings.\n * @returns a new instance of the `FalClient`.\n */\nexport function createFalClient(userConfig: Config = {}): FalClient {\n const config = createConfig(userConfig);\n const storage = createStorageClient({ config });\n const queue = createQueueClient({ config, storage });\n const streaming = createStreamingClient({ config, storage });\n const realtime = createRealtimeClient({ config });\n return {\n queue,\n realtime,\n storage,\n streaming,\n stream: streaming.stream,\n async run<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>> = {},\n ): Promise<Result<OutputType<Id>>> {\n const input = options.input\n ? await storage.transformInput(options.input)\n : undefined;\n return dispatchRequest<InputType<Id>, Result<OutputType<Id>>>({\n method: options.method,\n targetUrl: buildUrl(endpointId, options),\n input: input as InputType<Id>,\n // TODO: consider supporting custom headers in fal.run() as well\n headers: {\n ...buildObjectLifecycleHeaders(options.storageSettings),\n ...buildTimeoutHeaders(options.startTimeout),\n },\n config: {\n ...config,\n responseHandler: resultResponseHandler,\n },\n options: {\n signal: options.abortSignal,\n retry: {\n maxRetries: 3,\n baseDelay: 500,\n maxDelay: 15000,\n },\n },\n });\n },\n subscribe: async (endpointId, options) => {\n const { request_id: requestId } = await queue.submit(endpointId, options);\n if (options.onEnqueue) {\n options.onEnqueue(requestId);\n }\n await queue.subscribeToStatus(endpointId, { requestId, ...options });\n return queue.result(endpointId, { requestId });\n },\n };\n}\n", "import type { StorageSettings } from \"../storage\";\n\n/**\n * Represents an API result, containing the data,\n * the request ID and any other relevant information.\n */\nexport type Result<T> = {\n data: T;\n requestId: string;\n};\n\n/**\n * The function input and other configuration when running\n * the function, such as the HTTP method to use.\n */\nexport type RunOptions<Input> = {\n /**\n * The function input. It will be submitted either as query params\n * or the body payload, depending on the `method`.\n */\n readonly input?: Input;\n\n /**\n * The HTTP method, defaults to `post`;\n */\n readonly method?: \"get\" | \"post\" | \"put\" | \"delete\" | string;\n\n /**\n * The abort signal to cancel the request.\n */\n readonly abortSignal?: AbortSignal;\n\n /**\n * Object lifecycle configuration for controlling how long generated objects\n * (images, files, etc.) remain available before expiring.\n *\n * @see StorageSettings\n * @see https://docs.fal.ai/model-apis/model-endpoints/queue#object-lifecycle\n */\n readonly storageSettings?: StorageSettings;\n\n /**\n * Server-side request timeout in seconds. Limits total time spent waiting\n * before processing starts (includes queue wait, retries, and routing).\n * Does not apply once the application begins processing.\n *\n * This will be sent as the `x-fal-request-timeout` header.\n */\n readonly startTimeout?: number;\n};\n\nexport type UrlOptions = {\n /**\n * If `true`, the function will use the queue to run the function\n * asynchronously and return the result in a separate call. This\n * influences how the URL is built.\n */\n readonly subdomain?: string;\n\n /**\n * The query parameters to include in the URL.\n */\n readonly query?: Record<string, string>;\n\n /**\n * The path to append to the function URL.\n */\n path?: string;\n};\n\nexport type RequestLog = {\n message: string;\n level: \"STDERR\" | \"STDOUT\" | \"ERROR\" | \"INFO\" | \"WARN\" | \"DEBUG\";\n source: \"USER\";\n timestamp: string; // Using string to represent date-time format, but you could also use 'Date' type if you're going to construct Date objects.\n};\n\nexport type Metrics = {\n inference_time: number | null;\n};\n\ninterface BaseQueueStatus {\n status: \"IN_QUEUE\" | \"IN_PROGRESS\" | \"COMPLETED\";\n request_id: string;\n response_url: string;\n status_url: string;\n cancel_url: string;\n}\n\nexport interface InQueueQueueStatus extends BaseQueueStatus {\n status: \"IN_QUEUE\";\n queue_position: number;\n}\n\nexport interface InProgressQueueStatus extends BaseQueueStatus {\n status: \"IN_PROGRESS\";\n logs: RequestLog[];\n}\n\nexport interface CompletedQueueStatus extends BaseQueueStatus {\n status: \"COMPLETED\";\n logs: RequestLog[];\n metrics?: Metrics;\n}\n\nexport type QueueStatus =\n | InProgressQueueStatus\n | CompletedQueueStatus\n | InQueueQueueStatus;\n\nexport function isQueueStatus(obj: any): obj is QueueStatus {\n return obj && obj.status && obj.response_url;\n}\n\nexport function isCompletedQueueStatus(obj: any): obj is CompletedQueueStatus {\n return isQueueStatus(obj) && obj.status === \"COMPLETED\";\n}\n\nexport type ValidationErrorInfo = {\n msg: string;\n loc: Array<string | number>;\n type: string;\n};\n\n/**\n * Represents the response from a WebHook request.\n * This is a union type that varies based on the `status` property.\n *\n * @template Payload - The type of the payload in the response. It defaults to `any`,\n * allowing for flexibility in specifying the structure of the payload.\n */\nexport type WebHookResponse<Payload = any> =\n | {\n /** Indicates a successful response. */\n status: \"OK\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Error is never present in a successful response. */\n error: never;\n /** The unique identifier for the request. */\n request_id: string;\n }\n | {\n /** Indicates an unsuccessful response. */\n status: \"ERROR\";\n /** The payload of the response, structure determined by the Payload type. */\n payload: Payload;\n /** Description of the error that occurred. */\n error: string;\n /** The unique identifier for the request. */\n request_id: string;\n };\n", "import { createFalClient, type FalClient } from \"./client\";\nimport { Config } from \"./config\";\nimport { StreamOptions } from \"./streaming\";\nimport { EndpointType, InputType } from \"./types/client\";\nimport { RunOptions } from \"./types/common\";\n\nexport type { TokenProvider } from \"./auth\";\nexport { createFalClient, type FalClient } from \"./client\";\nexport { withMiddleware, withProxy } from \"./middleware\";\nexport type { RequestMiddleware } from \"./middleware\";\nexport type { QueueClient } from \"./queue\";\nexport type { RealtimeClient } from \"./realtime\";\nexport { ApiError, ValidationError } from \"./response\";\nexport type { ResponseHandler } from \"./response\";\nexport { isRetryableError } from \"./retry\";\nexport type { RetryOptions } from \"./retry\";\nexport type { StorageClient, StorageSettings } from \"./storage\";\nexport type { FalStream, StreamingClient } from \"./streaming\";\nexport type { OutputType } from \"./types/client\";\nexport * from \"./types/common\";\nexport type {\n QueueStatus,\n ValidationErrorInfo,\n WebHookResponse,\n} from \"./types/common\";\nexport { parseEndpointId } from \"./utils\";\n\ntype SingletonFalClient = {\n config(config: Config): void;\n} & FalClient;\n\n/**\n * Creates a singleton instance of the client. This is useful as a compatibility\n * layer for existing code that uses the clients version prior to 1.0.0.\n */\nexport const fal: SingletonFalClient = (function createSingletonFalClient() {\n let currentInstance: FalClient = createFalClient();\n return {\n config(config: Config) {\n currentInstance = createFalClient(config);\n },\n get queue() {\n return currentInstance.queue;\n },\n get realtime() {\n return currentInstance.realtime;\n },\n get storage() {\n return currentInstance.storage;\n },\n get streaming() {\n return currentInstance.streaming;\n },\n run<Id extends EndpointType>(id: Id, options: RunOptions<InputType<Id>>) {\n return currentInstance.run<Id>(id, options);\n },\n subscribe<Id extends EndpointType>(\n endpointId: Id,\n options: RunOptions<InputType<Id>>,\n ) {\n return currentInstance.subscribe<Id>(endpointId, options);\n },\n stream<Id extends EndpointType>(\n endpointId: Id,\n options: StreamOptions<InputType<Id>>,\n ) {\n return currentInstance.stream<Id>(endpointId, options);\n },\n } satisfies SingletonFalClient;\n})();\n", "/**\n * A single word with timing information, as returned by ElevenLabs-style\n * speech-to-text APIs (both via fal.ai and the direct ElevenLabs API).\n */\nexport interface TimedWord {\n text: string;\n start: number;\n end: number;\n type: 'word' | 'spacing' | 'audio_event';\n}\n\ninterface WordsToSrtOptions {\n /** Max characters per SRT line (default: 37) */\n maxLineLength?: number;\n /** Max lines per SRT cue (default: 2) */\n maxLines?: number;\n}\n\n/**\n * Converts an array of timed words into an SRT-formatted string.\n *\n * Groups words into cues respecting maxLineLength and maxLines constraints,\n * using the first word's start and last word's end as the cue timestamps.\n */\nexport function wordsToSrt(\n words: TimedWord[],\n options?: WordsToSrtOptions\n): string {\n const maxLineLength = options?.maxLineLength ?? 37;\n const maxLines = options?.maxLines ?? 1;\n\n const onlyWords = words.filter((w) => w.type === 'word');\n if (onlyWords.length === 0) return '';\n\n const cues = groupWordsIntoCues(onlyWords, maxLineLength, maxLines);\n\n return cues\n .map((cue, index) => {\n const seq = index + 1;\n const start = formatSrtTimestamp(cue.start);\n const end = formatSrtTimestamp(cue.end);\n return `${seq}\\n${start} --> ${end}\\n${cue.text}`;\n })\n .join('\\n\\n');\n}\n\ninterface Cue {\n start: number;\n end: number;\n text: string;\n}\n\nfunction groupWordsIntoCues(\n words: TimedWord[],\n maxLineLength: number,\n maxLines: number\n): Cue[] {\n const cues: Cue[] = [];\n let cueWords: TimedWord[] = [];\n let lines: string[] = [];\n let currentLine = '';\n\n const flushCue = () => {\n if (cueWords.length === 0) return;\n\n // Push any remaining line\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n cues.push({\n start: cueWords[0].start,\n end: cueWords[cueWords.length - 1].end,\n text: lines.join('\\n')\n });\n\n cueWords = [];\n lines = [];\n currentLine = '';\n };\n\n for (const word of words) {\n const candidate =\n currentLine.length === 0 ? word.text : `${currentLine} ${word.text}`;\n\n if (candidate.length > maxLineLength && currentLine.length > 0) {\n // Current line is full\n lines.push(currentLine);\n currentLine = '';\n\n if (lines.length >= maxLines) {\n // Cue is full \u2014 flush before starting this word\n flushCue();\n currentLine = word.text;\n cueWords = [word];\n } else {\n currentLine = word.text;\n cueWords.push(word);\n }\n } else {\n currentLine = candidate;\n cueWords.push(word);\n }\n }\n\n flushCue();\n return cues;\n}\n\n/**\n * Formats seconds into SRT timestamp format: HH:MM:SS,mmm\n */\nfunction formatSrtTimestamp(seconds: number): string {\n const totalMs = Math.round(seconds * 1000);\n const ms = totalMs % 1000;\n const totalSec = Math.floor(totalMs / 1000);\n const s = totalSec % 60;\n const totalMin = Math.floor(totalSec / 60);\n const m = totalMin % 60;\n const h = Math.floor(totalMin / 60);\n\n return (\n `${h.toString().padStart(2, '0')}:` +\n `${m.toString().padStart(2, '0')}:` +\n `${s.toString().padStart(2, '0')},` +\n `${ms.toString().padStart(3, '0')}`\n );\n}\n", "import {\n createFalClient as createClient,\n type FalClient as FalClientType\n} from '@fal-ai/client';\n\nexport type FalClient = FalClientType;\n\nexport function createFalClient(\n proxyUrl: string,\n headers?: Record<string, string>\n): FalClient {\n const client = createClient({\n proxyUrl,\n requestMiddleware: async (request) => {\n return {\n ...request,\n headers: {\n ...request.headers,\n ...(headers ?? {})\n }\n };\n }\n });\n\n return client;\n}\n", "import type {\n TranscriptionOptions,\n TranscriptionProvider,\n TranscriptionResult\n} from '../TranscriptionProvider';\nimport { wordsToSrt } from '../wordsToSrt';\nimport type { TimedWord } from '../wordsToSrt';\nimport { createFalClient } from './createFalClient';\n\nconst FAL_ELEVENLABS_SCRIBE_V2_MODEL =\n 'fal-ai/elevenlabs/speech-to-text/scribe-v2';\n\nexport interface FalElevenLabsConfig {\n /**\n * URL of a proxy server that forwards requests to fal.ai.\n * The proxy is responsible for adding the fal.ai API key.\n */\n proxyUrl: string;\n /** Optional additional headers to include in requests. */\n headers?: Record<string, string>;\n}\n\ninterface ElevenLabsWord {\n text: string;\n start: number;\n end: number;\n type: 'word' | 'spacing' | 'audio_event';\n speaker_id: string;\n}\n\ninterface ElevenLabsTranscribeResponse {\n text: string;\n language_code: string;\n language_probability: number;\n words: ElevenLabsWord[];\n}\n\n/**\n * Creates a transcription provider that uses fal.ai to run the ElevenLabs\n * Scribe V2 speech-to-text model.\n *\n * Uploads the audio blob to fal storage, runs the model, and converts the\n * word-level response into SRT format.\n */\nexport function ElevenLabsScribeV2(\n config: FalElevenLabsConfig\n): TranscriptionProvider {\n const client = createFalClient(config.proxyUrl, config.headers);\n\n return {\n name: 'ElevenLabs Scribe V2',\n\n async transcribe(\n audio: Blob,\n options?: TranscriptionOptions\n ): Promise<TranscriptionResult> {\n // eslint-disable-next-line no-console\n const log = options?.debug ? console.log.bind(console) : () => {};\n log(\n `[ElevenLabsScribeV2] Uploading ${audio.size} byte blob to fal storage...`\n );\n // Wrap as a File with .m4a extension so fal storage doesn't use .mp4,\n // which ElevenLabs rejects as an unsupported audio format.\n const file = new File([audio], 'audio.m4a', { type: audio.type });\n const audioUrl = await client.storage.upload(file);\n log(`[ElevenLabsScribeV2] Upload complete: ${audioUrl}`);\n\n options?.abortSignal?.throwIfAborted();\n\n const input: Record<string, unknown> = { audio_url: audioUrl };\n if (options?.language) {\n input.language_code = options.language;\n }\n\n log(\n `[ElevenLabsScribeV2] Running ${FAL_ELEVENLABS_SCRIBE_V2_MODEL} (language_code=${\n options?.language ?? 'auto'\n })`\n );\n\n const result = await client.run(FAL_ELEVENLABS_SCRIBE_V2_MODEL, {\n input,\n abortSignal: options?.abortSignal\n });\n\n const data = result.data as ElevenLabsTranscribeResponse;\n const wordCount = data.words.filter((w) => w.type === 'word').length;\n log(\n `[ElevenLabsScribeV2] Received ${wordCount} words, detected language: ${\n data.language_code\n } (confidence: ${data.language_probability.toFixed(2)})`\n );\n\n const timedWords: TimedWord[] = data.words.map((w) => ({\n text: w.text,\n start: w.start,\n end: w.end,\n type: w.type\n }));\n\n const srt = wordsToSrt(timedWords, {\n maxLineLength: options?.maxLineLength,\n maxLines: options?.maxLines\n });\n\n log(`[ElevenLabsScribeV2] Generated SRT (${srt.length} chars)`);\n return { srt };\n }\n };\n}\n"],
5
+ "mappings": "o8BAyBAA,EAAA,eAAAC,GAqBAD,EAAA,UAAAE,GArBA,SAAgBD,MACXE,EAAgC,CAEnC,IAAMC,EAAaC,GACjB,OAAOA,GAAe,WAExB,OAAcC,GAAyBC,GAAA,KAAA,OAAA,OAAA,WAAA,CACrC,IAAIC,EAAa,OAAA,OAAA,CAAA,EAAQF,CAAM,EAC/B,QAAWD,KAAcF,EAAY,OAAOC,CAAS,EACnDI,EAAgB,MAAMH,EAAWG,CAAa,EAEhD,OAAOA,CACT,CAAC,CACH,CAMaR,EAAA,kBAAoB,mBAEjC,SAAgBE,GAAUI,EAA0B,CAClD,IAAMG,EAAeC,GACnB,QAAQ,QAAQA,CAAa,EAE/B,OAAI,OAAO,OAAW,IACbD,EA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"__awaiter", "currentConfig", "passthrough", "requestConfig", "exports", "validateTimeoutHeader", "buildTimeoutHeaders", "timeout", "exports", "defaultResponseHandler", "resultResponseHandler", "headers_1", "REQUEST_ID_HEADER", "ApiError", "message", "status", "body", "requestId", "timeoutType", "ValidationError", "args", "field", "error", "response", "statusText", "contentType", "_a", "ErrorType", "exports", "ensureEndpointIdFormat", "parseEndpointId", "isValidUrl", "throttle", "isReact", "isPlainObject", "sleep", "id", "appOwner", "appId", "ENDPOINT_NAMESPACES", "parts", "url", "host", "func", "limit", "leading", "lastFunc", "lastRan", "args", "isRunningInReact", "stack", "value", "ms", "resolve", "exports", "isRetryableError", "calculateBackoffDelay", "executeWithRetry", "response_1", "utils_1", "error", "retryableStatusCodes", "attempt", "baseDelay", "maxDelay", "backoffMultiplier", "enableJitter", "exponentialDelay", "jitter", "operation", "options", "onRetry", "metrics", "lastError", "delay", "require_package", "__commonJSMin", "exports", "module", "exports", "isBrowser", "getUserAgent", "memoizedUserAgent", "packageInfo", "exports", "resolveDefaultFetch", "createConfig", "getRestApiUrl", "middleware_1", "response_1", "retry_1", "runtime_1", "hasEnvVariables", "credentialsFromEnv", "DEFAULT_CONFIG", "request", "config", "configuration", "_a", "resolveCredentials", "suppressLocalCredentialsWarning", "credentials", "exports", "dispatchRequest", "buildUrl", "retry_1", "runtime_1", "utils_1", "isCloudflareWorkers", "params", "targetUrl", "input", "config", "options", "credentialsValue", "requestMiddleware", "responseHandler", "fetch", "retryOptions", "executeRequest", "__awaiter", "userAgent", "credentials", "method", "url", "headers", "_b", "_a", "authHeader", "requestHeaders", "customResponseHandler", "_", "requestInit", "__rest", "response", "_c", "lastError", "attempt", "error", "delay", "id", "path", "queryParams", "appId", "exports", "getExpirationDurationSeconds", "buildObjectLifecycleHeaders", "createStorageClient", "config_1", "request_1", "utils_1", "EXPIRATION_VALUES", "lifecycle", "expiresIn", "expirationDurationSeconds", "getExtensionFromContentType", "contentType", "fileType", "_a", "initiateUpload", "file", "config", "filename", "headers", "lifecycleConfig", "initiateMultipartUpload", "partUploadRetries", "uploadUrl_1", "chunk_1", "config_2", "uploadUrl", "chunk", "tries", "fetch", "responseHandler", "response", "multipartUpload", "url", "chunkSize", "chunks", "parsedUrl", "responses", "i", "start", "end", "partNumber", "partUploadUrl", "completeUrl", "mpart", "ref", "options", "__awaiter", "input", "item", "promises", "key", "value", "results", "createParser", "onParse", "isFirstChunk", "buffer", "startingPosition", "startingFieldLength", "eventId", "eventName", "data", "reset", "feed", "chunk", "hasBom", "slice", "BOM", "length", "position", "discardTrailingNewline", "lineLength", "fieldLength", "character", "index", "parseEventStreamLine", "lineBuffer", "type", "id", "event", "noValue", "field", "step", "valueLength", "value", "toString", "concat", "includes", "retry", "parseInt", "Number", "isNaN", "every", "charCode", "charCodeAt", "exports", "getTemporaryAuthToken", "config_1", "request_1", "utils_1", "app", "config", "appId", "token", "exports", "createStreamingClient", "eventsource_parser_1", "auth_1", "request_1", "response_1", "CONTENT_TYPE_EVENT_STREAM", "EVENT_STREAM_TIMEOUT", "FalStream", "endpointId", "config", "options", "__awaiter", "input", "method", "connectionMode", "tokenProvider", "token", "fetch", "parsedUrl", "response", "_a", "_b", "error", "body", "reader", "emitRawChunk", "done", "value", "decoder", "parser", "event", "data", "parsedData", "e", "timeout", "readPartialResponse", "apiError", "type", "listener", "listeners", "reason", "resolve", "reject", "running", "stopAsyncIterator", "__await", "storage", "headers_1", "request_1", "response_1", "retry_1", "storage_1", "streaming_1", "utils_1", "DEFAULT_POLL_INTERVAL", "QUEUE_RETRY_CONFIG", "QUEUE_STATUS_RETRY_CONFIG", "createQueueClient", "config", "storage", "ref", "endpointId", "options", "webhookUrl", "priority", "hint", "startTimeout", "headers", "storageSettings", "runOptions", "__rest", "input", "extraHeaders", "key", "value", "endpointId_1", "_a", "requestId", "logs", "abortSignal", "appId", "prefix", "connectionMode", "queryParams", "url", "timeout", "timeoutId", "handleCancelError", "status", "data", "doneStatus", "resolve", "reject", "pollingTimeoutId", "pollInterval", "clearScheduledTasks", "poll", "__awaiter", "requestStatus", "error", "exports", "utf8Count", "str", "strLength", "byteLength", "pos", "value", "extra", "utf8EncodeJs", "output", "outputOffset", "offset", "sharedTextEncoder", "TEXT_ENCODER_THRESHOLD", "utf8EncodeTE", "utf8Encode", "CHUNK_SIZE", "utf8DecodeJs", "bytes", "inputOffset", "end", "units", "result", "byte1", "byte2", "byte3", "byte4", "unit", "sharedTextDecoder", "TEXT_DECODER_THRESHOLD", "utf8DecodeTD", "stringBytes", "utf8Decode", "ExtData", "type", "data", "DecodeError", "_DecodeError", "message", "proto", "exports", "setUint64", "view", "offset", "value", "high", "low", "setInt64", "getInt64", "getUint64", "DecodeError_ts_1", "int_ts_1", "exports", "TIMESTAMP32_MAX_SEC", "TIMESTAMP64_MAX_SEC", "encodeTimeSpecToTimestamp", "sec", "nsec", "rv", "secHigh", "secLow", "view", "encodeDateToTimeSpec", "date", "msec", "nsecInSec", "encodeTimestampExtension", "object", "timeSpec", "decodeTimestampToTimeSpec", "data", "nsec30AndSecHigh2", "secLow32", "decodeTimestampExtension", "ExtData_ts_1", "timestamp_ts_1", "ExtensionCodec", "_ExtensionCodec", "type", "encode", "decode", "index", "object", "context", "i", "encodeExt", "data", "decodeExt", "isArrayBufferLike", "buffer", "ensureUint8Array", "utf8_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "typedArrays_ts_1", "exports", "Encoder", "_Encoder", "options", "object", "depth", "sizeToWrite", "requiredSize", "newSize", "newBuffer", "newBytes", "newView", "byteLength", "ext", "size", "bytes", "item", "keys", "count", "key", "value", "data", "values", "Encoder_ts_1", "encode", "value", "options", "prettyByte", "byte", "utf8_ts_1", "DEFAULT_MAX_KEY_LENGTH", "DEFAULT_MAX_LENGTH_PER_KEY", "CachedKeyDecoder", "maxKeyLength", "maxLengthPerKey", "i", "byteLength", "bytes", "inputOffset", "records", "FIND_CHUNK", "record", "recordBytes", "j", "value", "cachedValue", "str", "slicedCopyOfBytes", "prettyByte_ts_1", "ExtensionCodec_ts_1", "int_ts_1", "utf8_ts_1", "typedArrays_ts_1", "CachedKeyDecoder_ts_1", "DecodeError_ts_1", "STATE_ARRAY", "STATE_MAP_KEY", "STATE_MAP_VALUE", "mapKeyConverter", "key", "StackPool", "size", "state", "partialState", "HEAD_BYTE_REQUIRED", "EMPTY_VIEW", "EMPTY_BYTES", "e", "MORE_DATA", "sharedCachedKeyDecoder", "Decoder", "_Decoder", "options", "buffer", "bytes", "remainingData", "newData", "newBuffer", "posToShow", "view", "pos", "object", "stream", "decoded", "headByte", "totalPos", "isArray", "isArrayHeaderRequired", "arrayItemsLeft", "DECODE", "byteLength", "stack", "headerOffset", "offset", "headOffset", "extType", "data", "value", "Decoder_ts_1", "decode", "buffer", "options", "decodeMulti", "isAsyncIterable", "object", "asyncIterableFromStream", "stream", "reader", "done", "value", "ensureAsyncIterable", "streamLike", "Decoder_ts_1", "stream_ts_1", "decodeAsync", "streamLike", "options", "stream", "decodeArrayStream", "decodeMultiStream", "encode_ts_1", "decode_ts_1", "decodeAsync_ts_1", "Decoder_ts_1", "DecodeError_ts_1", "Encoder_ts_1", "ExtensionCodec_ts_1", "ExtData_ts_1", "timestamp_ts_1", "require_machine", "__commonJSMin", "exports", "valueEnumerable", "value", "valueEnumerableWritable", "d", "truthy", "empty", "identity", "a", "callBoth", "par", "fn", "self", "args", "callForward", "b", "create", "stack", "fns", "def", "caller", "fnType", "reduceType", "reduce", "action", "ctx", "ev", "guardType", "guard", "filter", "Type", "arr", "makeTransition", "from", "to", "guards", "t", "reducers", "transitionType", "immediateType", "transition", "immediate", "enterImmediate", "machine", "service", "event", "transitionTo", "transitionsToMap", "transitions", "m", "stateType", "state", "immediates", "desc", "invokeFnType", "machine2", "rn", "invokeMachineType", "data", "error", "interpret", "s", "invoke", "createMachine", "current", "states", "contextFn", "fromEvent", "candidates", "context", "original", "newMachine", "send", "eventName", "currentStateName", "onChange", "initialContext", "exports", "createRealtimeClient", "msgpack_1", "robot3_1", "auth_1", "response_1", "runtime_1", "utils_1", "initialState", "hasToken", "context", "noToken", "enqueueMessage", "event", "closeConnection", "sendMessage", "expireToken", "setToken", "connectionEstablished", "connectionStateMachine", "buildRealtimeUrl", "app", "token", "maxBuffering", "path", "queryParams", "appId", "normalizedPath", "DEFAULT_THROTTLE_INTERVAL", "isUnauthorizedError", "message", "WebSocketErrorCodes", "connectionCache", "connectionCallbacks", "reuseInterpreter", "key", "throttleInterval", "onChange", "machine", "noop", "NoOpConnection", "isSuccessfulResult", "data", "isFalErrorResult", "decodeRealtimeMessage", "toUint8Array", "value", "__awaiter", "encodeRealtimeMessage", "input", "handleRealtimeMessage", "decodeMessage", "onResult", "onError", "send", "handleDecoded", "decoded", "error", "_a", "config", "handler", "clientOnly", "connectionKey", "encodeMessageOverride", "decodeMessageOverride", "tokenProvider", "tokenExpirationSeconds", "encodeMessageFn", "decodeMessageFn", "previousState", "latestEnqueuedMessage", "getCallbacks", "stateMachine", "enqueuedMessage", "websocket", "effectiveExpiration", "tokenRefreshInterval", "ws", "queued", "_b", "exports", "createFalClient", "config_1", "headers_1", "queue_1", "realtime_1", "request_1", "response_1", "storage_1", "streaming_1", "userConfig", "config", "storage", "queue", "streaming", "realtime", "endpointId_1", "endpointId", "options", "input", "__awaiter", "requestId", "exports", "isQueueStatus", "isCompletedQueueStatus", "obj", "client_1", "client_2", "exports", "middleware_1", "response_1", "retry_1", "__exportStar", "utils_1", "currentInstance", "config", "id", "options", "endpointId", "wordsToSrt", "words", "options", "maxLineLength", "maxLines", "onlyWords", "w", "groupWordsIntoCues", "cue", "index", "seq", "start", "formatSrtTimestamp", "end", "cues", "cueWords", "lines", "currentLine", "flushCue", "word", "candidate", "seconds", "totalMs", "ms", "totalSec", "s", "totalMin", "m", "import_client", "createFalClient", "proxyUrl", "headers", "createClient", "request", "FAL_ELEVENLABS_SCRIBE_V2_MODEL", "ElevenLabsScribeV2", "config", "client", "createFalClient", "audio", "options", "log", "file", "audioUrl", "input", "data", "wordCount", "w", "timedWords", "srt", "wordsToSrt"]
7
+ }