@gurezo/web-serial-rxjs 0.1.21 → 2.0.0
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.
- package/README.ja.md +82 -13
- package/README.md +82 -13
- package/dist/errors/serial-error-code.d.ts +7 -0
- package/dist/errors/serial-error-code.d.ts.map +1 -1
- package/dist/index.d.ts +31 -30
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +469 -449
- package/dist/index.mjs +469 -449
- package/dist/index.mjs.map +4 -4
- package/dist/session/create-serial-session.d.ts +49 -0
- package/dist/session/create-serial-session.d.ts.map +1 -0
- package/dist/session/index.d.ts +5 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/internal/build-request-options.d.ts +18 -0
- package/dist/session/internal/build-request-options.d.ts.map +1 -0
- package/dist/session/internal/has-web-serial-support.d.ts +12 -0
- package/dist/session/internal/has-web-serial-support.d.ts.map +1 -0
- package/dist/session/internal/line-buffer.d.ts +14 -0
- package/dist/session/internal/line-buffer.d.ts.map +1 -0
- package/dist/session/normalize-serial-error.d.ts +55 -0
- package/dist/session/normalize-serial-error.d.ts.map +1 -0
- package/dist/session/read-pump.d.ts +74 -0
- package/dist/session/read-pump.d.ts.map +1 -0
- package/dist/session/send-queue.d.ts +58 -0
- package/dist/session/send-queue.d.ts.map +1 -0
- package/dist/session/serial-session-options.d.ts +80 -0
- package/dist/session/serial-session-options.d.ts.map +1 -0
- package/dist/session/serial-session-state.d.ts +35 -0
- package/dist/session/serial-session-state.d.ts.map +1 -0
- package/dist/session/serial-session.d.ts +143 -0
- package/dist/session/serial-session.d.ts.map +1 -0
- package/dist/session/session-state-machine.d.ts +39 -0
- package/dist/session/session-state-machine.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/browser/browser-detection.d.ts +0 -104
- package/dist/browser/browser-detection.d.ts.map +0 -1
- package/dist/browser/browser-support.d.ts +0 -57
- package/dist/browser/browser-support.d.ts.map +0 -1
- package/dist/client/index.d.ts +0 -250
- package/dist/client/index.d.ts.map +0 -1
- package/dist/client/serial-client.d.ts +0 -98
- package/dist/client/serial-client.d.ts.map +0 -1
- package/dist/filters/build-request-options.d.ts +0 -42
- package/dist/filters/build-request-options.d.ts.map +0 -1
- package/dist/io/observable-to-writable.d.ts +0 -65
- package/dist/io/observable-to-writable.d.ts.map +0 -1
- package/dist/io/readable-to-observable.d.ts +0 -44
- package/dist/io/readable-to-observable.d.ts.map +0 -1
- package/dist/lib/web-serial-rxjs.d.ts +0 -7
- package/dist/lib/web-serial-rxjs.d.ts.map +0 -1
- package/dist/types/options.d.ts +0 -107
- package/dist/types/options.d.ts.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/
|
|
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,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,OAAO,KAAK,CAAC;AAAA,QAC1D;AAAA,MACF,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAI,YAAqB;AACvB,WAAO,KAAK;AAAA,EACd;AAAA;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", "
|
|
3
|
+
"sources": ["../src/session/create-serial-session.ts", "../src/errors/serial-error-code.ts", "../src/errors/serial-error.ts", "../src/session/internal/build-request-options.ts", "../src/session/internal/has-web-serial-support.ts", "../src/session/internal/line-buffer.ts", "../src/session/normalize-serial-error.ts", "../src/session/read-pump.ts", "../src/session/send-queue.ts", "../src/session/serial-session-options.ts", "../src/session/serial-session-state.ts", "../src/session/session-state-machine.ts"],
|
|
4
|
+
"sourcesContent": ["import { distinctUntilChanged, map, Observable, Subject } from 'rxjs';\nimport { SerialError } from '../errors/serial-error';\nimport { SerialErrorCode } from '../errors/serial-error-code';\nimport { buildRequestOptions } from './internal/build-request-options';\nimport { hasWebSerialSupport } from './internal/has-web-serial-support';\nimport { createLineBuffer } from './internal/line-buffer';\nimport {\n normalizeSerialError,\n type NormalizeSerialErrorOptions,\n} from './normalize-serial-error';\nimport { createReadPump, type ReadPump } from './read-pump';\nimport { createSendQueue } from './send-queue';\nimport type { SerialSession } from './serial-session';\nimport {\n DEFAULT_SERIAL_SESSION_OPTIONS,\n type SerialSessionOptions,\n} from './serial-session-options';\nimport { SerialSessionState } from './serial-session-state';\nimport { SessionStateMachine } from './session-state-machine';\n\n/**\n * Internal error classification used by the single `reportError` entry\n * point. `'fatal'` errors drive `state$` into `'error'` and tear down\n * the live session (pump stop + port close); `'non-fatal'` errors are\n * only multiplexed on `errors$` without mutating session state - this\n * matches the Issue #199 design note that write failures must not\n * implicitly disconnect the session.\n *\n * @internal\n */\ntype ReportErrorSeverity = 'fatal' | 'non-fatal';\n\n/**\n * Create a v2 {@link SerialSession}.\n *\n * This release wires the internal read pump (#202) and the internal send\n * queue (#203) into the session so that `connect$`, `disconnect$`,\n * `receive$`, and `send$` all operate end-to-end. Error handling is\n * centralised through a single `reportError` helper (#204) so every\n * failure path normalises through {@link normalizeSerialError} and emits\n * on the one `errors$` channel.\n *\n * Key behaviors:\n *\n * - `isBrowserSupported()` returns whether `navigator.serial` is available.\n * - `state$` replays the current lifecycle state driven by\n * {@link SessionStateMachine}.\n * - `connect$()` opens a user-selected port, starts the internal read pump,\n * and transitions `idle -> connecting -> connected`.\n * - `disconnect$()` stops the read pump, closes the port, and transitions\n * `connected -> disconnecting -> idle`.\n * - `receive$` emits UTF-8 decoded text chunks pushed by the pump. It is\n * **not** subscription-lazy - the pump is started by `connect$` and\n * decoded text is multicast to all subscribers; late subscribers see only\n * new data.\n * - `lines$` emits the same decoded stream split into line-terminated\n * segments (`\\n`, `\\r\\n`); a trailing line without a terminator is\n * buffered. It is also not subscription-lazy relative to the pump.\n * - `send$` enqueues each payload on an internal FIFO queue so concurrent\n * subscribers are written to the port in call order. String payloads are\n * UTF-8 encoded through a shared `TextEncoder`.\n * - `errors$` multiplexes every {@link SerialError} produced by the\n * session. Connect / read / close failures are treated as fatal and\n * also drive `state$` to `'error'`; write failures are non-fatal and\n * do not mutate `state$` because a real connection loss will be\n * observed by the read pump on the next tick anyway.\n *\n * @param options - Session options. Only `filters` is consulted by\n * `connect$` today (forwarded to `navigator.serial.requestPort`); the\n * remaining fields are passed to `port.open` using defaults when omitted.\n * @returns A {@link SerialSession} instance.\n *\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/202 | Issue #202}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/203 | Issue #203}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/204 | Issue #204}\n */\nexport function createSerialSession(\n options?: SerialSessionOptions,\n): SerialSession {\n const resolvedOptions = {\n ...DEFAULT_SERIAL_SESSION_OPTIONS,\n ...options,\n filters: options?.filters,\n };\n\n const supported = hasWebSerialSupport();\n const machine = new SessionStateMachine(\n supported ? SerialSessionState.Idle : SerialSessionState.Unsupported,\n );\n const errorsSubject = new Subject<SerialError>();\n const receiveSubject = new Subject<string>();\n const linesSubject = new Subject<string>();\n const sendQueue = createSendQueue();\n const textEncoder = new TextEncoder();\n const lineBuffer = createLineBuffer();\n\n const errors$ = errorsSubject.asObservable();\n const receive$ = receiveSubject.asObservable();\n const lines$ = linesSubject.asObservable();\n\n const isConnected$ = machine.state$.pipe(\n map((state) => state === SerialSessionState.Connected),\n distinctUntilChanged(),\n );\n\n let activePort: SerialPort | null = null;\n let activePump: ReadPump | null = null;\n\n const teardownPump = async (): Promise<void> => {\n const pump = activePump;\n activePump = null;\n lineBuffer.clear();\n if (pump) {\n await pump.stop();\n }\n };\n\n const closePortSafely = async (port: SerialPort | null): Promise<void> => {\n if (!port) {\n return;\n }\n try {\n await port.close();\n } catch {\n // The read pump may already have errored the stream, which makes\n // close() reject. We ignore it here because disconnect$ has a\n // dedicated error path for close failures initiated by the user.\n }\n };\n\n /**\n * Single entry point for every error that should reach `errors$`.\n *\n * Responsibilities:\n *\n * 1. Normalise the input through {@link normalizeSerialError} so every\n * emission is a well-formed {@link SerialError}.\n * 2. Multiplex the normalised error on `errors$`.\n * 3. For fatal severities, drive `state$` to `'error'`, clear the send\n * queue so pending writes fail fast, and tear down the live pump +\n * port off the hot path.\n *\n * Returning the normalised error keeps call sites terse: they can hand\n * the result straight to `subscriber.error(...)` without re-normalising.\n */\n const reportError = (\n error: unknown,\n severity: ReportErrorSeverity,\n options: NormalizeSerialErrorOptions,\n ): SerialError => {\n const serialError = normalizeSerialError(error, options);\n errorsSubject.next(serialError);\n if (severity === 'fatal') {\n machine.toError();\n sendQueue.clear();\n const portToClose = activePort;\n activePort = null;\n void teardownPump().then(() => closePortSafely(portToClose));\n }\n return serialError;\n };\n\n const writeToPort = async (payload: Uint8Array): Promise<void> => {\n const port = activePort;\n if (machine.current !== SerialSessionState.Connected || !port || !port.writable) {\n throw new SerialError(\n SerialErrorCode.PORT_NOT_OPEN,\n 'Cannot send data while session is not connected',\n );\n }\n const writer = port.writable.getWriter();\n try {\n await writer.write(payload);\n } finally {\n try {\n writer.releaseLock();\n } catch {\n // releaseLock throws when the stream is already errored; the real\n // failure is surfaced through the write() rejection above so we\n // intentionally swallow this secondary error.\n }\n }\n };\n\n return {\n isBrowserSupported(): boolean {\n return hasWebSerialSupport();\n },\n connect$(): Observable<void> {\n return new Observable<void>((subscriber) => {\n if (!hasWebSerialSupport()) {\n const error = reportError(\n new SerialError(\n SerialErrorCode.BROWSER_NOT_SUPPORTED,\n 'Web Serial API is not supported in this environment',\n ),\n 'non-fatal',\n { fallbackCode: SerialErrorCode.BROWSER_NOT_SUPPORTED },\n );\n subscriber.error(error);\n return;\n }\n\n const current = machine.current;\n if (\n current !== SerialSessionState.Idle &&\n current !== SerialSessionState.Error\n ) {\n const error = reportError(\n new SerialError(\n SerialErrorCode.PORT_ALREADY_OPEN,\n `Cannot connect while session state is '${current}'`,\n ),\n 'non-fatal',\n { fallbackCode: SerialErrorCode.PORT_ALREADY_OPEN },\n );\n subscriber.error(error);\n return;\n }\n\n let cancelled = false;\n machine.toConnecting();\n\n const run = async (): Promise<void> => {\n let selectedPort: SerialPort | null = null;\n try {\n selectedPort = await navigator.serial.requestPort(\n buildRequestOptions(resolvedOptions),\n );\n await selectedPort.open({\n baudRate: resolvedOptions.baudRate,\n dataBits: resolvedOptions.dataBits,\n stopBits: resolvedOptions.stopBits,\n parity: resolvedOptions.parity,\n bufferSize: resolvedOptions.bufferSize,\n flowControl: resolvedOptions.flowControl,\n });\n } catch (error) {\n if (selectedPort) {\n await closePortSafely(selectedPort);\n }\n activePort = null;\n const serialError = reportError(error, 'fatal', {\n fallbackCode: SerialErrorCode.PORT_OPEN_FAILED,\n messagePrefix: 'Failed to open port',\n });\n if (!cancelled) {\n subscriber.error(serialError);\n }\n return;\n }\n\n if (cancelled) {\n await closePortSafely(selectedPort);\n return;\n }\n\n activePort = selectedPort;\n lineBuffer.clear();\n activePump = createReadPump(selectedPort, {\n onChunk: (text) => {\n receiveSubject.next(text);\n for (const line of lineBuffer.feed(text)) {\n linesSubject.next(line);\n }\n },\n onError: (pumpError) =>\n reportError(pumpError, 'fatal', {\n fallbackCode: SerialErrorCode.READ_FAILED,\n messagePrefix: 'Read pump failed',\n }),\n });\n activePump.start();\n sendQueue.clear();\n machine.toConnected();\n subscriber.next();\n subscriber.complete();\n };\n\n void run();\n\n return () => {\n cancelled = true;\n };\n });\n },\n disconnect$(): Observable<void> {\n return new Observable<void>((subscriber) => {\n const current = machine.current;\n\n if (\n current === SerialSessionState.Idle ||\n current === SerialSessionState.Unsupported\n ) {\n subscriber.next();\n subscriber.complete();\n return;\n }\n\n if (\n current !== SerialSessionState.Connected &&\n current !== SerialSessionState.Error\n ) {\n const error = reportError(\n new SerialError(\n SerialErrorCode.PORT_NOT_OPEN,\n `Cannot disconnect while session state is '${current}'`,\n ),\n 'non-fatal',\n { fallbackCode: SerialErrorCode.PORT_NOT_OPEN },\n );\n subscriber.error(error);\n return;\n }\n\n machine.toDisconnecting();\n sendQueue.clear();\n const portToClose = activePort;\n\n const run = async (): Promise<void> => {\n try {\n await teardownPump();\n if (portToClose) {\n try {\n await portToClose.close();\n } catch (error) {\n activePort = null;\n const serialError = reportError(error, 'fatal', {\n fallbackCode: SerialErrorCode.CONNECTION_LOST,\n messagePrefix: 'Failed to close port',\n });\n subscriber.error(serialError);\n return;\n }\n }\n activePort = null;\n machine.toIdle();\n subscriber.next();\n subscriber.complete();\n } catch (error) {\n const serialError = reportError(error, 'fatal', {\n fallbackCode: SerialErrorCode.UNKNOWN,\n messagePrefix: 'Unexpected disconnect failure',\n });\n subscriber.error(serialError);\n }\n };\n\n void run();\n });\n },\n send$(data: string | Uint8Array): Observable<void> {\n return sendQueue.enqueue(async () => {\n const payload =\n typeof data === 'string' ? textEncoder.encode(data) : data;\n try {\n await writeToPort(payload);\n } catch (error) {\n throw reportError(error, 'non-fatal', {\n fallbackCode: SerialErrorCode.WRITE_FAILED,\n messagePrefix: 'Failed to write data',\n });\n }\n });\n },\n state$: machine.state$,\n isConnected$,\n errors$,\n receive$,\n lines$,\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 * Operation timed out before completion.\n *\n * This error occurs when an operation waits for a condition (for example, prompt\n * detection) and the timeout period elapses first.\n */\n OPERATION_TIMEOUT = 'OPERATION_TIMEOUT',\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", "import { SerialError } from '../../errors/serial-error';\nimport { SerialErrorCode } from '../../errors/serial-error-code';\nimport type { SerialSessionOptions } from '../serial-session-options';\n\n/**\n * Build {@link SerialPortRequestOptions} from {@link SerialSessionOptions}.\n *\n * Converts the `filters` field of {@link SerialSessionOptions} into the\n * shape expected by `navigator.serial.requestPort` and validates USB\n * vendor / product identifiers. Returns `undefined` when no filters are\n * supplied so the browser shows all available ports.\n *\n * @param options - The session options supplied by the caller.\n * @returns The request options, or `undefined` when no filters are set.\n * @throws {@link SerialError} with {@link SerialErrorCode.INVALID_FILTER_OPTIONS}\n * when a filter is empty or contains out-of-range IDs.\n *\n * @internal\n */\nexport function buildRequestOptions(\n options?: SerialSessionOptions,\n): SerialPortRequestOptions | undefined {\n if (!options || !options.filters || options.filters.length === 0) {\n return undefined;\n }\n\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", "/**\n * Internal feature detection for the Web Serial API.\n *\n * This helper is intentionally kept package-private: the v2 public API\n * exposes browser support only through {@link SerialSession.isBrowserSupported}.\n *\n * @returns `true` when `navigator.serial` is available.\n *\n * @internal\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 * Streaming UTF-16 text to newline-delimited lines for {@link createSerialSession}.\n * Supports `\\r\\n` and `\\n` per #237; a lone `\\r` that is not the last character\n * in the buffer is treated as a line end (compatibility with some devices). A\n * trailing `\\r` is retained until a following chunk disambiguates `\\r` vs\n * `\\r\\n`.\n *\n * @internal\n */\nexport function createLineBuffer(): {\n feed(chunk: string): string[];\n clear(): void;\n} {\n let buffer = '';\n\n const clear = (): void => {\n buffer = '';\n };\n\n const feed = (chunk: string): string[] => {\n buffer += chunk;\n const out: string[] = [];\n\n for (;;) {\n const crlf = buffer.indexOf('\\r\\n');\n if (crlf >= 0) {\n out.push(buffer.slice(0, crlf));\n buffer = buffer.slice(crlf + 2);\n continue;\n }\n\n // Lone \\r (not the last character) is a line end so we must not let\n // a later \\n in the same buffer be matched first (e.g. \"a\\rb\\n\").\n const cr = buffer.indexOf('\\r');\n if (cr >= 0 && cr + 1 < buffer.length && buffer[cr + 1] !== '\\n') {\n out.push(buffer.slice(0, cr));\n buffer = buffer.slice(cr + 1);\n continue;\n }\n\n const nl = buffer.indexOf('\\n');\n if (nl >= 0) {\n out.push(buffer.slice(0, nl));\n buffer = buffer.slice(nl + 1);\n continue;\n }\n\n if (cr >= 0 && cr + 1 === buffer.length) {\n break;\n }\n\n break;\n }\n\n return out;\n };\n\n return { feed, clear };\n}\n", "import { SerialError } from '../errors/serial-error';\nimport { SerialErrorCode } from '../errors/serial-error-code';\n\n/**\n * Default human-readable prefix attached to normalized errors when the\n * caller does not supply one. Kept short so downstream messages remain\n * readable (e.g. `\"Serial operation failed: <cause>\"`).\n *\n * @internal\n */\nconst DEFAULT_MESSAGE_PREFIX = 'Serial operation failed';\n\n/**\n * Options accepted by {@link normalizeSerialError}.\n *\n * @internal\n */\nexport interface NormalizeSerialErrorOptions {\n /**\n * Error code assigned when the input cannot be classified more\n * specifically (for example a generic `Error` thrown from `port.open`).\n *\n * Most call sites in the session pipeline know which lifecycle phase\n * they are in (connect / read / write / close) and therefore pick a\n * phase-specific fallback such as {@link SerialErrorCode.PORT_OPEN_FAILED}\n * or {@link SerialErrorCode.WRITE_FAILED}.\n */\n fallbackCode: SerialErrorCode;\n /**\n * Prefix used when the input has to be wrapped. Ignored when the input\n * is already a {@link SerialError} so we never rewrite a well-formed\n * message the caller has already chosen.\n */\n messagePrefix?: string;\n}\n\nconst isDomExceptionWithName = (\n error: unknown,\n name: string,\n): error is DOMException =>\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === name;\n\n/**\n * Normalize an arbitrary thrown value into a {@link SerialError}.\n *\n * This helper is the single entry point used by every v2 session\n * component (session factory, read pump, send queue) to coerce raw\n * platform errors into the library's error type. Centralising the\n * mapping here satisfies Issue #204's completion criterion that\n * \"error handling lives in one place\" and removes the duplicated\n * `toError` / `normalizeError` helpers previously scattered across\n * session modules.\n *\n * Mapping rules applied, in order:\n *\n * 1. `SerialError` instances pass through unchanged so a caller that has\n * already classified the failure (e.g. `PORT_NOT_OPEN` on a pre-open\n * `send$`) is not rewrapped.\n * 2. `DOMException('NotFoundError')` is mapped to\n * {@link SerialErrorCode.OPERATION_CANCELLED}. Chromium raises this\n * when the user dismisses the `requestPort` dialog; it is a normal\n * control-flow event, not a hard failure.\n * 3. Any other value is wrapped as a {@link SerialError} with\n * {@link NormalizeSerialErrorOptions.fallbackCode}, preserving the\n * original error as `originalError` for debugging.\n *\n * @internal\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/204 | Issue #204}\n */\nexport function normalizeSerialError(\n error: unknown,\n options: NormalizeSerialErrorOptions,\n): SerialError {\n if (error instanceof SerialError) {\n return error;\n }\n\n const prefix = options.messagePrefix ?? DEFAULT_MESSAGE_PREFIX;\n\n if (isDomExceptionWithName(error, 'NotFoundError')) {\n return new SerialError(\n SerialErrorCode.OPERATION_CANCELLED,\n 'Port selection was cancelled by the user',\n error,\n );\n }\n\n const cause = error instanceof Error ? error : new Error(String(error));\n return new SerialError(\n options.fallbackCode,\n `${prefix}: ${cause.message}`,\n cause,\n );\n}\n", "import { SerialError } from '../errors/serial-error';\nimport { SerialErrorCode } from '../errors/serial-error-code';\nimport { normalizeSerialError } from './normalize-serial-error';\n\n/**\n * Callback invoked for every decoded chunk the read pump produces.\n *\n * The text is decoded from the raw bytes using a shared `TextDecoder` with\n * `{ stream: true }`, so multi-byte characters that straddle chunk\n * boundaries are joined correctly before reaching the callback.\n *\n * @internal\n */\nexport type ReadPumpChunkHandler = (text: string) => void;\n\n/**\n * Callback invoked when the read pump cannot continue.\n *\n * The provided error is always a {@link SerialError}; raw platform errors\n * are normalized by the pump before they reach the caller so consumers only\n * ever observe the library's error type.\n *\n * @internal\n */\nexport type ReadPumpErrorHandler = (error: SerialError) => void;\n\n/**\n * Options accepted by {@link createReadPump}.\n *\n * @internal\n */\nexport interface ReadPumpOptions {\n onChunk: ReadPumpChunkHandler;\n onError: ReadPumpErrorHandler;\n}\n\n/**\n * Handle returned by {@link createReadPump}.\n *\n * @internal\n */\nexport interface ReadPump {\n /**\n * Start reading from the associated `SerialPort.readable` stream.\n *\n * Subsequent calls are ignored while the pump is already running.\n */\n start(): void;\n /**\n * Stop the read loop and release the underlying reader lock.\n *\n * Safe to call multiple times or before `start()`.\n */\n stop(): Promise<void>;\n /**\n * `true` while the internal loop is actively reading.\n */\n readonly isRunning: boolean;\n}\n\n/**\n * Create an internal read pump for a {@link SerialPort}.\n *\n * The pump is an implementation detail of the v2 `SerialSession` API: it\n * owns a single `TextDecoder` (with `stream: true`), drives a\n * `reader.read()` loop against `port.readable`, and forwards decoded text\n * to the provided sink. It is **not** subscription-lazy - the `SerialSession`\n * starts the pump as soon as `connect$` succeeds so that `receive$`\n * subscribers never miss data because of subscription timing.\n *\n * Errors are normalized into {@link SerialError} with\n * {@link SerialErrorCode.READ_FAILED} for read-side failures and\n * {@link SerialErrorCode.CONNECTION_LOST} for missing readable streams, so\n * the session can forward them to `errors$` without rewrapping.\n *\n * @internal\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/202 | Issue #202}\n */\nexport function createReadPump(\n port: SerialPort,\n { onChunk, onError }: ReadPumpOptions,\n): ReadPump {\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n let running = false;\n let stopped = false;\n const decoder = new TextDecoder(undefined, { fatal: false });\n\n const releaseReader = (): void => {\n if (!reader) {\n return;\n }\n try {\n reader.releaseLock();\n } catch {\n // releaseLock may throw when the reader is already detached; ignore.\n }\n reader = null;\n };\n\n const pump = async (stream: ReadableStream<Uint8Array>): Promise<void> => {\n reader = stream.getReader();\n running = true;\n try {\n while (!stopped) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value && value.byteLength > 0) {\n const text = decoder.decode(value, { stream: true });\n if (text.length > 0) {\n onChunk(text);\n }\n }\n }\n if (!stopped) {\n const tail = decoder.decode();\n if (tail.length > 0) {\n onChunk(tail);\n }\n }\n } catch (error) {\n if (!stopped) {\n onError(\n normalizeSerialError(error, {\n fallbackCode: SerialErrorCode.READ_FAILED,\n messagePrefix: 'Read pump failed',\n }),\n );\n }\n } finally {\n running = false;\n releaseReader();\n }\n };\n\n return {\n start(): void {\n if (running || stopped) {\n return;\n }\n const stream = port.readable;\n if (!stream) {\n stopped = true;\n onError(\n new SerialError(\n SerialErrorCode.CONNECTION_LOST,\n 'Read pump failed: port.readable is not available',\n ),\n );\n return;\n }\n void pump(stream);\n },\n async stop(): Promise<void> {\n if (stopped) {\n return;\n }\n stopped = true;\n if (!reader) {\n return;\n }\n try {\n await reader.cancel();\n } catch {\n // Cancel can reject when the stream is already errored; ignore so\n // the caller's disconnect flow is not derailed by a read failure.\n } finally {\n releaseReader();\n }\n },\n get isRunning(): boolean {\n return running;\n },\n };\n}\n", "import { Observable, defer } from 'rxjs';\n\n/**\n * A single enqueued unit of work. Operations are awaited sequentially so\n * that `send$` guarantees call order even when the caller fires multiple\n * observables concurrently.\n *\n * @internal\n */\nexport type SendQueueOperation<T> = () => Promise<T>;\n\n/**\n * Internal helper returned by {@link createSendQueue}.\n *\n * The queue is intentionally not an RxJS operator because Issue #199 calls\n * out explicitly that `send$` must not be re-implemented with `mergeMap`\n * (or any other concurrency-altering operator). A chained `Promise<void>`\n * is the simplest way to guarantee strict FIFO ordering while still\n * surfacing per-operation completion back to the caller.\n *\n * @internal\n */\nexport interface SendQueue {\n /**\n * Schedule an operation to run after all previously enqueued operations\n * have settled (resolved or rejected). The returned Observable completes\n * with the operation's resolved value, or errors with its rejection.\n *\n * Subscribing is what actually schedules the work - the queue is driven\n * by `defer`, so late/never-subscribed Observables never enqueue.\n */\n enqueue<T>(operation: SendQueueOperation<T>): Observable<T>;\n /**\n * Reset the internal promise chain. Existing in-flight operations keep\n * running because we do not cancel native promises, but no newly\n * enqueued work will wait for them. Use this when the session is torn\n * down so a fresh `connect$` starts with a clean chain.\n */\n clear(): void;\n}\n\n/**\n * Create an internal send queue that serialises `send$` writes.\n *\n * Ordering model:\n *\n * - Each `enqueue` call appends its operation to a single `Promise<void>`\n * chain.\n * - A failure in one operation does not poison the chain - the next\n * operation still runs (the chain is advanced with a `.then(() => {},\n * () => {})` safety tail).\n * - Unsubscribing before the operation resolves suppresses `next` /\n * `complete` / `error` for that subscriber; the underlying promise is\n * still awaited so later operations continue to respect call order.\n *\n * @internal\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/203 | Issue #203}\n */\nexport function createSendQueue(): SendQueue {\n let chain: Promise<void> = Promise.resolve();\n\n return {\n enqueue<T>(operation: SendQueueOperation<T>): Observable<T> {\n return defer(\n () =>\n new Observable<T>((subscriber) => {\n let cancelled = false;\n\n const run = async (): Promise<void> => {\n try {\n const value = await operation();\n if (!cancelled) {\n subscriber.next(value);\n subscriber.complete();\n }\n } catch (error) {\n if (!cancelled) {\n subscriber.error(error);\n }\n }\n };\n\n const scheduled = chain.then(run, run);\n chain = scheduled.then(\n () => undefined,\n () => undefined,\n );\n\n return () => {\n cancelled = true;\n };\n }),\n );\n },\n clear(): void {\n chain = Promise.resolve();\n },\n };\n}\n", "/**\n * Options for creating a {@link SerialSession} via {@link createSerialSession}.\n *\n * These options configure the serial port connection parameters used when\n * calling `port.open` and `navigator.serial.requestPort`. All properties\n * are optional; omitted fields fall back to {@link DEFAULT_SERIAL_SESSION_OPTIONS}.\n *\n * @example\n * ```typescript\n * const session = createSerialSession({\n * baudRate: 115200,\n * dataBits: 8,\n * stopBits: 1,\n * parity: 'none',\n * flowControl: 'none',\n * filters: [{ usbVendorId: 0x1234, usbProductId: 0x5678 }],\n * });\n * ```\n *\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/200 | Issue #200}\n */\nexport interface SerialSessionOptions {\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 * @default 8\n */\n dataBits?: 7 | 8;\n\n /**\n * Number of stop bits (1 or 2).\n *\n * @default 1\n */\n stopBits?: 1 | 2;\n\n /**\n * Parity checking mode.\n *\n * @default 'none'\n */\n parity?: 'none' | 'even' | 'odd';\n\n /**\n * Buffer size for the underlying read stream, in bytes.\n *\n * @default 255\n */\n bufferSize?: number;\n\n /**\n * Flow control mode.\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\n * matching these filters. Each filter can specify `usbVendorId` and/or\n * `usbProductId`.\n */\n filters?: SerialPortFilter[];\n}\n\n/**\n * Default values applied to omitted {@link SerialSessionOptions} fields.\n *\n * @internal\n */\nexport const DEFAULT_SERIAL_SESSION_OPTIONS: Required<\n Omit<SerialSessionOptions, '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", "/**\n * Reactive lifecycle state for a {@link SerialSession}.\n *\n * This is the v2 API counterpart of the legacy `SerialState` used by\n * `SerialClient`. The runtime values are the same flat strings v1\n * consumers used for UI switches; the {@link SerialSessionState} const\n * object is the canonical source of those literals so call sites can\n * avoid string typos and get IDE completion.\n *\n * Lifecycle transitions:\n *\n * ```\n * idle -> connecting -> connected -> disconnecting -> idle\n * \\-> error\n * (any) -> unsupported (when Web Serial API is unavailable)\n * (any) -> error (when an unrecoverable failure occurs)\n * ```\n *\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/200 | Issue #200}\n */\nexport const SerialSessionState = {\n Idle: 'idle',\n Connecting: 'connecting',\n Connected: 'connected',\n Disconnecting: 'disconnecting',\n Unsupported: 'unsupported',\n Error: 'error',\n} as const;\n\n/**\n * String union of allowed {@link SerialSessionState} runtime values\n * (same set as the values on the {@link SerialSessionState} object).\n */\nexport type SerialSessionState =\n (typeof SerialSessionState)[keyof typeof SerialSessionState];\n", "import { BehaviorSubject, Observable } from 'rxjs';\nimport { SerialSessionState } from './serial-session-state';\n\n/**\n * Allowed transitions for the internal SerialSession state machine.\n *\n * Keys are the source state, values are the set of states that the source\n * is allowed to transition into. Transitions missing from this map are\n * treated as invalid and silently rejected (with a `console.warn`) so that\n * a logic bug in one sub-issue cannot corrupt `state$` for downstream\n * consumers.\n *\n * Lifecycle model (matches {@link SerialSessionState}):\n *\n * ```\n * idle -> connecting -> connected -> disconnecting -> idle\n * \\-> error\n * error -> idle (reset / retry)\n * unsupported (terminal; entered only at construction time)\n * ```\n *\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}\n * @see {@link https://github.com/gurezo/web-serial-rxjs/issues/201 | Issue #201}\n */\nconst S = SerialSessionState;\n\nconst ALLOWED_TRANSITIONS: Readonly<\n Record<SerialSessionState, readonly SerialSessionState[]>\n> = {\n [S.Idle]: [S.Connecting, S.Error],\n [S.Connecting]: [S.Connected, S.Error, S.Idle],\n [S.Connected]: [S.Disconnecting, S.Error],\n [S.Disconnecting]: [S.Idle, S.Error],\n [S.Error]: [S.Idle, S.Connecting],\n [S.Unsupported]: [],\n};\n\n/**\n * Internal state machine that backs {@link SerialSession.state$}.\n *\n * The machine is deliberately kept as an internal module (not exported\n * from the package) because the public surface is only the Observable.\n * Sub-issues of #199 (read pump / send queue / errors) drive transitions\n * through the dedicated `to*` methods below instead of mutating a shared\n * `BehaviorSubject` directly.\n *\n * Design notes:\n *\n * - Invalid transitions are silently rejected so that the `state$` stream\n * never emits a state that violates the lifecycle contract. A\n * `console.warn` is emitted in development builds to aid debugging.\n * - `unsupported` is terminal: once entered (during construction when\n * `navigator.serial` is missing), the machine refuses every further\n * transition.\n * - `state$` is derived from a {@link BehaviorSubject} so late subscribers\n * still receive the current state on subscription.\n *\n * @internal\n */\nexport class SessionStateMachine {\n private readonly subject: BehaviorSubject<SerialSessionState>;\n\n constructor(initial: SerialSessionState = SerialSessionState.Idle) {\n this.subject = new BehaviorSubject<SerialSessionState>(initial);\n }\n\n get current(): SerialSessionState {\n return this.subject.getValue();\n }\n\n get state$(): Observable<SerialSessionState> {\n return this.subject.asObservable();\n }\n\n toConnecting(): boolean {\n return this.transition(S.Connecting);\n }\n\n toConnected(): boolean {\n return this.transition(S.Connected);\n }\n\n toDisconnecting(): boolean {\n return this.transition(S.Disconnecting);\n }\n\n toIdle(): boolean {\n return this.transition(S.Idle);\n }\n\n toError(): boolean {\n return this.transition(S.Error);\n }\n\n toUnsupported(): boolean {\n return this.transition(S.Unsupported);\n }\n\n complete(): void {\n this.subject.complete();\n }\n\n private transition(next: SerialSessionState): boolean {\n const current = this.subject.getValue();\n\n if (current === next) {\n return false;\n }\n\n const allowed = ALLOWED_TRANSITIONS[current];\n if (!allowed.includes(next)) {\n if (typeof console !== 'undefined' && console.warn) {\n console.warn(\n `[web-serial-rxjs] Ignoring invalid SerialSession transition ${current} -> ${next}`,\n );\n }\n return false;\n }\n\n this.subject.next(next);\n return true;\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,sBAAsB,KAAK,cAAAA,aAAY,eAAe;;;AC0BxD,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;AAQtB,EAAAA,iBAAA,uBAAoB;AAUpB,EAAAA,iBAAA,aAAU;AAzHA,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,QAAK,MAAc,mBAAmB;AAEpC,MAAC,MAAc,kBAAkB,MAAM,YAAW;AAAA,IACpD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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,CAAC;AAAA,IACH;AAAA,IACA,QAAQ,QAAQ;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["Observable", "SerialErrorCode", "options", "Observable"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { SerialSession } from './serial-session';
|
|
2
|
+
import { type SerialSessionOptions } from './serial-session-options';
|
|
3
|
+
/**
|
|
4
|
+
* Create a v2 {@link SerialSession}.
|
|
5
|
+
*
|
|
6
|
+
* This release wires the internal read pump (#202) and the internal send
|
|
7
|
+
* queue (#203) into the session so that `connect$`, `disconnect$`,
|
|
8
|
+
* `receive$`, and `send$` all operate end-to-end. Error handling is
|
|
9
|
+
* centralised through a single `reportError` helper (#204) so every
|
|
10
|
+
* failure path normalises through {@link normalizeSerialError} and emits
|
|
11
|
+
* on the one `errors$` channel.
|
|
12
|
+
*
|
|
13
|
+
* Key behaviors:
|
|
14
|
+
*
|
|
15
|
+
* - `isBrowserSupported()` returns whether `navigator.serial` is available.
|
|
16
|
+
* - `state$` replays the current lifecycle state driven by
|
|
17
|
+
* {@link SessionStateMachine}.
|
|
18
|
+
* - `connect$()` opens a user-selected port, starts the internal read pump,
|
|
19
|
+
* and transitions `idle -> connecting -> connected`.
|
|
20
|
+
* - `disconnect$()` stops the read pump, closes the port, and transitions
|
|
21
|
+
* `connected -> disconnecting -> idle`.
|
|
22
|
+
* - `receive$` emits UTF-8 decoded text chunks pushed by the pump. It is
|
|
23
|
+
* **not** subscription-lazy - the pump is started by `connect$` and
|
|
24
|
+
* decoded text is multicast to all subscribers; late subscribers see only
|
|
25
|
+
* new data.
|
|
26
|
+
* - `lines$` emits the same decoded stream split into line-terminated
|
|
27
|
+
* segments (`\n`, `\r\n`); a trailing line without a terminator is
|
|
28
|
+
* buffered. It is also not subscription-lazy relative to the pump.
|
|
29
|
+
* - `send$` enqueues each payload on an internal FIFO queue so concurrent
|
|
30
|
+
* subscribers are written to the port in call order. String payloads are
|
|
31
|
+
* UTF-8 encoded through a shared `TextEncoder`.
|
|
32
|
+
* - `errors$` multiplexes every {@link SerialError} produced by the
|
|
33
|
+
* session. Connect / read / close failures are treated as fatal and
|
|
34
|
+
* also drive `state$` to `'error'`; write failures are non-fatal and
|
|
35
|
+
* do not mutate `state$` because a real connection loss will be
|
|
36
|
+
* observed by the read pump on the next tick anyway.
|
|
37
|
+
*
|
|
38
|
+
* @param options - Session options. Only `filters` is consulted by
|
|
39
|
+
* `connect$` today (forwarded to `navigator.serial.requestPort`); the
|
|
40
|
+
* remaining fields are passed to `port.open` using defaults when omitted.
|
|
41
|
+
* @returns A {@link SerialSession} instance.
|
|
42
|
+
*
|
|
43
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}
|
|
44
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/202 | Issue #202}
|
|
45
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/203 | Issue #203}
|
|
46
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/204 | Issue #204}
|
|
47
|
+
*/
|
|
48
|
+
export declare function createSerialSession(options?: SerialSessionOptions): SerialSession;
|
|
49
|
+
//# sourceMappingURL=create-serial-session.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-serial-session.d.ts","sourceRoot":"","sources":["../../src/session/create-serial-session.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,0BAA0B,CAAC;AAgBlC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,oBAAoB,GAC7B,aAAa,CAqSf"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createSerialSession } from './create-serial-session';
|
|
2
|
+
export type { SerialSession } from './serial-session';
|
|
3
|
+
export type { SerialSessionOptions } from './serial-session-options';
|
|
4
|
+
export { SerialSessionState } from './serial-session-state';
|
|
5
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/session/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,YAAY,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { SerialSessionOptions } from '../serial-session-options';
|
|
2
|
+
/**
|
|
3
|
+
* Build {@link SerialPortRequestOptions} from {@link SerialSessionOptions}.
|
|
4
|
+
*
|
|
5
|
+
* Converts the `filters` field of {@link SerialSessionOptions} into the
|
|
6
|
+
* shape expected by `navigator.serial.requestPort` and validates USB
|
|
7
|
+
* vendor / product identifiers. Returns `undefined` when no filters are
|
|
8
|
+
* supplied so the browser shows all available ports.
|
|
9
|
+
*
|
|
10
|
+
* @param options - The session options supplied by the caller.
|
|
11
|
+
* @returns The request options, or `undefined` when no filters are set.
|
|
12
|
+
* @throws {@link SerialError} with {@link SerialErrorCode.INVALID_FILTER_OPTIONS}
|
|
13
|
+
* when a filter is empty or contains out-of-range IDs.
|
|
14
|
+
*
|
|
15
|
+
* @internal
|
|
16
|
+
*/
|
|
17
|
+
export declare function buildRequestOptions(options?: SerialSessionOptions): SerialPortRequestOptions | undefined;
|
|
18
|
+
//# sourceMappingURL=build-request-options.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-request-options.d.ts","sourceRoot":"","sources":["../../../src/session/internal/build-request-options.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,CAAC,EAAE,oBAAoB,GAC7B,wBAAwB,GAAG,SAAS,CA2CtC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal feature detection for the Web Serial API.
|
|
3
|
+
*
|
|
4
|
+
* This helper is intentionally kept package-private: the v2 public API
|
|
5
|
+
* exposes browser support only through {@link SerialSession.isBrowserSupported}.
|
|
6
|
+
*
|
|
7
|
+
* @returns `true` when `navigator.serial` is available.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
export declare function hasWebSerialSupport(): boolean;
|
|
12
|
+
//# sourceMappingURL=has-web-serial-support.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"has-web-serial-support.d.ts","sourceRoot":"","sources":["../../../src/session/internal/has-web-serial-support.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAO7C"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streaming UTF-16 text to newline-delimited lines for {@link createSerialSession}.
|
|
3
|
+
* Supports `\r\n` and `\n` per #237; a lone `\r` that is not the last character
|
|
4
|
+
* in the buffer is treated as a line end (compatibility with some devices). A
|
|
5
|
+
* trailing `\r` is retained until a following chunk disambiguates `\r` vs
|
|
6
|
+
* `\r\n`.
|
|
7
|
+
*
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export declare function createLineBuffer(): {
|
|
11
|
+
feed(chunk: string): string[];
|
|
12
|
+
clear(): void;
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=line-buffer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"line-buffer.d.ts","sourceRoot":"","sources":["../../../src/session/internal/line-buffer.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,IAAI;IAClC,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAC9B,KAAK,IAAI,IAAI,CAAC;CACf,CA8CA"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { SerialError } from '../errors/serial-error';
|
|
2
|
+
import { SerialErrorCode } from '../errors/serial-error-code';
|
|
3
|
+
/**
|
|
4
|
+
* Options accepted by {@link normalizeSerialError}.
|
|
5
|
+
*
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export interface NormalizeSerialErrorOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Error code assigned when the input cannot be classified more
|
|
11
|
+
* specifically (for example a generic `Error` thrown from `port.open`).
|
|
12
|
+
*
|
|
13
|
+
* Most call sites in the session pipeline know which lifecycle phase
|
|
14
|
+
* they are in (connect / read / write / close) and therefore pick a
|
|
15
|
+
* phase-specific fallback such as {@link SerialErrorCode.PORT_OPEN_FAILED}
|
|
16
|
+
* or {@link SerialErrorCode.WRITE_FAILED}.
|
|
17
|
+
*/
|
|
18
|
+
fallbackCode: SerialErrorCode;
|
|
19
|
+
/**
|
|
20
|
+
* Prefix used when the input has to be wrapped. Ignored when the input
|
|
21
|
+
* is already a {@link SerialError} so we never rewrite a well-formed
|
|
22
|
+
* message the caller has already chosen.
|
|
23
|
+
*/
|
|
24
|
+
messagePrefix?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Normalize an arbitrary thrown value into a {@link SerialError}.
|
|
28
|
+
*
|
|
29
|
+
* This helper is the single entry point used by every v2 session
|
|
30
|
+
* component (session factory, read pump, send queue) to coerce raw
|
|
31
|
+
* platform errors into the library's error type. Centralising the
|
|
32
|
+
* mapping here satisfies Issue #204's completion criterion that
|
|
33
|
+
* "error handling lives in one place" and removes the duplicated
|
|
34
|
+
* `toError` / `normalizeError` helpers previously scattered across
|
|
35
|
+
* session modules.
|
|
36
|
+
*
|
|
37
|
+
* Mapping rules applied, in order:
|
|
38
|
+
*
|
|
39
|
+
* 1. `SerialError` instances pass through unchanged so a caller that has
|
|
40
|
+
* already classified the failure (e.g. `PORT_NOT_OPEN` on a pre-open
|
|
41
|
+
* `send$`) is not rewrapped.
|
|
42
|
+
* 2. `DOMException('NotFoundError')` is mapped to
|
|
43
|
+
* {@link SerialErrorCode.OPERATION_CANCELLED}. Chromium raises this
|
|
44
|
+
* when the user dismisses the `requestPort` dialog; it is a normal
|
|
45
|
+
* control-flow event, not a hard failure.
|
|
46
|
+
* 3. Any other value is wrapped as a {@link SerialError} with
|
|
47
|
+
* {@link NormalizeSerialErrorOptions.fallbackCode}, preserving the
|
|
48
|
+
* original error as `originalError` for debugging.
|
|
49
|
+
*
|
|
50
|
+
* @internal
|
|
51
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}
|
|
52
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/204 | Issue #204}
|
|
53
|
+
*/
|
|
54
|
+
export declare function normalizeSerialError(error: unknown, options: NormalizeSerialErrorOptions): SerialError;
|
|
55
|
+
//# sourceMappingURL=normalize-serial-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize-serial-error.d.ts","sourceRoot":"","sources":["../../src/session/normalize-serial-error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAW9D;;;;GAIG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;;;;;;OAQG;IACH,YAAY,EAAE,eAAe,CAAC;IAC9B;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAUD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,2BAA2B,GACnC,WAAW,CAqBb"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { SerialError } from '../errors/serial-error';
|
|
2
|
+
/**
|
|
3
|
+
* Callback invoked for every decoded chunk the read pump produces.
|
|
4
|
+
*
|
|
5
|
+
* The text is decoded from the raw bytes using a shared `TextDecoder` with
|
|
6
|
+
* `{ stream: true }`, so multi-byte characters that straddle chunk
|
|
7
|
+
* boundaries are joined correctly before reaching the callback.
|
|
8
|
+
*
|
|
9
|
+
* @internal
|
|
10
|
+
*/
|
|
11
|
+
export type ReadPumpChunkHandler = (text: string) => void;
|
|
12
|
+
/**
|
|
13
|
+
* Callback invoked when the read pump cannot continue.
|
|
14
|
+
*
|
|
15
|
+
* The provided error is always a {@link SerialError}; raw platform errors
|
|
16
|
+
* are normalized by the pump before they reach the caller so consumers only
|
|
17
|
+
* ever observe the library's error type.
|
|
18
|
+
*
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
export type ReadPumpErrorHandler = (error: SerialError) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Options accepted by {@link createReadPump}.
|
|
24
|
+
*
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
export interface ReadPumpOptions {
|
|
28
|
+
onChunk: ReadPumpChunkHandler;
|
|
29
|
+
onError: ReadPumpErrorHandler;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Handle returned by {@link createReadPump}.
|
|
33
|
+
*
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
export interface ReadPump {
|
|
37
|
+
/**
|
|
38
|
+
* Start reading from the associated `SerialPort.readable` stream.
|
|
39
|
+
*
|
|
40
|
+
* Subsequent calls are ignored while the pump is already running.
|
|
41
|
+
*/
|
|
42
|
+
start(): void;
|
|
43
|
+
/**
|
|
44
|
+
* Stop the read loop and release the underlying reader lock.
|
|
45
|
+
*
|
|
46
|
+
* Safe to call multiple times or before `start()`.
|
|
47
|
+
*/
|
|
48
|
+
stop(): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* `true` while the internal loop is actively reading.
|
|
51
|
+
*/
|
|
52
|
+
readonly isRunning: boolean;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Create an internal read pump for a {@link SerialPort}.
|
|
56
|
+
*
|
|
57
|
+
* The pump is an implementation detail of the v2 `SerialSession` API: it
|
|
58
|
+
* owns a single `TextDecoder` (with `stream: true`), drives a
|
|
59
|
+
* `reader.read()` loop against `port.readable`, and forwards decoded text
|
|
60
|
+
* to the provided sink. It is **not** subscription-lazy - the `SerialSession`
|
|
61
|
+
* starts the pump as soon as `connect$` succeeds so that `receive$`
|
|
62
|
+
* subscribers never miss data because of subscription timing.
|
|
63
|
+
*
|
|
64
|
+
* Errors are normalized into {@link SerialError} with
|
|
65
|
+
* {@link SerialErrorCode.READ_FAILED} for read-side failures and
|
|
66
|
+
* {@link SerialErrorCode.CONNECTION_LOST} for missing readable streams, so
|
|
67
|
+
* the session can forward them to `errors$` without rewrapping.
|
|
68
|
+
*
|
|
69
|
+
* @internal
|
|
70
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}
|
|
71
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/202 | Issue #202}
|
|
72
|
+
*/
|
|
73
|
+
export declare function createReadPump(port: SerialPort, { onChunk, onError }: ReadPumpOptions): ReadPump;
|
|
74
|
+
//# sourceMappingURL=read-pump.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-pump.d.ts","sourceRoot":"","sources":["../../src/session/read-pump.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAIrD;;;;;;;;GAQG;AACH,MAAM,MAAM,oBAAoB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;AAE1D;;;;;;;;GAQG;AACH,MAAM,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,CAAC;AAEhE;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,oBAAoB,CAAC;IAC9B,OAAO,EAAE,oBAAoB,CAAC;CAC/B;AAED;;;;GAIG;AACH,MAAM,WAAW,QAAQ;IACvB;;;;OAIG;IACH,KAAK,IAAI,IAAI,CAAC;IACd;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,UAAU,EAChB,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,eAAe,GACpC,QAAQ,CA8FV"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
/**
|
|
3
|
+
* A single enqueued unit of work. Operations are awaited sequentially so
|
|
4
|
+
* that `send$` guarantees call order even when the caller fires multiple
|
|
5
|
+
* observables concurrently.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/
|
|
9
|
+
export type SendQueueOperation<T> = () => Promise<T>;
|
|
10
|
+
/**
|
|
11
|
+
* Internal helper returned by {@link createSendQueue}.
|
|
12
|
+
*
|
|
13
|
+
* The queue is intentionally not an RxJS operator because Issue #199 calls
|
|
14
|
+
* out explicitly that `send$` must not be re-implemented with `mergeMap`
|
|
15
|
+
* (or any other concurrency-altering operator). A chained `Promise<void>`
|
|
16
|
+
* is the simplest way to guarantee strict FIFO ordering while still
|
|
17
|
+
* surfacing per-operation completion back to the caller.
|
|
18
|
+
*
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
export interface SendQueue {
|
|
22
|
+
/**
|
|
23
|
+
* Schedule an operation to run after all previously enqueued operations
|
|
24
|
+
* have settled (resolved or rejected). The returned Observable completes
|
|
25
|
+
* with the operation's resolved value, or errors with its rejection.
|
|
26
|
+
*
|
|
27
|
+
* Subscribing is what actually schedules the work - the queue is driven
|
|
28
|
+
* by `defer`, so late/never-subscribed Observables never enqueue.
|
|
29
|
+
*/
|
|
30
|
+
enqueue<T>(operation: SendQueueOperation<T>): Observable<T>;
|
|
31
|
+
/**
|
|
32
|
+
* Reset the internal promise chain. Existing in-flight operations keep
|
|
33
|
+
* running because we do not cancel native promises, but no newly
|
|
34
|
+
* enqueued work will wait for them. Use this when the session is torn
|
|
35
|
+
* down so a fresh `connect$` starts with a clean chain.
|
|
36
|
+
*/
|
|
37
|
+
clear(): void;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Create an internal send queue that serialises `send$` writes.
|
|
41
|
+
*
|
|
42
|
+
* Ordering model:
|
|
43
|
+
*
|
|
44
|
+
* - Each `enqueue` call appends its operation to a single `Promise<void>`
|
|
45
|
+
* chain.
|
|
46
|
+
* - A failure in one operation does not poison the chain - the next
|
|
47
|
+
* operation still runs (the chain is advanced with a `.then(() => {},
|
|
48
|
+
* () => {})` safety tail).
|
|
49
|
+
* - Unsubscribing before the operation resolves suppresses `next` /
|
|
50
|
+
* `complete` / `error` for that subscriber; the underlying promise is
|
|
51
|
+
* still awaited so later operations continue to respect call order.
|
|
52
|
+
*
|
|
53
|
+
* @internal
|
|
54
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/199 | Issue #199}
|
|
55
|
+
* @see {@link https://github.com/gurezo/web-serial-rxjs/issues/203 | Issue #203}
|
|
56
|
+
*/
|
|
57
|
+
export declare function createSendQueue(): SendQueue;
|
|
58
|
+
//# sourceMappingURL=send-queue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"send-queue.d.ts","sourceRoot":"","sources":["../../src/session/send-queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAS,MAAM,MAAM,CAAC;AAEzC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,CAAC,CAAC,IAAI,MAAM,OAAO,CAAC,CAAC,CAAC,CAAC;AAErD;;;;;;;;;;GAUG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;;OAOG;IACH,OAAO,CAAC,CAAC,EAAE,SAAS,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;IAC5D;;;;;OAKG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,IAAI,SAAS,CAwC3C"}
|