### Example: listening for status bytes Source: https://github.com/at-point-of-sale/webusbreceiptprinter Adds a 'data' event listener to receive status bytes, connects to the device, and calls listen() to start reading. Logs the received bytes as an array. ```JavaScript receiptPrinter.addEventListener('data', dataView => { console.log('Status bytes received:', [...new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)]); }); await receiptPrinter.connect(); if (await receiptPrinter.listen()) { console.log('Listening for input on the status endpoint'); } ``` -------------------------------- ### Example: listening to connected and disconnected events Source: https://github.com/at-point-of-sale/webusbreceiptprinter Shows how to subscribe to 'connected' and 'disconnected' events. The connected callback receives a device object with manufacturerName, productName, serialNumber, language, and codepageMapping properties. ```javascript receiptPrinter.addEventListener('connected', device => { console.log(`Connected to ${device.manufacturerName} ${device.productName} (#${device.serialNumber})`); printerLanguage = device.language; printerCodepageMapping = device.codepageMapping; lastUsedDevice = device; }); receiptPrinter.addEventListener('disconnected', () => { console.log('Printer disconnected'); }); ``` -------------------------------- ### listen() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Starts a continuous read loop on the device's input (status) endpoint. Returns true if the device exposes an input endpoint and the read loop was started, otherwise undefined. ```APIDOC ## `listen()` ### Description Starts a continuous read loop on the device's input (status) endpoint. Returns `true` if the device exposes an input endpoint and the read loop was started, otherwise `undefined`. ### Method `listen()` ### Parameters No parameters. ### Returns `Promise` — `true` when the device exposes an input (status) bulk endpoint and the read loop was started; `undefined` when the device has no input endpoint, in which case nothing listens. ### Behavior - Starts a continuous read loop (`#read`, `src/main.js:534-551`) that issues 64-byte `transferIn` calls on the input endpoint forever. - Each received transfer that has data emits a `data` event carrying `result.data` (a `DataView` from the `USBInTransferResult`). - Read errors are caught and silently ignored (empty `catch(e)`), after which the loop continues. - The status bytes received are not interpreted in any way; this applies for example to the TSP100 series printers. ### Example — listening for status bytes ```js receiptPrinter.addEventListener('data', dataView => { console.log('Status bytes received:', [...new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)]); }); await receiptPrinter.connect(); if (await receiptPrinter.listen()) { console.log('Listening for input on the status endpoint'); } ``` ``` -------------------------------- ### listen() method implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Starts a continuous read loop on the input endpoint if present. Returns true when the device exposes an input bulk endpoint, otherwise undefined. Read errors are silently ignored and status bytes are not interpreted. ```JavaScript async listen() { if (this.#endpoints.input) { this.#read(); return true; } } ``` -------------------------------- ### CommandData example: Uint8Array initialization Source: https://github.com/at-point-of-sale/webusbreceiptprinter Example of a typed array accepted as the command argument for print(). It represents a byte sequence for the printer. ```javascript new Uint8Array([0x1b, 0x40]) ``` -------------------------------- ### CommandData example: Array of byte values Source: https://github.com/at-point-of-sale/webusbreceiptprinter Example of a plain array of byte values accepted as the command argument for print(). ```javascript [0x1b, 0x40, 0x41] ``` -------------------------------- ### Example: disconnect on button click Source: https://github.com/at-point-of-sale/webusbreceiptprinter Calls disconnect() when a button with id 'disconnectButton' is clicked. ```JavaScript document.querySelector('#disconnectButton').addEventListener('click', () => { receiptPrinter.disconnect(); }); ``` -------------------------------- ### Load and instantiate WebUSBReceiptPrinter via script tag Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Loads the UMD build and creates a new WebUSBReceiptPrinter instance. The constructor can take an optional options object for graphics-only printers like Star TSP100. ```html ``` -------------------------------- ### connect() method implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Prompts the user with the browser's device chooser, filtered to built-in device profiles. Must be called in direct response to a user gesture. On success, opens the device, resolves the profile, optionally instantiates the renderer, claims the interface, finds bulk endpoints, resets the device, and emits 'connected'. Only a RendererError propagates; other failures are logged and swallowed. ```javascript async connect() { try { let device = await navigator.usb.requestDevice({ filters: DeviceProfiles.map(i => i.filters).reduce((a, b) => a.concat(b)) }); if (device) { await this.#open(device); } } catch(error) { if (error instanceof RendererError) { throw error; } console.log('Could not connect! ' + error); } } ``` -------------------------------- ### constructor(options) Source: https://github.com/at-point-of-sale/webusbreceiptprinter Creates a new WebUSBReceiptPrinter instance. Accepts optional options for configuring the renderer and renderer options. Registers a navigator.usb disconnect listener that emits a 'disconnected' event when the currently open device is unplugged. ```APIDOC ## constructor(options) ### Description Creates a new WebUSBReceiptPrinter instance. Accepts optional options for configuring the renderer and renderer options. Registers a navigator.usb disconnect listener that emits a 'disconnected' event when the currently open device is unplugged. ### Parameters #### Constructor Options - `options` (WebUSBReceiptPrinterOptions) - Optional - Constructor options, merged over the defaults below. - `renderer` (ReceiptPrinterRenderer class or function) - Optional - Default: `null` - ReceiptPrinterRenderer class, or a function (possibly async) that returns it. Only used for graphics-only printers (Star TSP100 series). - `rendererOptions` (object) - Optional - Default: `{}` - Extra options passed to the renderer constructor. ### Example — basic instantiation ```js import WebUSBReceiptPrinter from 'webusb-receipt-printer.esm.js'; const receiptPrinter = new WebUSBReceiptPrinter(); ``` ### Example — with a renderer for Star TSP100 series printers ```js import ReceiptPrinterRenderer from '@point-of-sale/receipt-printer-renderer'; const receiptPrinter = new WebUSBReceiptPrinter({ renderer: ReceiptPrinterRenderer, rendererOptions: { maxHeight: 1000 } }); /* Or load the renderer lazily, only when it turns out a graphics printer was picked: */ const receiptPrinter2 = new WebUSBReceiptPrinter({ renderer: () => import('@point-of-sale/receipt-printer-renderer').then(m => m.default) }); ``` ``` -------------------------------- ### connect() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Prompts the user to select a USB device and establishes a connection to the receipt printer. Must be called in response to a user gesture. On success, opens the device, resolves the profile, optionally instantiates the renderer, claims the interface, finds bulk endpoints, resets the device, and emits a 'connected' event. ```APIDOC ## connect() ### Description Prompts the user with the browser's device chooser to select a USB receipt printer and establishes a connection. Must be called in direct response to a user gesture. On success, opens the device, resolves the profile, optionally instantiates the renderer, claims the interface, finds the bulk endpoints, resets the device, and emits a `connected` event with the device descriptor. ### Method connect() ### Parameters No parameters. ### Returns `Promise` - The connected device is not returned; the connection result is delivered through the `connected` event. ### Throws - `RendererError` - Only when a graphics-only printer was selected and the `renderer` option is neither the `ReceiptPrinterRenderer` class nor a function returning it. Other failures are logged and swallowed. ### Request Example ```js const receiptPrinter = new WebUSBReceiptPrinter(); document.querySelector('#connectButton').addEventListener('click', () => { receiptPrinter.connect(); }); ``` ### Error Handling Example ```js const receiptPrinter = new WebUSBReceiptPrinter({ renderer: class { } // not a renderer: no static languages array }); try { await receiptPrinter.connect(); } catch (error) { // Only the renderer mistake reaches this point. // 'The renderer option must be the ReceiptPrinterRenderer class, // or a function that returns it' console.error('Application error:', error.message); } ``` ``` -------------------------------- ### Import WebUSBReceiptPrinter as ES module Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Imports the ES module version and creates a new instance. Use this when using a module bundler or native ES modules. ```js import WebUSBReceiptPrinter from 'webusb-receipt-printer.esm.js'; const receiptPrinter = new WebUSBReceiptPrinter(); ``` -------------------------------- ### Constructor options with defaults Source: https://github.com/at-point-of-sale/webusbreceiptprinter The library is configured exclusively through the constructor options object. The constructor merges the provided options with defaults for `renderer` and `rendererOptions`. ```javascript constructor(options) { this.#options = Object.assign({ renderer: null, rendererOptions: {} }, options); } ``` -------------------------------- ### WebUSBReceiptPrinter constructor with options and disconnect listener Source: https://github.com/at-point-of-sale/webusbreceiptprinter Constructor merges provided options over defaults (renderer: null, rendererOptions: {}) and registers a navigator.usb disconnect listener that emits 'disconnected' when the current device is unplugged. No validation of the renderer option occurs here; it happens later in connect()/reconnect(). ```javascript constructor(options) { super(); this.#options = Object.assign({ renderer: null, rendererOptions: {} }, options); this.#emitter = new EventEmitter(); navigator.usb.addEventListener('disconnect', event => { if (this.#device == event.device) { this.#emitter.emit('disconnected'); } }); } ``` -------------------------------- ### Basic instantiation of WebUSBReceiptPrinter Source: https://github.com/at-point-of-sale/webusbreceiptprinter Creates a new WebUSBReceiptPrinter instance without any options. The renderer defaults to null, so it is only used for graphics-only printers like the Star TSP100 series. ```javascript import WebUSBReceiptPrinter from 'webusb-receipt-printer.esm.js'; const receiptPrinter = new WebUSBReceiptPrinter(); ``` -------------------------------- ### connect() catch block for user/device failures Source: https://github.com/at-point-of-sale/webusbreceiptprinter Handles errors from connect() when the user cancels the device chooser or the device cannot be opened/claimed/reset. Re-throws RendererError for bad renderer option, otherwise logs and resolves. ```javascript catch(error) { if (error instanceof RendererError) { throw error; } console.log('Could not connect! ' + error); } ``` -------------------------------- ### Create WebUSBReceiptPrinter with renderer for Star TSP100 Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Use this snippet to let the library render receipts for Star TSP100 series printers. Requires the optional @point-of-sale/receipt-printer-renderer package. The renderer is an optional peer dependency, so it is only included in the bundle when used. ```javascript import ReceiptPrinterRenderer from '@point-of-sale/receipt-printer-renderer'; const receiptPrinter = new WebUSBReceiptPrinter({ renderer: ReceiptPrinterRenderer }); ``` -------------------------------- ### Create WebUSBReceiptPrinter without renderer for manual raster commands Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Use this snippet when you want to send raster commands yourself. Without the renderer option, the connected event reports 'star-graphics' as the language and no columns, and everything passed to print() is sent unchanged. ```javascript const receiptPrinter = new WebUSBReceiptPrinter(); ``` -------------------------------- ### print() method implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Sends a command to the printer. No-op when the device is not connected or no output endpoint is found. For renderer-backed graphics printers, the command is rendered and wrapped; otherwise bytes are transferred unchanged. Transfer failures are logged and swallowed, so the promise always resolves. ```javascript async print(command) { if (this.#device && this.#endpoints.output) { try { if (this.#graphics) { command = this.#wrapper(this.#renderer.render(command), this.#graphics); } await this.#device.transferOut(this.#endpoints.output.endpointNumber, command); } catch(e) { console.log(e); } } } ``` -------------------------------- ### Connect to a receipt printer on button click Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Calls connect() as a result of a user action. This function must be called from a user gesture; it does not throw on failure but logs the problem. ```js function handleConnectButtonClick() { receiptPrinter.connect(); } ``` -------------------------------- ### Basic use of connect() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Connects the printer when a button is clicked. The connection result is delivered through the 'connected' event, not returned by the method. ```javascript const receiptPrinter = new WebUSBReceiptPrinter(); document.querySelector('#connectButton').addEventListener('click', () => { receiptPrinter.connect(); }); ``` -------------------------------- ### reconnect(previousDevice) implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Reconnects to a previously authorized printer by matching serialNumber first, then vendorId and productId. Runs the same #open sequence as connect() and emits 'connected' if found; otherwise resolves without effect. Unlike connect(), it has no try/catch, so errors propagate to the caller. ```javascript async reconnect(previousDevice) { let devices = await navigator.usb.getDevices(); let device = devices.find(device => device.serialNumber == previousDevice.serialNumber); if (!device) { device = devices.find(device => device.vendorId == previousDevice.vendorId && device.productId == previousDevice.productId); } if (device) { await this.#open(device); } } ``` -------------------------------- ### Basic use of reconnect() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Shows how to store the connected device and call reconnect() on page load to silently restore the connection without prompting the user. The 'connected' event provides the device object to save for the next page load. ```javascript const receiptPrinter = new WebUSBReceiptPrinter(); let lastUsedDevice = null; receiptPrinter.addEventListener('connected', device => { console.log(`Connected to ${device.manufacturerName} ${device.productName} (#${device.serialNumber})`); lastUsedDevice = device; // store for the next page load }); /* On page load: */ if (lastUsedDevice) { receiptPrinter.reconnect(lastUsedDevice); } ``` -------------------------------- ### Renderer instantiation with option precedence Source: https://github.com/at-point-of-sale/webusbreceiptprinter When a renderer is instantiated, `settings` (printer-owned settings) are merged over `rendererOptions`, so printer settings like `language`, `width`, `commands`, and `codepageMapping` always override application-provided options. ```javascript this.#renderer = new Renderer(Object.assign({}, this.#options.rendererOptions, settings)); ``` -------------------------------- ### Handle connected event for Star TSP100 Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Use this snippet to set up the encoder with the language, codepage mapping, and columns reported by the connected event. For these printers, language is 'star-prnt' and codepage mapping is 'star', with 48 columns for 80 mm paper. ```javascript receiptPrinter.addEventListener('connected', device => { let encoder = new ReceiptPrinterEncoder({ language: device.language, codepageMapping: device.codepageMapping, columns: device.columns }); }); ``` -------------------------------- ### Unknown wrapper Error throw Source: https://github.com/at-point-of-sale/webusbreceiptprinter Throws a plain `Error` when a graphics profile references a `wrapper` name that is not in the internal `Wrappers` map. This is a defensive error for hypothetical future profiles; with shipped profiles it cannot occur. ```javascript if (!this.#wrapper) { throw new Error('The profile of this printer asks for the wrapper ' + graphics.wrapper + ', which does not exist'); } ``` -------------------------------- ### Print receipt with ReceiptPrinterEncoder Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Use this snippet to encode and print a receipt. It initializes the encoder with language and codepage mapping, builds the receipt content (text, newline, QR code), and sends it to the printer via the print() function. The data must be properly encoded for the printer. ```JavaScript /* Encode the receipt */ let encoder = new ReceiptPrinterEncoder({ language: printerLanguage, codepageMapping: printerCodepageMapping }); let data = encoder .initialize() .text('The quick brown fox jumps over the lazy dog') .newline() .qrcode('https://nielsleenheer.com') .encode(); /* Print the receipt */ receiptPrinter.print(data); ``` -------------------------------- ### Error handling for reconnect() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Wraps reconnect() in try/catch to handle errors that propagate from navigator.usb.getDevices() or #open, including RendererError for a bad renderer option. ```javascript try { await receiptPrinter.reconnect(lastUsedDevice); } catch (error) { console.error('Reconnect failed', error); } ``` -------------------------------- ### Catching RendererError in consumer code Source: https://github.com/at-point-of-sale/webusbreceiptprinter Shows how to catch the `RendererError` from `connect()` by checking the error message. Since `RendererError` is not exported, `instanceof` cannot be used; the message string is the only reliable discriminator. ```javascript import WebUSBReceiptPrinter from 'webusb-receipt-printer.esm.js'; const receiptPrinter = new WebUSBReceiptPrinter({ renderer: class { } // not a renderer — has no static languages array }); try { await receiptPrinter.connect(); } catch (error) { if (error instanceof Error && error.message === 'The renderer option must be the ReceiptPrinterRenderer class, or a function that returns it') { console.error('Application misconfiguration:', error.message); } else { throw error; // any other error from connect() is already the renderer mistake } } ``` -------------------------------- ### Lazy-load renderer for Star TSP100 Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Use this snippet to load the renderer asynchronously only when a graphics printer is connected. The function may be asynchronous, allowing dynamic import of the package. ```javascript const receiptPrinter = new WebUSBReceiptPrinter({ renderer: () => import('@point-of-sale/receipt-printer-renderer').then(m => m.default) }); ``` -------------------------------- ### Wrappers object with star-raster encoder Source: https://github.com/at-point-of-sale/webusbreceiptprinter Maps renderer output to printer wire format. Currently only 'star-raster' is defined, using StarGraphicsPrinterEncoder from @point-of-sale/star-graphics-printer-encoder. ```JavaScript const Wrappers = { 'star-raster': (items, options) => new StarGraphicsPrinterEncoder({ tearBar: options.tearBar, quality: options.quality, pageLength: options.pageLength }).encode(items) }; ``` -------------------------------- ### WebUSBReceiptPrinterOptions constructor defaults Source: https://github.com/at-point-of-sale/webusbreceiptprinter Defines the default options object for the WebUSBReceiptPrinter constructor. The renderer is null by default and rendererOptions is an empty object. ```javascript this.#options = Object.assign({ renderer: null, rendererOptions: {} }, options); ``` -------------------------------- ### Listen for the connected event Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Adds an event listener for the 'connected' event. The callback receives a device object with properties like manufacturerName, productName, serialNumber, language, codepageMapping, and columns. ```js receiptPrinter.addEventListener('connected', device => { console.log(`Connected to ${device.manufacturerName} ${device.productName} (#${device.serialNumber})`); printerLanguage = device.language; printerCodepageMapping = device.codepageMapping; /* Store device for reconnecting */ lastUsedDevice = device; }); ``` -------------------------------- ### print(command) Source: https://github.com/at-point-of-sale/webusbreceiptprinter Sends a receipt command to the connected WebUSB receipt printer. The command is an array, typed array, DataView, ArrayBuffer, or other BufferSource of raw bytes. For renderer-backed graphics printers, the bytes are rendered to images and wrapped into the printer's wire format before transfer. ```APIDOC ## print(command) ### Description Sends a receipt command to the connected WebUSB receipt printer. The command is an array, typed array, DataView, ArrayBuffer, or other BufferSource of raw bytes. For renderer-backed graphics printers, the bytes are rendered to images and wrapped into the printer's wire format before transfer. ### Method print ### Parameters #### Path Parameters - `command` (CommandData) - Required - The receipt encoded for the printer's language (e.g. produced by `ReceiptPrinterEncoder`), or, for a renderer-backed graphics printer, the receipt in the renderer's reported language. ### Response #### Success Response Returns `Promise`. ### Behavior - No-op when the device is not connected or no output endpoint was found. - For renderer-backed graphics printers: the bytes are first rendered to images via `this.#renderer.render(command)`, then wrapped into the printer's wire format (Star Graphic raster) via `this.#wrapper` — the wrapper is `Wrappers['star-raster']` from `src/main.js:11-21`, which delegates to `@point-of-sale/star-graphics-printer-encoder`. - For ordinary printers and for graphics printers without a renderer, the bytes are transferred to the output endpoint unchanged. - Transfer failures are logged with `console.log(e)` and swallowed — the caller's promise always resolves. ### Request Example ```js import ReceiptPrinterEncoder from '@point-of-sale/receipt-printer-encoder'; let encoder = new ReceiptPrinterEncoder({ language: printerLanguage, codepageMapping: printerCodepageMapping }); let data = encoder .initialize() .text('The quick brown fox jumps over the lazy dog') .newline() .qrcode('https://nielsleenheer.com') .encode(); await receiptPrinter.print(data); ``` ### Request Example ```js /* A TSP100-series printer without a renderer speaks 'star-graphics': every byte is sent to the printer unchanged. */ await receiptPrinter.print(new Uint8Array([0x1b, 0x2a, 0x72, 0x41])); /* Raw byte arrays are accepted too: */ await receiptPrinter.print([0x1b, 0x40]); ``` ``` -------------------------------- ### Reconnect to a previously used printer Source: https://github.com/at-point-of-sale/webusbreceiptprinter/blob/main/README.md Calls reconnect() with an object containing serial number, vendor id, and product id. Does nothing if no matching previously connected printer is found. ```js receiptPrinter.reconnect(lastUsedDevice); ``` -------------------------------- ### Error handling for misconfigured renderer Source: https://github.com/at-point-of-sale/webusbreceiptprinter Catches the only error that propagates from connect(): a RendererError thrown when a graphics-only printer is selected and the renderer option is not the ReceiptPrinterRenderer class or a function returning it. Other failures are logged and swallowed. ```javascript const receiptPrinter = new WebUSBReceiptPrinter({ renderer: class { } // not a renderer: no static languages array }); try { await receiptPrinter.connect(); } catch (error) { // Only the renderer mistake reaches this point. // 'The renderer option must be the ReceiptPrinterRenderer class, // or a function that returns it' console.error('Application error:', error.message); } ``` -------------------------------- ### #read() empty catch block for input transfer failures Source: https://github.com/at-point-of-sale/webusbreceiptprinter Silently ignores errors from the input-endpoint read loop (device removed, transfer aborted). The empty catch discards the error and the loop continues. ```javascript } catch(e) { } ``` -------------------------------- ### EventEmitter class skeleton Source: https://github.com/at-point-of-sale/webusbreceiptprinter Internal event emitter with synchronous registration and asynchronous dispatch via setTimeout(..., 0). The constructor's device parameter is unused. Supports multiple callbacks per event but no removal method. ```JavaScript class EventEmitter { constructor(device) { ... } // note: the device parameter is unused on(e, f) { ... } // register callback emit(e, ...args) { ... } // dispatch via setTimeout(..., 0) } ``` -------------------------------- ### Basic use with ReceiptPrinterEncoder Source: https://github.com/at-point-of-sale/webusbreceiptprinter Encodes a receipt with text and a QR code, then sends it to the printer. Requires a printer language and codepage mapping for the encoder. ```javascript import ReceiptPrinterEncoder from '@point-of-sale/receipt-printer-encoder'; let encoder = new ReceiptPrinterEncoder({ language: printerLanguage, codepageMapping: printerCodepageMapping }); let data = encoder .initialize() .text('The quick brown fox jumps over the lazy dog') .newline() .qrcode('https://nielsleenheer.com') .encode(); await receiptPrinter.print(data); ``` -------------------------------- ### Instantiation with renderer for Star TSP100 series printers Source: https://github.com/at-point-of-sale/webusbreceiptprinter Shows two ways to pass a renderer: directly with the ReceiptPrinterRenderer class and rendererOptions, or lazily via a dynamic import() that resolves to the class. The renderer is only validated when a graphics printer is detected; otherwise an invalid renderer never throws. ```javascript import ReceiptPrinterRenderer from '@point-of-sale/receipt-printer-renderer'; const receiptPrinter = new WebUSBReceiptPrinter({ renderer: ReceiptPrinterRenderer, rendererOptions: { maxHeight: 1000 } }); /* Or load the renderer lazily, only when it turns out a graphics printer was picked: */ const receiptPrinter2 = new WebUSBReceiptPrinter({ renderer: () => import('@point-of-sale/receipt-printer-renderer').then(m => m.default) }); ``` -------------------------------- ### print() catch block for transfer failures Source: https://github.com/at-point-of-sale/webusbreceiptprinter Logs errors from print() when the device is gone, endpoint is gone, rendering fails, or transferOut rejects. print() still resolves; consumers must detect disconnected state via the 'disconnected' event. ```javascript catch(e) { console.log(e); } ``` -------------------------------- ### CodepageMappings mapping Source: https://github.com/at-point-of-sale/webusbreceiptprinter Maps renderer language to codepage mapping name for the encoder. Belongs to the renderer language, not the printer, so switching renderer only changes one import. ```JavaScript const CodepageMappings = { 'esc-pos': 'epson', 'star-prnt': 'star', 'star-line': 'star' }; ``` -------------------------------- ### Build connected event payload in #open() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Constructs the DeviceDescriptor object emitted with the 'connected' event. Sets type to 'usb' and copies printer properties. Adds columns only when graphics support is available, using width divided by 12. ```javascript let connected = { type: 'usb', manufacturerName: this.#device.manufacturerName, productName: this.#device.productName, serialNumber: this.#device.serialNumber, vendorId: this.#device.vendorId, productId: this.#device.productId, language: language, codepageMapping: codepageMapping }; if (this.#graphics) { connected.columns = this.#graphics.width / 12; } ``` -------------------------------- ### reconnect(previousDevice) Source: https://github.com/at-point-of-sale/webusbreceiptprinter Reconnects to a previously authorized USB receipt printer without prompting the user. It looks up the device by serial number first, then by vendor and product ID, and opens the connection if found. ```APIDOC ## `reconnect(previousDevice)` ### Description Reconnects to a previously authorized USB receipt printer without prompting the user. It looks up the device by serial number first, then by vendor and product ID, and opens the connection if found. ### Method `reconnect(previousDevice)` ### Parameters #### Parameters - **previousDevice** (ReconnectDescriptor) - Required - Object describing a previously connected printer, as captured from the `connected` event ### Returns `Promise` - Resolves without effect if no matching previously-authorized device is found. ### Behavior - Looks up the device by `serialNumber` (exact match) first. - Falls back to a `vendorId` + `productId` match. - If found, runs the same `#open()` sequence as `connect()` and emits `connected`; otherwise it does nothing (no error). - Intended to be called on page load to silently restore a connection, since it never prompts the user. ### Throws/rejects Unlike `connect()`, there is no `try`/`catch` — a rejected `navigator.usb.getDevices()` or any error inside `#open` (including `RendererError` for a bad renderer option) propagates to the caller. ### Request Example ```js const receiptPrinter = new WebUSBReceiptPrinter(); let lastUsedDevice = null; receiptPrinter.addEventListener('connected', device => { console.log(`Connected to ${device.manufacturerName} ${device.productName} (#${device.serialNumber})`); lastUsedDevice = device; // store for the next page load }); /* On page load: */ if (lastUsedDevice) { receiptPrinter.reconnect(lastUsedDevice); } ``` ### Request Example ```js try { await receiptPrinter.reconnect(lastUsedDevice); } catch (error) { console.error('Reconnect failed', error); } ``` ``` -------------------------------- ### RendererSettings array Source: https://github.com/at-point-of-sale/webusbreceiptprinter Settings of a graphics profile section passed to the renderer, in addition to always-passed language, width, commands, and codepageMapping. Only passed when the profile defines them. ```JavaScript const RendererSettings = [ 'maxHeight', 'feedThreshold' ]; ``` -------------------------------- ### disconnect() method implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Closes the USB device, clears all internal state, and emits 'disconnected'. No-op when no device is connected. ```JavaScript async disconnect() { if (!this.#device) { return; } await this.#device.close(); this.#device = null; this.#profile = null; this.#graphics = null; this.#renderer = null; this.#wrapper = null; this.#emitter.emit('disconnected'); } ``` -------------------------------- ### addEventListener method implementation Source: https://github.com/at-point-of-sale/webusbreceiptprinter Registers a callback for printer events. The callback is invoked asynchronously with the event payload. No unsubscribe function is returned; there is no removeEventListener. ```javascript addEventListener(n, f) { this.#emitter.on(n, f); } ``` -------------------------------- ### addEventListener(n, f) Source: https://github.com/at-point-of-sale/webusbreceiptprinter Registers a callback for printer events such as 'connected', 'disconnected', or 'data'. The callback is invoked asynchronously with the event payload. ```APIDOC ## addEventListener(n, f) ### Description Registers a callback for printer events such as 'connected', 'disconnected', or 'data'. The callback is invoked asynchronously with the event payload. ### Method addEventListener ### Parameters - **n** (string) - Required - Event name: `'connected'`, `'disconnected'` or `'data'` - **f** (function) - Required - Callback invoked asynchronously with the event payload (see Events) ### Returns `undefined` (no unsubscribe function is returned; there is no `removeEventListener`). ### Request Example ```js receiptPrinter.addEventListener('connected', device => { console.log(`Connected to ${device.manufacturerName} ${device.productName} (#${device.serialNumber})`); printerLanguage = device.language; printerCodepageMapping = device.codepageMapping; lastUsedDevice = device; }); receiptPrinter.addEventListener('disconnected', () => { console.log('Printer disconnected'); }); ``` ``` -------------------------------- ### WebUSBReceiptPrinter class declaration Source: https://github.com/at-point-of-sale/webusbreceiptprinter Shows the class declaration with private fields for device, profile, graphics, renderer, wrapper, and endpoints. The class extends the internal ReceiptPrinterDriver base class and is the only public export. ```javascript class ReceiptPrinterDriver {} class WebUSBReceiptPrinter extends ReceiptPrinterDriver { #emitter; #options; #device = null; #profile = null; #graphics = null; #renderer = null; #wrapper = null; #endpoints = { input: null, output: null }; ``` -------------------------------- ### disconnect() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Closes the USB device, clears all internal state, and emits a 'disconnected' event. No-op when no device is connected. ```APIDOC ## `disconnect()` ### Description Closes the USB device, clears all internal state, and emits a `disconnected` event. No-op when no device is connected. ### Method `disconnect()` ### Parameters No parameters. ### Returns `Promise`. ### Behavior No-op when no device is connected; otherwise closes the USB device, clears all internal state, and emits `disconnected`. ### Example ```js document.querySelector('#disconnectButton').addEventListener('click', () => { receiptPrinter.disconnect(); }); ``` ``` -------------------------------- ### Passing bytes directly (Star Graphic raster mode, no renderer) Source: https://github.com/at-point-of-sale/webusbreceiptprinter Sends raw byte arrays directly to a TSP100-series printer without a renderer. Every byte is sent unchanged; both Uint8Array and plain arrays are accepted. ```javascript /* A TSP100-series printer without a renderer speaks 'star-graphics': every byte is sent to the printer unchanged. */ await receiptPrinter.print(new Uint8Array([0x1b, 0x2a, 0x72, 0x41])); /* Raw byte arrays are accepted too: */ await receiptPrinter.print([0x1b, 0x40]); ``` -------------------------------- ### CommandData Source: https://github.com/at-point-of-sale/webusbreceiptprinter The `command` argument of `print()`. It must be an array, or a typed array with bytes, properly encoded for the printer. It is passed straight to `navigator.usb`'s `transferOut(endpointNumber, data)`, so any `BufferSource` (ArrayBuffer, typed array, DataView) or array of byte values is accepted. ```APIDOC ## CommandData ### Description The `command` argument of `print()`. It must be an array, or a typed array with bytes, properly encoded for the printer. It is passed straight to `navigator.usb`'s `transferOut(endpointNumber, data)`, so any `BufferSource` (ArrayBuffer, typed array, DataView) or array of byte values is accepted. ### Accepted Shapes - `Uint8Array` (or other typed array) - Example: `new Uint8Array([0x1b, 0x40])` - `Array` (byte values) - Example: `[0x1b, 0x40, 0x41]` - `ArrayBuffer` / `DataView` - from `encoder.encode()` variants ### Accepted By `print(command)` ``` -------------------------------- ### RendererError class definition Source: https://github.com/at-point-of-sale/webusbreceiptprinter Defines the custom error class `RendererError` that extends the built-in `Error`. It is thrown when the `renderer` option is invalid, but only for graphics-only printers. ```javascript class RendererError extends Error {} ``` -------------------------------- ### ReconnectDescriptor device lookup by serialNumber or vendorId/productId Source: https://github.com/at-point-of-sale/webusbreceiptprinter Used in src/main.js:350-362 to find a previously granted device when reconnecting. It first matches by serialNumber exactly, then falls back to matching vendorId and productId together if no serial match is found. ```javascript let device = devices.find(device => device.serialNumber == previousDevice.serialNumber); if (!device) { device = devices.find(device => device.vendorId == previousDevice.vendorId && device.productId == previousDevice.productId); } ``` -------------------------------- ### RendererError message constant Source: https://github.com/at-point-of-sale/webusbreceiptprinter The exact error message used when the `renderer` option is not the `ReceiptPrinterRenderer` class or a function returning it. This message is the reliable discriminator for consumer code since `RendererError` is not exported. ```text The renderer option must be the ReceiptPrinterRenderer class, or a function that returns it ``` -------------------------------- ### ReconnectDescriptor Source: https://github.com/at-point-of-sale/webusbreceiptprinter The `previousDevice` argument of `reconnect()`. It must carry the serial number, vendor id and product id of the previously connected printer. The `DeviceDescriptor` captured from `connected` satisfies it. ```APIDOC ## ReconnectDescriptor ### Description The `previousDevice` argument of `reconnect()`. It must carry the serial number, vendor id and product id of the previously connected printer. The `DeviceDescriptor` captured from `connected` satisfies it. ### Fields - **serialNumber** (string) - Required - Matched exactly first against the serial numbers of previously granted devices. - **vendorId** (number) - Required - Used for the fallback match (in combination with `productId`) when no serial number matches. - **productId** (number) - Required - Used for the fallback match (in combination with `vendorId`) when no serial number matches. ### Accepted By `reconnect(previousDevice)` ``` -------------------------------- ### Renderer validation in resolve() Source: https://github.com/at-point-of-sale/webusbreceiptprinter Checks that a renderer is a function with a static `languages` array; otherwise throws an Error. Used in `#resolve()` at `src/main.js:479-505`. ```javascript if (typeof renderer == 'function' && !Array.isArray(renderer.languages)) { renderer = await renderer(); } if (typeof renderer != 'function' || !Array.isArray(renderer.languages)) { throw new Error(); } ```