Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/okikio/observables. A spec-faithful yet ergonomic TC39-inspired Observable library with detailed ty
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401/** * Utility helpers connect Observable pipelines with Web Streams and foreign * operator ecosystems. * * Most application code will use these indirectly through `pipe()`, * `fromStreamPair()`, or `fromObservableOperator()`. They live here so the * adapter logic stays reusable and the public helpers stay small. * * @module */import type { ObservableInteropInputLike, ObservableOperatorInterop, ObservableOperatorInteropOptions, TransformFunctionOptions, StreamPair, TransformStreamOptions,} from "./_types.ts";import type { CreateOperatorOptions, Operator } from "./_types.ts";import { ObservableError } from "../error.ts";import { Observable } from "../observable.ts";
/** * Returns `true` when operator options provide a `TransformStream` factory. */export function isTransformStreamOptions<T, R>( options: CreateOperatorOptions<T, R>,): options is TransformStreamOptions<T, R> { return "stream" in options;}
/** * Returns `true` when operator options provide a custom transform callback. */export function isTransformFunctionOptions<T, R>( options: CreateOperatorOptions<T, R>,): options is TransformFunctionOptions<T, R> { return "transform" in options;}
/** * Applies one operator to a stream and converts setup failures into injected * error values. */export function applyOperator( input: ReadableStream<unknown>, // deno-lint-ignore no-explicit-any operator: Operator<any, any>, { message = `pipe:operator` } = {},): ReadableStream<unknown> { try { const result = operator(input); return result; } catch (err) { return input.pipeThrough(injectError(err, message)); }}
/** * Converts an iterable or async iterable into a `ReadableStream`. */export function toStream<T>( iterable: Iterable<T> | AsyncIterable<T>,): ReadableStream<T | ObservableError> { // Check if it's an async iterable const isAsync = typeof (iterable as AsyncIterable<T>)[Symbol.asyncIterator] === "function";
return new ReadableStream<T | ObservableError>({ async start(controller) { try { if (isAsync) { for await (const item of iterable as AsyncIterable<T>) { controller.enqueue(item); } } else { for (const item of iterable as Iterable<T>) { controller.enqueue(item); } }
try { controller.close(); } catch { // Downstream may already be closed or errored. } } catch (err) { try { controller.enqueue(ObservableError.from(err, "toStream")); controller.close(); } catch { // If downstream is already unavailable, the original failure has // already decided the stream outcome. Do not surface a second error. } } }, });}
/** * Adapts a readable/writable stream pair into an Observable operator. * * Some platform transforms, such as `CompressionStream`, expose a writable side * and a readable side without being created through this library's operator * builders. This helper turns that pair into a normal `Operator` so it can be * used inside `pipe()` like any built-in operator. * * A fresh pair is created for each operator application. That preserves the * cold semantics of the surrounding Observable pipeline and avoids reusing a * consumed stream pair across subscriptions. * * @typeParam TIn - Chunk type written into the pair * @typeParam TOut - Chunk type read from the pair * @param createPair - Factory that returns a fresh readable/writable pair * @returns An operator that pipes input through the created pair * * @example * ```ts * const gzip = fromStreamPair<Uint8Array, Uint8Array>( * () => new CompressionStream('gzip') * ); * ``` */export function fromStreamPair<TIn, TOut>( createPair: () => StreamPair<TIn, TOut>,): Operator<TIn, TOut> { return (source) => source.pipeThrough(createPair());}
/** * Wraps a `ReadableStream` as an Observable so foreign Observable-style * operators can subscribe to it directly. * * This avoids first converting the stream into an async-iterable Observable via * `Observable.from()`, which would add an extra adaptation layer before the * foreign operator even starts running. */export function streamAsObservable<T>(stream: ReadableStream<T>): Observable<T> { return new Observable<T>((observer) => { const reader = stream.getReader(); let cancelled = false;
void (async () => { try { while (!cancelled && !observer.closed) { const { done, value } = await reader.read();
if (done) { break; }
observer.next(value); }
if (!cancelled && !observer.closed) { observer.complete(); } } catch (err) { if (!cancelled && !observer.closed) { observer.error(err); } } finally { try { reader.releaseLock(); } catch { // Releasing the reader is best-effort during teardown. } } })();
return () => { cancelled = true; void reader.cancel(); }; });}
/** * Returns true when a value exposes a direct `subscribe()` method. * * Many Observable libraries return subscribable objects that are usable without * first going through this library's `Observable.from()`. Detecting that shape * lets interop stay direct for outputs such as RxJS Observables. */function hasSubscribe<T>( input: ObservableInteropInputLike<T> | unknown,): input is { subscribe(observer: { next?(value: T): void; error?(error: unknown): void; complete?(): void; }): { unsubscribe?(): void } | void;} { return typeof input === "object" && input !== null && typeof (input as { subscribe?: unknown }).subscribe === "function";}
/** * Subscribes to an Observable-like output and exposes it as a ReadableStream. * * Foreign operators are allowed to return either a normal `Observable.from()` * input or a direct subscribable from another Observable implementation. * Converting the result with a direct subscription avoids the extra * async-generator and stream layers that `pull(...)+toStream()` would add. * * If the foreign subscribable throws during subscription setup, this bridge * converts that failure into an `ObservableError` value so downstream * consumers see the same buffered-error behavior as the rest of this library. */export function observableInputToStream<T>( input: ObservableInteropInputLike<T>, errorContext: string,): ReadableStream<T | ObservableError> { let subscription: { unsubscribe?(): void } | void; let settled = false;
return new ReadableStream<T | ObservableError>({ start(controller) { const source = hasSubscribe<T>(input) ? input : Observable.from(input);
try { const startedSubscription = source.subscribe({ next(value) { try { controller.enqueue(value); } catch { // Downstream cancellation already decided the stream outcome. } }, error(error) { settled = true;
try { controller.enqueue(ObservableError.from(error, errorContext)); controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } }, complete() { settled = true;
try { controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } }, });
subscription = settled ? undefined : startedSubscription; } catch (error) { settled = true;
try { controller.enqueue(ObservableError.from(error, errorContext)); controller.close(); } catch { // Downstream cancellation already decided the stream outcome. } finally { subscription = undefined; } } }, cancel() { subscription?.unsubscribe?.(); subscription = undefined; }, });}
/** * Adapts a foreign Observable-style operator into a stream operator. * * Libraries such as RxJS model operators as functions from one Observable-like * source to another Observable-like result. This helper bridges that shape into * this library's `Operator` contract by: * * 1. wrapping the input stream as an Observable-like source * 2. calling the foreign operator * 3. converting the resulting Observable-like output back into a stream * * The result keeps this library's buffered error behavior by converting the * foreign output into a `ReadableStream` that enqueues wrapped * `ObservableError` values instead of failing the readable side outright. * That includes synchronous setup failures when the foreign subscribable * throws from its `subscribe()` implementation. * * @typeParam TIn - Value type accepted by the foreign operator * @typeParam TOut - Value type produced by the foreign operator * @param operator - Foreign operator function to adapt * @returns An operator compatible with this library's `pipe()` * * @example * ```ts * const foreignTakeOne = fromObservableOperator<number, number>((source) => * rxTake(1)(source) * , { sourceAdapter: (source) => rxFrom(source) }); * ``` */export function fromObservableOperator<TIn, TOut, TSource = Observable<TIn>>( operator: ObservableOperatorInterop<TIn, TOut, TSource>, options?: ObservableOperatorInteropOptions<TIn, TSource>,): Operator<TIn, TOut | ObservableError> { return (source) => { const observableSource = streamAsObservable(source); const foreignSource = options?.sourceAdapter ? options.sourceAdapter(observableSource) : observableSource as unknown as TSource;
const output = operator(foreignSource) as ObservableInteropInputLike<TOut>;
return observableInputToStream( output, options?.errorContext ?? "operator:fromObservableOperator:output", ); };}
/** * Creates a TransformStream that injects an error at the start and passes through all original data. * * ## What this does * Think of this as creating a "tee" in your stream pipeline where an error gets injected at the * beginning, but all your original data continues to flow through unchanged. It's like adding * a warning sign at the start of a conveyor belt while keeping everything else moving. * * ## Why you need this * When operator setup fails, you want to signal the error but not lose all your data. This creates * a transform that does exactly that - it marks the problem but preserves your stream's content. * * ## How it works * The transform immediately outputs the error when the stream starts, then passes every chunk * from the source unchanged. Your downstream consumers see the error first, then all the data. * * ## When to use this * - **Operator setup failures**: When building an operator fails but the source data is still valid * - **Warning injection**: When you want to flag a problem but continue processing * - **Error preservation**: When you need both error information and data preservation * * ## What the output looks like * ```typescript * // Original stream: [1, 2, 3, 4, 5] * // After error injection: [ObservableError("setup failed"), 1, 2, 3, 4, 5] * // The error appears first, then all original data flows through * ``` * * @param error The error to inject at the start of the stream * @param context Context string for error reporting (where it happened) * * @returns A TransformStream that injects the error and passes through data * * @example * ```typescript * // Handle operator setup failure * function createSafeOperator<T, R>( * operatorBuilder: () => Operator<T, R>, * context: string * ): Operator<T, R | ObservableError> { * return (source: ReadableStream<T>) => { * try { * return operatorBuilder()(source); * } catch (err) { * return source.pipeThrough( * createErrorInjectionTransform(err, context) * ); * } * }; * } * ``` * * @example * ```typescript * // Add warning to stream without breaking it * const warningStream = dataStream.pipeThrough( * createErrorInjectionTransform( * new Error("Data quality issue detected"), * "data-validation" * ) * ); * * // Consumers will see: [Error, ...originalData] * ``` */export function injectError<T>( error?: Error | Error[] | unknown | unknown[], context?: string, value?: unknown,): TransformStream<T, ObservableError> { return new TransformStream({ start(controller) { // Inject the error as the first item in the stream controller.enqueue(ObservableError.from(error, context, value)); }, });}