@gurezo/web-serial-rxjs 0.1.0 → 0.1.3

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": ["../src/client/serial-client.ts", "../src/errors/serial-error-code.ts", "../src/errors/serial-error.ts", "../src/browser/browser-detection.ts", "../src/browser/browser-support.ts", "../src/filters/build-request-options.ts", "../src/io/observable-to-writable.ts", "../src/io/readable-to-observable.ts", "../src/types/options.ts", "../src/client/index.ts"],
4
+ "sourcesContent": ["import { Observable, defer, switchMap } from 'rxjs';\nimport { checkBrowserSupport } from '../browser/browser-support';\nimport { SerialError, SerialErrorCode } from '../errors/serial-error';\nimport { buildRequestOptions } from '../filters/build-request-options';\nimport { subscribeToWritable } from '../io/observable-to-writable';\nimport { readableToObservable } from '../io/readable-to-observable';\nimport {\n DEFAULT_SERIAL_CLIENT_OPTIONS,\n SerialClientOptions,\n} from '../types/options';\n\n/**\n * Internal implementation of SerialClient interface.\n *\n * This class implements the {@link SerialClient} interface and provides the actual\n * functionality for serial port communication. Users should not instantiate this class\n * directly; instead, use {@link createSerialClient} to create a SerialClient instance.\n *\n * @internal\n */\nexport class SerialClientImpl {\n /** @internal */\n private port: SerialPort | null = null;\n /** @internal */\n private isOpen = false;\n /** @internal */\n private readSubscription: { unsubscribe: () => void } | null = null;\n /** @internal */\n private writeSubscription: { unsubscribe: () => void } | null = null;\n /** @internal */\n private readonly options: Required<Omit<SerialClientOptions, 'filters'>> & {\n filters?: SerialClientOptions['filters'];\n };\n\n /**\n * Creates a new SerialClientImpl instance.\n *\n * @param options - Optional configuration options for the serial port connection\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the browser doesn't support Web Serial API\n * @internal\n */\n constructor(options?: SerialClientOptions) {\n checkBrowserSupport();\n this.options = {\n ...DEFAULT_SERIAL_CLIENT_OPTIONS,\n ...options,\n filters: options?.filters,\n };\n }\n\n /**\n * Request a serial port from the user.\n *\n * @returns Observable that emits the selected SerialPort\n * @internal\n */\n requestPort(): Observable<SerialPort> {\n return defer(() => {\n checkBrowserSupport();\n\n return navigator.serial\n .requestPort(buildRequestOptions(this.options))\n .catch((error) => {\n if (error instanceof DOMException && error.name === 'NotFoundError') {\n throw new SerialError(\n SerialErrorCode.OPERATION_CANCELLED,\n 'Port selection was cancelled by the user',\n error,\n );\n }\n throw new SerialError(\n SerialErrorCode.PORT_NOT_AVAILABLE,\n `Failed to request port: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n });\n });\n }\n\n /**\n * Get available serial ports.\n *\n * @returns Observable that emits an array of available SerialPorts\n * @internal\n */\n getPorts(): Observable<SerialPort[]> {\n return defer(() => {\n checkBrowserSupport();\n\n return navigator.serial.getPorts().catch((error) => {\n throw new SerialError(\n SerialErrorCode.PORT_NOT_AVAILABLE,\n `Failed to get ports: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n });\n });\n }\n\n /**\n * Connect to a serial port.\n *\n * @param port - Optional SerialPort to connect to. If not provided, will request one.\n * @returns Observable that completes when the port is opened\n * @internal\n */\n connect(port?: SerialPort): Observable<void> {\n checkBrowserSupport();\n\n if (this.isOpen) {\n return new Observable<void>((subscriber) => {\n subscriber.error(\n new SerialError(\n SerialErrorCode.PORT_ALREADY_OPEN,\n 'Port is already open',\n ),\n );\n });\n }\n\n const port$ = port\n ? new Observable<SerialPort>((subscriber) => {\n subscriber.next(port);\n subscriber.complete();\n })\n : this.requestPort();\n\n return port$.pipe(\n switchMap((selectedPort) => {\n return defer(() => {\n this.port = selectedPort;\n\n return this.port\n .open({\n baudRate: this.options.baudRate,\n dataBits: this.options.dataBits,\n stopBits: this.options.stopBits,\n parity: this.options.parity,\n bufferSize: this.options.bufferSize,\n flowControl: this.options.flowControl,\n })\n .then(() => {\n this.isOpen = true;\n })\n .catch((error) => {\n this.port = null;\n this.isOpen = false;\n\n if (error instanceof SerialError) {\n throw error;\n }\n\n throw new SerialError(\n SerialErrorCode.PORT_OPEN_FAILED,\n `Failed to open port: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n });\n });\n }),\n );\n }\n\n /**\n * Disconnect from the serial port.\n *\n * @returns Observable that completes when the port is closed\n * @internal\n */\n disconnect(): Observable<void> {\n return defer(() => {\n if (!this.isOpen || !this.port) {\n return Promise.resolve();\n }\n\n // Unsubscribe from read/write streams\n if (this.readSubscription) {\n this.readSubscription.unsubscribe();\n this.readSubscription = null;\n }\n\n if (this.writeSubscription) {\n this.writeSubscription.unsubscribe();\n this.writeSubscription = null;\n }\n\n // Close the port\n return this.port\n .close()\n .then(() => {\n this.port = null;\n this.isOpen = false;\n })\n .catch((error) => {\n this.port = null;\n this.isOpen = false;\n\n throw new SerialError(\n SerialErrorCode.CONNECTION_LOST,\n `Failed to close port: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n });\n });\n }\n\n /**\n * Get an Observable that emits data read from the serial port.\n *\n * @returns Observable that emits Uint8Array chunks\n * @internal\n */\n getReadStream(): Observable<Uint8Array> {\n if (!this.isOpen || !this.port || !this.port.readable) {\n throw new SerialError(\n SerialErrorCode.PORT_NOT_OPEN,\n 'Port is not open or readable stream is not available',\n );\n }\n\n return readableToObservable(this.port.readable);\n }\n\n /**\n * Write data to the serial port from an Observable.\n *\n * @param data$ - Observable that emits Uint8Array chunks to write\n * @returns Observable that completes when writing is finished\n * @internal\n */\n writeStream(data$: Observable<Uint8Array>): Observable<void> {\n if (!this.isOpen || !this.port || !this.port.writable) {\n throw new SerialError(\n SerialErrorCode.PORT_NOT_OPEN,\n 'Port is not open or writable stream is not available',\n );\n }\n\n // Cancel previous write subscription if exists\n if (this.writeSubscription) {\n this.writeSubscription.unsubscribe();\n }\n\n this.writeSubscription = subscribeToWritable(data$, this.port.writable);\n\n return new Observable<void>((subscriber) => {\n // The subscription is already active, we just need to track completion\n if (!this.writeSubscription) {\n subscriber.error(\n new SerialError(\n SerialErrorCode.WRITE_FAILED,\n 'Write subscription is not available',\n ),\n );\n return;\n }\n const originalUnsubscribe = this.writeSubscription.unsubscribe;\n\n this.writeSubscription = {\n unsubscribe: () => {\n originalUnsubscribe();\n subscriber.complete();\n },\n };\n\n // If the observable completes, complete the subscriber\n data$.subscribe({\n complete: () => {\n if (this.writeSubscription) {\n this.writeSubscription.unsubscribe();\n this.writeSubscription = null;\n }\n subscriber.complete();\n },\n error: (error) => {\n if (this.writeSubscription) {\n this.writeSubscription.unsubscribe();\n this.writeSubscription = null;\n }\n subscriber.error(error);\n },\n });\n });\n }\n\n /**\n * Write a single chunk of data to the serial port.\n *\n * @param data - Data to write\n * @returns Observable that completes when the data is written\n * @internal\n */\n write(data: Uint8Array): Observable<void> {\n return defer(() => {\n if (!this.isOpen || !this.port || !this.port.writable) {\n throw new SerialError(\n SerialErrorCode.PORT_NOT_OPEN,\n 'Port is not open or writable stream is not available',\n );\n }\n\n const writer = this.port.writable.getWriter();\n return writer\n .write(data)\n .then(() => {\n writer.releaseLock();\n })\n .catch((error) => {\n writer.releaseLock();\n throw new SerialError(\n SerialErrorCode.WRITE_FAILED,\n `Failed to write data: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n });\n });\n }\n\n /**\n * Check if the port is currently open.\n *\n * @returns `true` if a port is currently open, `false` otherwise\n * @internal\n */\n get connected(): boolean {\n return this.isOpen;\n }\n\n /**\n * Get the current SerialPort instance.\n *\n * @returns The current SerialPort instance, or `null` if no port is open\n * @internal\n */\n get currentPort(): SerialPort | null {\n return this.port;\n }\n}\n", "/**\n * Error codes for serial port operations.\n *\n * These codes identify specific error conditions that can occur when working with\n * serial ports. Each error code corresponds to a specific failure scenario, making\n * it easier to handle errors programmatically.\n *\n * @example\n * ```typescript\n * try {\n * await client.connect().toPromise();\n * } catch (error) {\n * if (error instanceof SerialError) {\n * switch (error.code) {\n * case SerialErrorCode.BROWSER_NOT_SUPPORTED:\n * console.error('Please use a Chromium-based browser');\n * break;\n * case SerialErrorCode.OPERATION_CANCELLED:\n * console.log('User cancelled port selection');\n * break;\n * // ... handle other error codes\n * }\n * }\n * }\n * ```\n */\nexport enum SerialErrorCode {\n /**\n * Browser does not support the Web Serial API.\n *\n * This error occurs when attempting to use serial port functionality in a browser\n * that doesn't support the Web Serial API. Only Chromium-based browsers (Chrome,\n * Edge, Opera) support this API.\n *\n * **Suggested action**: Inform the user to use a supported browser.\n */\n BROWSER_NOT_SUPPORTED = 'BROWSER_NOT_SUPPORTED',\n\n /**\n * Serial port is not available.\n *\n * This error occurs when a requested port cannot be accessed, such as when\n * getting previously granted ports fails or when the port is already in use\n * by another application.\n *\n * **Suggested action**: Check if the port is available or being used by another application.\n */\n PORT_NOT_AVAILABLE = 'PORT_NOT_AVAILABLE',\n\n /**\n * Failed to open the serial port.\n *\n * This error occurs when the port cannot be opened, typically due to incorrect\n * connection parameters, hardware issues, or permission problems.\n *\n * **Suggested action**: Verify connection parameters and check hardware connections.\n */\n PORT_OPEN_FAILED = 'PORT_OPEN_FAILED',\n\n /**\n * Serial port is already open.\n *\n * This error occurs when attempting to open a port that is already connected.\n * Only one connection can be active at a time per SerialClient instance.\n *\n * **Suggested action**: Disconnect the current port before connecting a new one.\n */\n PORT_ALREADY_OPEN = 'PORT_ALREADY_OPEN',\n\n /**\n * Serial port is not open.\n *\n * This error occurs when attempting to read from or write to a port that hasn't\n * been opened yet. The port must be connected before performing I/O operations.\n *\n * **Suggested action**: Call {@link SerialClient.connect} before reading or writing.\n */\n PORT_NOT_OPEN = 'PORT_NOT_OPEN',\n\n /**\n * Failed to read from the serial port.\n *\n * This error occurs when reading data from the port fails, typically due to\n * connection loss, hardware issues, or stream errors.\n *\n * **Suggested action**: Check the connection and hardware, then retry the read operation.\n */\n READ_FAILED = 'READ_FAILED',\n\n /**\n * Failed to write to the serial port.\n *\n * This error occurs when writing data to the port fails, typically due to\n * connection loss, hardware issues, or stream errors.\n *\n * **Suggested action**: Check the connection and hardware, then retry the write operation.\n */\n WRITE_FAILED = 'WRITE_FAILED',\n\n /**\n * Serial port connection was lost.\n *\n * This error occurs when the connection to the serial port is unexpectedly\n * terminated, such as when the device is disconnected or the port is closed\n * by another process.\n *\n * **Suggested action**: Check the physical connection and reconnect if needed.\n */\n CONNECTION_LOST = 'CONNECTION_LOST',\n\n /**\n * Invalid filter options provided.\n *\n * This error occurs when port filter options are invalid, such as when\n * filter values are out of range or missing required fields.\n *\n * **Suggested action**: Verify filter options match the expected format and value ranges.\n */\n INVALID_FILTER_OPTIONS = 'INVALID_FILTER_OPTIONS',\n\n /**\n * Operation was cancelled by the user.\n *\n * This error occurs when the user cancels a port selection dialog or aborts\n * an operation before it completes.\n *\n * **Suggested action**: This is a normal condition - no action required, but you may want\n * to inform the user that the operation was cancelled.\n */\n OPERATION_CANCELLED = 'OPERATION_CANCELLED',\n\n /**\n * Unknown error occurred.\n *\n * This error code is used for errors that don't fit into any other category.\n * The original error details may be available in the error's message or originalError property.\n *\n * **Suggested action**: Check the error message and originalError for more details.\n */\n UNKNOWN = 'UNKNOWN',\n}\n", "import { SerialErrorCode } from './serial-error-code';\n\n// Re-export SerialErrorCode for convenience\nexport { SerialErrorCode };\n\n/**\n * Custom error class for serial port operations.\n *\n * This error class extends the standard Error class and includes additional information\n * about the type of error that occurred. It provides an error code for programmatic\n * error handling and may include the original error that caused the failure.\n *\n * @example\n * ```typescript\n * try {\n * await client.connect().toPromise();\n * } catch (error) {\n * if (error instanceof SerialError) {\n * console.error(`Error code: ${error.code}`);\n * console.error(`Message: ${error.message}`);\n * if (error.originalError) {\n * console.error(`Original error:`, error.originalError);\n * }\n *\n * // Check specific error code\n * if (error.is(SerialErrorCode.BROWSER_NOT_SUPPORTED)) {\n * // Handle browser not supported\n * }\n * }\n * }\n * ```\n */\nexport class SerialError extends Error {\n /**\n * The error code identifying the type of error that occurred.\n *\n * Use this code to programmatically handle specific error conditions.\n *\n * @see {@link SerialErrorCode} for all available error codes\n */\n public readonly code: SerialErrorCode;\n\n /**\n * The original error that caused this SerialError, if available.\n *\n * This property contains the underlying error (e.g., DOMException, TypeError)\n * that was wrapped in this SerialError. It may be undefined if no original error exists.\n */\n public readonly originalError?: Error;\n\n /**\n * Creates a new SerialError instance.\n *\n * @param code - The error code identifying the type of error\n * @param message - A human-readable error message\n * @param originalError - The original error that caused this SerialError, if any\n */\n constructor(code: SerialErrorCode, message: string, originalError?: Error) {\n super(message);\n this.name = 'SerialError';\n this.code = code;\n this.originalError = originalError;\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if ((Error as any).captureStackTrace) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (Error as any).captureStackTrace(this, SerialError);\n }\n }\n\n /**\n * Check if the error matches a specific error code.\n *\n * This is a convenience method for checking the error code without directly\n * comparing the code property.\n *\n * @param code - The error code to check against\n * @returns `true` if this error's code matches the provided code, `false` otherwise\n *\n * @example\n * ```typescript\n * if (error.is(SerialErrorCode.PORT_NOT_OPEN)) {\n * // Handle port not open error\n * }\n * ```\n */\n public is(code: SerialErrorCode): boolean {\n return this.code === code;\n }\n}\n", "/**\n * Browser type enumeration for identifying the browser environment.\n *\n * This enum is used to identify the specific browser type, which is useful for\n * browser-specific behavior or error messages.\n *\n * @example\n * ```typescript\n * const browserType = detectBrowserType();\n * if (browserType === BrowserType.CHROME) {\n * console.log('Running in Chrome');\n * }\n * ```\n */\nexport enum BrowserType {\n /** Google Chrome browser */\n CHROME = 'chrome',\n /** Microsoft Edge browser */\n EDGE = 'edge',\n /** Opera browser */\n OPERA = 'opera',\n /** Unknown or unsupported browser */\n UNKNOWN = 'unknown',\n}\n\n/**\n * Feature detection for Web Serial API.\n *\n * Checks if the browser supports the Web Serial API by verifying the presence\n * of `navigator.serial`. This is a non-throwing check that returns `false` if\n * the API is not available.\n *\n * Note: This function only checks for API availability, not whether the browser\n * type is supported. For a throwing check that provides better error messages,\n * use {@link checkBrowserSupport}.\n *\n * @returns `true` if the Web Serial API is available, `false` otherwise\n *\n * @example\n * ```typescript\n * if (hasWebSerialSupport()) {\n * // Safe to use serial port functionality\n * const client = createSerialClient();\n * } else {\n * console.error('Web Serial API is not supported');\n * }\n * ```\n *\n * @see {@link checkBrowserSupport} for a throwing version with better error messages\n * @see {@link isBrowserSupported} for an alias to this function\n */\nexport function hasWebSerialSupport(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n 'serial' in navigator &&\n navigator.serial !== undefined &&\n navigator.serial !== null\n );\n}\n\n/**\n * Detect browser type from the user agent string.\n *\n * Analyzes the browser's user agent string to identify the browser type.\n * This function is useful for providing browser-specific functionality or\n * error messages.\n *\n * @returns The detected {@link BrowserType}, or {@link BrowserType.UNKNOWN} if the browser cannot be identified\n *\n * @example\n * ```typescript\n * const browserType = detectBrowserType();\n * switch (browserType) {\n * case BrowserType.CHROME:\n * console.log('Running in Chrome');\n * break;\n * case BrowserType.EDGE:\n * console.log('Running in Edge');\n * break;\n * case BrowserType.OPERA:\n * console.log('Running in Opera');\n * break;\n * default:\n * console.log('Unknown browser');\n * }\n * ```\n *\n * @see {@link isChromiumBased} for checking if the browser is Chromium-based\n */\nexport function detectBrowserType(): BrowserType {\n if (typeof navigator === 'undefined' || !navigator.userAgent) {\n return BrowserType.UNKNOWN;\n }\n\n const ua = navigator.userAgent.toLowerCase();\n\n if (ua.includes('edg/')) {\n return BrowserType.EDGE;\n }\n\n if (ua.includes('opr/') || ua.includes('opera/')) {\n return BrowserType.OPERA;\n }\n\n if (ua.includes('chrome/')) {\n return BrowserType.CHROME;\n }\n\n return BrowserType.UNKNOWN;\n}\n\n/**\n * Check if the browser is Chromium-based.\n *\n * Determines if the current browser is based on Chromium, which includes\n * Chrome, Edge, and Opera. These browsers support the Web Serial API.\n *\n * @returns `true` if the browser is Chromium-based (Chrome, Edge, or Opera), `false` otherwise\n *\n * @example\n * ```typescript\n * if (isChromiumBased()) {\n * // Browser supports Web Serial API\n * const client = createSerialClient();\n * } else {\n * console.error('Please use a Chromium-based browser (Chrome, Edge, or Opera)');\n * }\n * ```\n *\n * @see {@link detectBrowserType} for identifying the specific browser type\n * @see {@link hasWebSerialSupport} for checking Web Serial API availability\n */\nexport function isChromiumBased(): boolean {\n const browserType = detectBrowserType();\n return (\n browserType === BrowserType.CHROME ||\n browserType === BrowserType.EDGE ||\n browserType === BrowserType.OPERA\n );\n}\n", "import { SerialError, SerialErrorCode } from '../errors/serial-error';\nimport {\n BrowserType,\n detectBrowserType,\n hasWebSerialSupport,\n} from './browser-detection';\n\n/**\n * Check if the browser supports the Web Serial API, throwing an error if not supported.\n *\n * This function performs a feature detection check and throws a {@link SerialError}\n * with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the Web Serial API\n * is not available. The error message includes the detected browser type for better\n * user feedback.\n *\n * This is the recommended way to check browser support before using serial port\n * functionality, as it provides clear error messages.\n *\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED}\n * if the browser doesn't support the Web Serial API\n *\n * @example\n * ```typescript\n * try {\n * checkBrowserSupport();\n * // Safe to use serial port functionality\n * const client = createSerialClient();\n * } catch (error) {\n * if (error instanceof SerialError && error.code === SerialErrorCode.BROWSER_NOT_SUPPORTED) {\n * console.error(error.message);\n * // Show user-friendly message: \"Please use a Chromium-based browser...\"\n * }\n * }\n * ```\n *\n * @see {@link isBrowserSupported} for a non-throwing version that returns a boolean\n * @see {@link hasWebSerialSupport} for the underlying feature detection function\n */\nexport function checkBrowserSupport(): void {\n if (!hasWebSerialSupport()) {\n const browserType = detectBrowserType();\n const browserName =\n browserType === BrowserType.UNKNOWN\n ? 'your browser'\n : browserType.toUpperCase();\n\n throw new SerialError(\n SerialErrorCode.BROWSER_NOT_SUPPORTED,\n `Web Serial API is not supported in ${browserName}. Please use a Chromium-based browser (Chrome, Edge, or Opera).`,\n );\n }\n}\n\n/**\n * Check if the browser supports the Web Serial API (non-throwing version).\n *\n * This is a convenience function that returns a boolean indicating whether\n * the Web Serial API is available. Unlike {@link checkBrowserSupport}, this\n * function does not throw an error if the API is not available.\n *\n * @returns `true` if the Web Serial API is supported, `false` otherwise\n *\n * @example\n * ```typescript\n * if (isBrowserSupported()) {\n * const client = createSerialClient();\n * // Use serial port functionality\n * } else {\n * console.error('Web Serial API is not supported in this browser');\n * // Show fallback UI or message\n * }\n * ```\n *\n * @see {@link checkBrowserSupport} for a throwing version with better error messages\n * @see {@link hasWebSerialSupport} which this function calls internally\n */\nexport function isBrowserSupported(): boolean {\n return hasWebSerialSupport();\n}\n", "import { SerialError, SerialErrorCode } from '../errors/serial-error';\nimport { SerialClientOptions } from '../types/options';\n\n/**\n * Build SerialPortRequestOptions from SerialClientOptions.\n *\n * This utility function converts filter options from {@link SerialClientOptions} into\n * the format expected by the Web Serial API's `navigator.serial.requestPort()` method.\n * It validates the filter options to ensure they are valid before returning them.\n *\n * If no filters are provided in the options, this function returns `undefined`, which\n * allows the port selection dialog to show all available ports.\n *\n * @param options - Optional SerialClientOptions containing filter configuration\n * @returns SerialPortRequestOptions object with validated filters, or `undefined` if no filters are provided\n * @throws {@link SerialError} with code {@link SerialErrorCode.INVALID_FILTER_OPTIONS} if filter validation fails\n *\n * @example\n * ```typescript\n * // With filters\n * const options = {\n * baudRate: 9600,\n * filters: [\n * { usbVendorId: 0x1234 },\n * { usbVendorId: 0x5678, usbProductId: 0x9abc },\n * ],\n * };\n * const requestOptions = buildRequestOptions(options);\n * // Returns: { filters: [...] }\n *\n * // Without filters\n * const requestOptions = buildRequestOptions({ baudRate: 9600 });\n * // Returns: undefined\n *\n * // Invalid filter (will throw)\n * try {\n * buildRequestOptions({ filters: [{ usbVendorId: -1 }] });\n * } catch (error) {\n * // SerialError with code INVALID_FILTER_OPTIONS\n * }\n * ```\n */\nexport function buildRequestOptions(\n options?: SerialClientOptions,\n): SerialPortRequestOptions | undefined {\n if (!options || !options.filters || options.filters.length === 0) {\n return undefined;\n }\n\n // Validate filters\n for (const filter of options.filters) {\n if (!filter.usbVendorId && !filter.usbProductId) {\n throw new SerialError(\n SerialErrorCode.INVALID_FILTER_OPTIONS,\n 'Filter must have at least usbVendorId or usbProductId',\n );\n }\n\n if (filter.usbVendorId !== undefined) {\n if (\n !Number.isInteger(filter.usbVendorId) ||\n filter.usbVendorId < 0 ||\n filter.usbVendorId > 0xffff\n ) {\n throw new SerialError(\n SerialErrorCode.INVALID_FILTER_OPTIONS,\n `Invalid usbVendorId: ${filter.usbVendorId}. Must be an integer between 0 and 65535.`,\n );\n }\n }\n\n if (filter.usbProductId !== undefined) {\n if (\n !Number.isInteger(filter.usbProductId) ||\n filter.usbProductId < 0 ||\n filter.usbProductId > 0xffff\n ) {\n throw new SerialError(\n SerialErrorCode.INVALID_FILTER_OPTIONS,\n `Invalid usbProductId: ${filter.usbProductId}. Must be an integer between 0 and 65535.`,\n );\n }\n }\n }\n\n return {\n filters: options.filters,\n };\n}\n", "import { Observable } from 'rxjs';\nimport { SerialError, SerialErrorCode } from '../errors/serial-error';\n\n/**\n * Convert an RxJS Observable to a WritableStream.\n *\n * This utility function converts an RxJS Observable into a Web Streams API WritableStream.\n * Values emitted by the Observable will be written to the returned WritableStream. The stream\n * will close when the Observable completes or abort if the Observable errors.\n *\n * Note: This function creates a new WritableStream. For directly subscribing to an Observable\n * and writing to an existing WritableStream, use {@link subscribeToWritable} instead.\n *\n * @param observable - The Observable to convert to a WritableStream\n * @returns A WritableStream that writes Uint8Array chunks emitted by the Observable\n *\n * @example\n * ```typescript\n * const data$ = from([\n * new TextEncoder().encode('Hello'),\n * new TextEncoder().encode('World'),\n * ]);\n *\n * const writableStream = observableToWritable(data$);\n * // Use the writable stream with other Web Streams APIs\n * ```\n */\nexport function observableToWritable(\n observable: Observable<Uint8Array>,\n): WritableStream<Uint8Array> {\n let writer: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let subscription: { unsubscribe: () => void } | null = null;\n let stream: WritableStream<Uint8Array> | null = null;\n\n stream = new WritableStream<Uint8Array>({\n async start() {\n if (!stream) {\n return;\n }\n writer = stream.getWriter();\n\n subscription = observable.subscribe({\n next: async (chunk) => {\n if (writer) {\n try {\n await writer.write(chunk);\n } catch (error) {\n subscription?.unsubscribe();\n if (writer) {\n writer.releaseLock();\n }\n throw error;\n }\n }\n },\n error: async (error) => {\n if (writer) {\n try {\n await writer.abort(error);\n } catch {\n // Ignore abort errors\n } finally {\n writer.releaseLock();\n writer = null;\n }\n }\n },\n complete: async () => {\n if (writer) {\n try {\n await writer.close();\n } catch {\n // Ignore close errors\n } finally {\n writer.releaseLock();\n writer = null;\n }\n }\n },\n });\n },\n\n abort(reason) {\n if (subscription) {\n subscription.unsubscribe();\n subscription = null;\n }\n if (writer) {\n writer.abort(reason).catch(() => {\n // Ignore abort errors\n });\n writer.releaseLock();\n writer = null;\n }\n },\n });\n\n return stream;\n}\n\n/**\n * Subscribe to an Observable and write its values to a WritableStream.\n *\n * This utility function subscribes to an RxJS Observable and writes all emitted values\n * to the provided WritableStream. This is commonly used to write Observable data to a\n * serial port's writable stream.\n *\n * The function returns a subscription object that can be used to unsubscribe and clean up.\n * When unsubscribed, the writer lock will be released properly.\n *\n * @param observable - The Observable to subscribe to and read data from\n * @param stream - The WritableStream to write data to\n * @returns A subscription object with an `unsubscribe` method for cleanup\n * @throws {@link SerialError} with code {@link SerialErrorCode.WRITE_FAILED} if writing to the stream fails\n *\n * @example\n * ```typescript\n * const data$ = from([\n * new TextEncoder().encode('Hello'),\n * new TextEncoder().encode('World'),\n * ]);\n *\n * const subscription = subscribeToWritable(data$, port.writable);\n *\n * // Later, to cancel and clean up:\n * subscription.unsubscribe();\n *\n * // Use with RxJS operators\n * const processedData$ = of('Hello, Serial!').pipe(\n * map((text) => new TextEncoder().encode(text))\n * );\n *\n * subscribeToWritable(processedData$, port.writable);\n * ```\n */\nexport function subscribeToWritable(\n observable: Observable<Uint8Array>,\n stream: WritableStream<Uint8Array>,\n): { unsubscribe: () => void } {\n const writer = stream.getWriter();\n\n // Define error handler separately so we can call it directly\n const errorHandler = async (error: unknown) => {\n try {\n await writer.abort(error);\n } catch {\n // Ignore abort errors\n } finally {\n writer.releaseLock();\n }\n };\n\n const subscription = observable.subscribe({\n next: async (chunk) => {\n try {\n await writer.write(chunk);\n } catch (error) {\n subscription.unsubscribe();\n writer.releaseLock();\n // Convert write error to SerialError and pass to error handler\n const serialError = new SerialError(\n SerialErrorCode.WRITE_FAILED,\n `Failed to write to stream: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n );\n // Manually trigger error handler to avoid unhandled rejection\n await errorHandler(serialError);\n }\n },\n error: errorHandler,\n complete: async () => {\n try {\n await writer.close();\n } catch {\n // Ignore close errors\n } finally {\n writer.releaseLock();\n }\n },\n });\n\n return {\n unsubscribe: () => {\n subscription.unsubscribe();\n writer.releaseLock();\n },\n };\n}\n", "import { Observable } from 'rxjs';\nimport { SerialError, SerialErrorCode } from '../errors/serial-error';\n\n/**\n * Convert a ReadableStream to an RxJS Observable.\n *\n * This utility function converts a Web Streams API ReadableStream into an RxJS Observable,\n * allowing you to use RxJS operators with stream data. The Observable will emit Uint8Array\n * chunks as they are read from the stream, complete when the stream ends, or error if\n * the stream encounters an error.\n *\n * The returned Observable handles stream cleanup automatically - if you unsubscribe before\n * the stream completes, the reader lock will be released properly.\n *\n * @param stream - The ReadableStream to convert to an Observable\n * @returns An Observable that emits Uint8Array chunks from the stream\n * @throws {@link SerialError} with code {@link SerialErrorCode.READ_FAILED} if reading from the stream fails\n *\n * @example\n * ```typescript\n * // Convert a serial port's readable stream to an Observable\n * const readable$ = readableToObservable(port.readable);\n *\n * readable$.subscribe({\n * next: (chunk) => {\n * console.log('Received chunk:', chunk);\n * },\n * complete: () => {\n * console.log('Stream completed');\n * },\n * error: (error) => {\n * console.error('Stream error:', error);\n * },\n * });\n *\n * // Use with RxJS operators\n * readableToObservable(port.readable)\n * .pipe(\n * map((chunk) => new TextDecoder().decode(chunk)),\n * filter((text) => text.includes('OK'))\n * )\n * .subscribe((text) => console.log('Filtered text:', text));\n * ```\n */\nexport function readableToObservable(\n stream: ReadableStream<Uint8Array>,\n): Observable<Uint8Array> {\n return new Observable<Uint8Array>((subscriber) => {\n const reader = stream.getReader();\n\n const pump = async (): Promise<void> => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n subscriber.complete();\n break;\n }\n\n if (value) {\n subscriber.next(value);\n }\n }\n } catch (error) {\n if (error instanceof Error) {\n subscriber.error(\n new SerialError(\n SerialErrorCode.READ_FAILED,\n `Failed to read from stream: ${error.message}`,\n error,\n ),\n );\n } else {\n subscriber.error(\n new SerialError(\n SerialErrorCode.READ_FAILED,\n 'Failed to read from stream: Unknown error',\n error as Error,\n ),\n );\n }\n } finally {\n reader.releaseLock();\n }\n };\n\n pump().catch((error) => {\n if (!subscriber.closed) {\n subscriber.error(error);\n }\n });\n\n // Cleanup function\n return () => {\n reader.releaseLock();\n };\n });\n}\n", "/**\n * Options for creating a SerialClient instance.\n *\n * These options configure the serial port connection parameters. All properties are optional\n * and will use default values if not specified. See {@link DEFAULT_SERIAL_CLIENT_OPTIONS} for\n * the default values used.\n *\n * @example\n * ```typescript\n * const client = createSerialClient({\n * baudRate: 115200,\n * dataBits: 8,\n * stopBits: 1,\n * parity: 'none',\n * flowControl: 'none',\n * filters: [{ usbVendorId: 0x1234, usbProductId: 0x5678 }],\n * });\n * ```\n */\nexport interface SerialClientOptions {\n /**\n * Baud rate for the serial port connection (bits per second).\n *\n * Common values include 9600, 19200, 38400, 57600, 115200, etc.\n * Must match the baud rate configured on the connected device.\n *\n * @default 9600\n */\n baudRate?: number;\n\n /**\n * Number of data bits per character (7 or 8).\n *\n * - `7`: Seven data bits (used with parity)\n * - `8`: Eight data bits (most common, used without parity)\n *\n * @default 8\n */\n dataBits?: 7 | 8;\n\n /**\n * Number of stop bits (1 or 2).\n *\n * - `1`: One stop bit (most common)\n * - `2`: Two stop bits (less common, used for slower devices)\n *\n * @default 1\n */\n stopBits?: 1 | 2;\n\n /**\n * Parity checking mode.\n *\n * - `'none'`: No parity checking (most common)\n * - `'even'`: Even parity\n * - `'odd'`: Odd parity\n *\n * @default 'none'\n */\n parity?: 'none' | 'even' | 'odd';\n\n /**\n * Buffer size for reading data from the serial port, in bytes.\n *\n * This determines how much data can be buffered before it needs to be read.\n * Larger buffers can improve performance but use more memory.\n *\n * @default 255\n */\n bufferSize?: number;\n\n /**\n * Flow control mode.\n *\n * - `'none'`: No flow control (most common)\n * - `'hardware'`: Hardware flow control (RTS/CTS)\n *\n * @default 'none'\n */\n flowControl?: 'none' | 'hardware';\n\n /**\n * Filters for port selection when requesting a port.\n *\n * When specified, the port selection dialog will only show devices matching\n * these filters. Each filter can specify `usbVendorId` and/or `usbProductId`\n * to filter by USB device identifiers.\n *\n * @example\n * ```typescript\n * filters: [\n * { usbVendorId: 0x1234 },\n * { usbVendorId: 0x1234, usbProductId: 0x5678 },\n * ]\n * ```\n *\n * @see {@link SerialPortFilter} for the filter structure\n */\n filters?: SerialPortFilter[];\n}\n\n/**\n * Default options for SerialClient instances.\n *\n * These are the default values used when creating a SerialClient if no options\n * are provided or if specific options are omitted. The values are chosen to work\n * with most common serial devices.\n *\n * @see {@link SerialClientOptions} for details on each option\n */\nexport const DEFAULT_SERIAL_CLIENT_OPTIONS: Required<\n Omit<SerialClientOptions, 'filters'>\n> & { filters?: SerialPortFilter[] } = {\n baudRate: 9600,\n dataBits: 8,\n stopBits: 1,\n parity: 'none',\n bufferSize: 255,\n flowControl: 'none',\n filters: undefined,\n};\n", "import { Observable } from 'rxjs';\nimport { SerialClientOptions } from '../types/options';\nimport { SerialClientImpl } from './serial-client';\n\n/**\n * SerialClient interface for interacting with serial ports using RxJS Observables.\n *\n * This interface provides a reactive API for serial port communication, allowing you to\n * connect to serial devices, read and write data using RxJS Observables.\n *\n * @example\n * ```typescript\n * const client = createSerialClient({ baudRate: 9600 });\n *\n * // Connect to a port\n * client.connect().subscribe({\n * next: () => {\n * console.log('Connected!');\n *\n * // Read data\n * client.getReadStream().subscribe({\n * next: (data) => console.log('Received:', data),\n * });\n *\n * // Write data\n * const encoder = new TextEncoder();\n * client.write(encoder.encode('Hello')).subscribe();\n * },\n * error: (error) => console.error('Connection error:', error),\n * });\n * ```\n */\nexport interface SerialClient {\n /**\n * Request a serial port from the user.\n *\n * This method opens the browser's port selection dialog and returns an Observable\n * that emits the selected SerialPort when the user chooses a port.\n *\n * @returns An Observable that emits the selected {@link SerialPort} when the user selects a port\n * @throws {@link SerialError} with code {@link SerialErrorCode.OPERATION_CANCELLED} if the user cancels the selection\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_NOT_AVAILABLE} if the port request fails\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the browser doesn't support Web Serial API\n *\n * @example\n * ```typescript\n * client.requestPort().subscribe({\n * next: (port) => console.log('Selected port:', port),\n * error: (error) => console.error('Port selection failed:', error),\n * });\n * ```\n */\n requestPort(): Observable<SerialPort>;\n\n /**\n * Get available serial ports that have been previously granted access.\n *\n * This method returns an Observable that emits an array of SerialPort instances\n * that the user has previously granted access to in this browser session.\n *\n * @returns An Observable that emits an array of available {@link SerialPort} instances\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_NOT_AVAILABLE} if getting ports fails\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the browser doesn't support Web Serial API\n *\n * @example\n * ```typescript\n * client.getPorts().subscribe({\n * next: (ports) => {\n * console.log(`Found ${ports.length} available ports`);\n * if (ports.length > 0) {\n * client.connect(ports[0]).subscribe();\n * }\n * },\n * });\n * ```\n */\n getPorts(): Observable<SerialPort[]>;\n\n /**\n * Connect to a serial port.\n *\n * Opens the specified port (or requests one if not provided) and configures it\n * with the options passed to {@link createSerialClient}. The port must be connected\n * before reading or writing data.\n *\n * @param port - Optional {@link SerialPort} to connect to. If not provided, will call {@link requestPort} to prompt the user.\n * @returns An Observable that completes when the port is successfully opened\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_ALREADY_OPEN} if a port is already open\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_OPEN_FAILED} if opening the port fails\n * @throws {@link SerialError} with code {@link SerialErrorCode.OPERATION_CANCELLED} if the user cancels port selection\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the browser doesn't support Web Serial API\n *\n * @example\n * ```typescript\n * // Connect by requesting a port\n * client.connect().subscribe({\n * next: () => console.log('Connected!'),\n * error: (error) => console.error('Connection failed:', error),\n * });\n *\n * // Connect to a specific port\n * client.getPorts().subscribe({\n * next: (ports) => {\n * if (ports.length > 0) {\n * client.connect(ports[0]).subscribe();\n * }\n * },\n * });\n * ```\n */\n connect(port?: SerialPort): Observable<void>;\n\n /**\n * Disconnect from the serial port.\n *\n * Closes the currently open port and stops all active read/write streams.\n * This method is safe to call even if no port is currently open.\n *\n * @returns An Observable that completes when the port is successfully closed\n * @throws {@link SerialError} with code {@link SerialErrorCode.CONNECTION_LOST} if closing the port fails\n *\n * @example\n * ```typescript\n * client.disconnect().subscribe({\n * next: () => console.log('Disconnected'),\n * error: (error) => console.error('Disconnect failed:', error),\n * });\n * ```\n */\n disconnect(): Observable<void>;\n\n /**\n * Get an Observable that emits data read from the serial port.\n *\n * Returns an Observable stream that emits Uint8Array chunks as data is received\n * from the serial port. The stream will continue until the port is disconnected\n * or an error occurs.\n *\n * @returns An Observable that emits Uint8Array chunks containing data read from the serial port\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_NOT_OPEN} if the port is not open\n *\n * @example\n * ```typescript\n * client.getReadStream().subscribe({\n * next: (data) => {\n * const text = new TextDecoder().decode(data);\n * console.log('Received:', text);\n * },\n * error: (error) => console.error('Read error:', error),\n * });\n * ```\n */\n getReadStream(): Observable<Uint8Array>;\n\n /**\n * Write data to the serial port from an Observable.\n *\n * Writes data from an Observable stream to the serial port. The Observable should\n * emit Uint8Array chunks that will be written sequentially to the port. If a previous\n * write stream is active, it will be cancelled before starting the new one.\n *\n * @param data$ - Observable that emits Uint8Array chunks to write to the serial port\n * @returns An Observable that completes when all data has been written and the stream completes\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_NOT_OPEN} if the port is not open\n * @throws {@link SerialError} with code {@link SerialErrorCode.WRITE_FAILED} if writing fails\n *\n * @example\n * ```typescript\n * const data$ = from([\n * new TextEncoder().encode('Hello'),\n * new TextEncoder().encode('World'),\n * ]);\n *\n * client.writeStream(data$).subscribe({\n * next: () => console.log('Writing...'),\n * complete: () => console.log('All data written'),\n * error: (error) => console.error('Write error:', error),\n * });\n * ```\n */\n writeStream(data$: Observable<Uint8Array>): Observable<void>;\n\n /**\n * Write a single chunk of data to the serial port.\n *\n * Writes a single Uint8Array chunk to the serial port. For writing multiple chunks,\n * consider using {@link writeStream} with an Observable instead.\n *\n * @param data - Uint8Array data to write to the serial port\n * @returns An Observable that completes when the data has been written\n * @throws {@link SerialError} with code {@link SerialErrorCode.PORT_NOT_OPEN} if the port is not open\n * @throws {@link SerialError} with code {@link SerialErrorCode.WRITE_FAILED} if writing fails\n *\n * @example\n * ```typescript\n * const encoder = new TextEncoder();\n * const data = encoder.encode('Hello, Serial!');\n *\n * client.write(data).subscribe({\n * next: () => console.log('Data written'),\n * error: (error) => console.error('Write error:', error),\n * });\n * ```\n */\n write(data: Uint8Array): Observable<void>;\n\n /**\n * Check if the port is currently open and connected.\n *\n * @returns `true` if a port is currently open, `false` otherwise\n */\n readonly connected: boolean;\n\n /**\n * Get the current SerialPort instance.\n *\n * Returns the currently connected SerialPort instance, or `null` if no port is open.\n * This allows direct access to the underlying Web Serial API SerialPort object if needed.\n *\n * @returns The current {@link SerialPort} instance, or `null` if no port is open\n */\n readonly currentPort: SerialPort | null;\n}\n\n/**\n * Create a new SerialClient instance for interacting with serial ports.\n *\n * This is the main entry point for creating a serial client. The client provides\n * a reactive RxJS-based API for connecting to serial ports and reading/writing data.\n *\n * @param options - Optional configuration options for the serial port connection.\n * If not provided, default values will be used (9600 baud, 8 data bits, etc.)\n * @returns A new {@link SerialClient} instance\n * @throws {@link SerialError} with code {@link SerialErrorCode.BROWSER_NOT_SUPPORTED} if the browser doesn't support Web Serial API\n *\n * @example\n * ```typescript\n * // Create a client with default settings (9600 baud)\n * const client = createSerialClient();\n *\n * // Create a client with custom settings\n * const client = createSerialClient({\n * baudRate: 115200,\n * dataBits: 8,\n * stopBits: 1,\n * parity: 'none',\n * filters: [{ usbVendorId: 0x1234 }],\n * });\n *\n * // Check browser support before creating a client\n * import { isBrowserSupported } from '@gurezo/web-serial-rxjs';\n *\n * if (!isBrowserSupported()) {\n * console.error('Web Serial API is not supported');\n * } else {\n * const client = createSerialClient();\n * }\n * ```\n */\nexport function createSerialClient(\n options?: SerialClientOptions,\n): SerialClient {\n return new SerialClientImpl(options);\n}\n"],
5
+ "mappings": ";AAAA,SAAS,cAAAA,aAAY,OAAO,iBAAiB;;;AC0BtC,IAAK,kBAAL,kBAAKC,qBAAL;AAUL,EAAAA,iBAAA,2BAAwB;AAWxB,EAAAA,iBAAA,wBAAqB;AAUrB,EAAAA,iBAAA,sBAAmB;AAUnB,EAAAA,iBAAA,uBAAoB;AAUpB,EAAAA,iBAAA,mBAAgB;AAUhB,EAAAA,iBAAA,iBAAc;AAUd,EAAAA,iBAAA,kBAAe;AAWf,EAAAA,iBAAA,qBAAkB;AAUlB,EAAAA,iBAAA,4BAAyB;AAWzB,EAAAA,iBAAA,yBAAsB;AAUtB,EAAAA,iBAAA,aAAU;AAjHA,SAAAA;AAAA,GAAA;;;ACML,IAAM,cAAN,MAAM,qBAAoB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAyBrC,YAAY,MAAuB,SAAiB,eAAuB;AACzE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,gBAAgB;AAIrB,Q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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,cAAiC;AACnC,WAAO,KAAK;AAAA,EACd;AACF;;;AS9EO,SAAS,mBACd,SACc;AACd,SAAO,IAAI,iBAAiB,OAAO;AACrC;",
6
+ "names": ["Observable", "SerialErrorCode", "BrowserType", "Observable"]
7
+ }
@@ -0,0 +1,65 @@
1
+ import { Observable } from 'rxjs';
2
+ /**
3
+ * Convert an RxJS Observable to a WritableStream.
4
+ *
5
+ * This utility function converts an RxJS Observable into a Web Streams API WritableStream.
6
+ * Values emitted by the Observable will be written to the returned WritableStream. The stream
7
+ * will close when the Observable completes or abort if the Observable errors.
8
+ *
9
+ * Note: This function creates a new WritableStream. For directly subscribing to an Observable
10
+ * and writing to an existing WritableStream, use {@link subscribeToWritable} instead.
11
+ *
12
+ * @param observable - The Observable to convert to a WritableStream
13
+ * @returns A WritableStream that writes Uint8Array chunks emitted by the Observable
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const data$ = from([
18
+ * new TextEncoder().encode('Hello'),
19
+ * new TextEncoder().encode('World'),
20
+ * ]);
21
+ *
22
+ * const writableStream = observableToWritable(data$);
23
+ * // Use the writable stream with other Web Streams APIs
24
+ * ```
25
+ */
26
+ export declare function observableToWritable(observable: Observable<Uint8Array>): WritableStream<Uint8Array>;
27
+ /**
28
+ * Subscribe to an Observable and write its values to a WritableStream.
29
+ *
30
+ * This utility function subscribes to an RxJS Observable and writes all emitted values
31
+ * to the provided WritableStream. This is commonly used to write Observable data to a
32
+ * serial port's writable stream.
33
+ *
34
+ * The function returns a subscription object that can be used to unsubscribe and clean up.
35
+ * When unsubscribed, the writer lock will be released properly.
36
+ *
37
+ * @param observable - The Observable to subscribe to and read data from
38
+ * @param stream - The WritableStream to write data to
39
+ * @returns A subscription object with an `unsubscribe` method for cleanup
40
+ * @throws {@link SerialError} with code {@link SerialErrorCode.WRITE_FAILED} if writing to the stream fails
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * const data$ = from([
45
+ * new TextEncoder().encode('Hello'),
46
+ * new TextEncoder().encode('World'),
47
+ * ]);
48
+ *
49
+ * const subscription = subscribeToWritable(data$, port.writable);
50
+ *
51
+ * // Later, to cancel and clean up:
52
+ * subscription.unsubscribe();
53
+ *
54
+ * // Use with RxJS operators
55
+ * const processedData$ = of('Hello, Serial!').pipe(
56
+ * map((text) => new TextEncoder().encode(text))
57
+ * );
58
+ *
59
+ * subscribeToWritable(processedData$, port.writable);
60
+ * ```
61
+ */
62
+ export declare function subscribeToWritable(observable: Observable<Uint8Array>, stream: WritableStream<Uint8Array>): {
63
+ unsubscribe: () => void;
64
+ };
65
+ //# sourceMappingURL=observable-to-writable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observable-to-writable.d.ts","sourceRoot":"","sources":["../../src/io/observable-to-writable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGlC;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,oBAAoB,CAClC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,UAAU,CAAC,CAqE5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,mBAAmB,CACjC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,EAClC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC;IAAE,WAAW,EAAE,MAAM,IAAI,CAAA;CAAE,CAiD7B"}
@@ -0,0 +1,44 @@
1
+ import { Observable } from 'rxjs';
2
+ /**
3
+ * Convert a ReadableStream to an RxJS Observable.
4
+ *
5
+ * This utility function converts a Web Streams API ReadableStream into an RxJS Observable,
6
+ * allowing you to use RxJS operators with stream data. The Observable will emit Uint8Array
7
+ * chunks as they are read from the stream, complete when the stream ends, or error if
8
+ * the stream encounters an error.
9
+ *
10
+ * The returned Observable handles stream cleanup automatically - if you unsubscribe before
11
+ * the stream completes, the reader lock will be released properly.
12
+ *
13
+ * @param stream - The ReadableStream to convert to an Observable
14
+ * @returns An Observable that emits Uint8Array chunks from the stream
15
+ * @throws {@link SerialError} with code {@link SerialErrorCode.READ_FAILED} if reading from the stream fails
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // Convert a serial port's readable stream to an Observable
20
+ * const readable$ = readableToObservable(port.readable);
21
+ *
22
+ * readable$.subscribe({
23
+ * next: (chunk) => {
24
+ * console.log('Received chunk:', chunk);
25
+ * },
26
+ * complete: () => {
27
+ * console.log('Stream completed');
28
+ * },
29
+ * error: (error) => {
30
+ * console.error('Stream error:', error);
31
+ * },
32
+ * });
33
+ *
34
+ * // Use with RxJS operators
35
+ * readableToObservable(port.readable)
36
+ * .pipe(
37
+ * map((chunk) => new TextDecoder().decode(chunk)),
38
+ * filter((text) => text.includes('OK'))
39
+ * )
40
+ * .subscribe((text) => console.log('Filtered text:', text));
41
+ * ```
42
+ */
43
+ export declare function readableToObservable(stream: ReadableStream<Uint8Array>): Observable<Uint8Array>;
44
+ //# sourceMappingURL=readable-to-observable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readable-to-observable.d.ts","sourceRoot":"","sources":["../../src/io/readable-to-observable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AAGlC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,UAAU,CAAC,UAAU,CAAC,CAoDxB"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Utility function that returns the library name.
3
+ *
4
+ * @returns The library name as a string: 'web-serial-rxjs'
5
+ */
6
+ export declare function webSerialRxjs(): string;
7
+ //# sourceMappingURL=web-serial-rxjs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-serial-rxjs.d.ts","sourceRoot":"","sources":["../../src/lib/web-serial-rxjs.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAEtC"}
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Options for creating a SerialClient instance.
3
+ *
4
+ * These options configure the serial port connection parameters. All properties are optional
5
+ * and will use default values if not specified. See {@link DEFAULT_SERIAL_CLIENT_OPTIONS} for
6
+ * the default values used.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * const client = createSerialClient({
11
+ * baudRate: 115200,
12
+ * dataBits: 8,
13
+ * stopBits: 1,
14
+ * parity: 'none',
15
+ * flowControl: 'none',
16
+ * filters: [{ usbVendorId: 0x1234, usbProductId: 0x5678 }],
17
+ * });
18
+ * ```
19
+ */
20
+ export interface SerialClientOptions {
21
+ /**
22
+ * Baud rate for the serial port connection (bits per second).
23
+ *
24
+ * Common values include 9600, 19200, 38400, 57600, 115200, etc.
25
+ * Must match the baud rate configured on the connected device.
26
+ *
27
+ * @default 9600
28
+ */
29
+ baudRate?: number;
30
+ /**
31
+ * Number of data bits per character (7 or 8).
32
+ *
33
+ * - `7`: Seven data bits (used with parity)
34
+ * - `8`: Eight data bits (most common, used without parity)
35
+ *
36
+ * @default 8
37
+ */
38
+ dataBits?: 7 | 8;
39
+ /**
40
+ * Number of stop bits (1 or 2).
41
+ *
42
+ * - `1`: One stop bit (most common)
43
+ * - `2`: Two stop bits (less common, used for slower devices)
44
+ *
45
+ * @default 1
46
+ */
47
+ stopBits?: 1 | 2;
48
+ /**
49
+ * Parity checking mode.
50
+ *
51
+ * - `'none'`: No parity checking (most common)
52
+ * - `'even'`: Even parity
53
+ * - `'odd'`: Odd parity
54
+ *
55
+ * @default 'none'
56
+ */
57
+ parity?: 'none' | 'even' | 'odd';
58
+ /**
59
+ * Buffer size for reading data from the serial port, in bytes.
60
+ *
61
+ * This determines how much data can be buffered before it needs to be read.
62
+ * Larger buffers can improve performance but use more memory.
63
+ *
64
+ * @default 255
65
+ */
66
+ bufferSize?: number;
67
+ /**
68
+ * Flow control mode.
69
+ *
70
+ * - `'none'`: No flow control (most common)
71
+ * - `'hardware'`: Hardware flow control (RTS/CTS)
72
+ *
73
+ * @default 'none'
74
+ */
75
+ flowControl?: 'none' | 'hardware';
76
+ /**
77
+ * Filters for port selection when requesting a port.
78
+ *
79
+ * When specified, the port selection dialog will only show devices matching
80
+ * these filters. Each filter can specify `usbVendorId` and/or `usbProductId`
81
+ * to filter by USB device identifiers.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * filters: [
86
+ * { usbVendorId: 0x1234 },
87
+ * { usbVendorId: 0x1234, usbProductId: 0x5678 },
88
+ * ]
89
+ * ```
90
+ *
91
+ * @see {@link SerialPortFilter} for the filter structure
92
+ */
93
+ filters?: SerialPortFilter[];
94
+ }
95
+ /**
96
+ * Default options for SerialClient instances.
97
+ *
98
+ * These are the default values used when creating a SerialClient if no options
99
+ * are provided or if specific options are omitted. The values are chosen to work
100
+ * with most common serial devices.
101
+ *
102
+ * @see {@link SerialClientOptions} for details on each option
103
+ */
104
+ export declare const DEFAULT_SERIAL_CLIENT_OPTIONS: Required<Omit<SerialClientOptions, 'filters'>> & {
105
+ filters?: SerialPortFilter[];
106
+ };
107
+ //# sourceMappingURL=options.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../src/types/options.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAEjB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IAEjB;;;;;;;;OAQG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;IAEjC;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAElC;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC;CAC9B;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,6BAA6B,EAAE,QAAQ,CAClD,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CACrC,GAAG;IAAE,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAA;CAQjC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gurezo/web-serial-rxjs",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "description": "A TypeScript library that provides a reactive RxJS-based wrapper for the Web Serial API, enabling easy serial port communication in web applications.",
5
5
  "author": "Akihiko Kigure <akihiko.kigure@gmail.com>",
6
6
  "license": "MIT",
@@ -19,6 +19,15 @@
19
19
  "README.ja.md",
20
20
  "LICENSE"
21
21
  ],
22
+ "scripts": {
23
+ "build": "pnpm run build:types && pnpm run build:bundle && pnpm run build:copy-files && pnpm run build:cleanup",
24
+ "build:types": "../../node_modules/.bin/tsc --project tsconfig.lib.json",
25
+ "build:bundle": "node esbuild.config.mjs",
26
+ "build:copy-files": "cp ../../LICENSE . 2>/dev/null || true",
27
+ "build:cleanup": "rm -rf dist/packages dist/package.json 2>/dev/null || true",
28
+ "clean": "rm -rf dist",
29
+ "prepublishOnly": "pnpm run build"
30
+ },
22
31
  "dependencies": {},
23
32
  "peerDependencies": {
24
33
  "rxjs": "^7.8.0"
@@ -43,12 +52,5 @@
43
52
  ],
44
53
  "publishConfig": {
45
54
  "access": "public"
46
- },
47
- "scripts": {
48
- "build": "pnpm run build:types && pnpm run build:bundle && pnpm run build:copy-files",
49
- "build:types": "tsc --project tsconfig.lib.json",
50
- "build:bundle": "node esbuild.config.mjs",
51
- "build:copy-files": "cp ../../LICENSE . 2>/dev/null || true",
52
- "clean": "rm -rf dist"
53
55
  }
54
- }
56
+ }