@slastra/tsplib 0.0.0-stage → 0.1.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.
@@ -0,0 +1,45 @@
1
+ import type { Link } from './transport.js';
2
+ export interface ConnectOptions {
3
+ /**
4
+ * Device name prefix to match. The module advertises twice, `Y43BT-XXXX`
5
+ * over classic Bluetooth and `Y43BT-XXXX_LE` over BLE; pick the `_LE` one
6
+ * in the chooser, since that is the one with the GATT services.
7
+ */
8
+ namePrefix?: string;
9
+ /**
10
+ * Largest GATT write to attempt. The printer announces its own limit on
11
+ * the flow channel (244 on the Y43BT) and the smaller of the two wins. If
12
+ * the browser's link turns out not to have negotiated a big enough MTU, the
13
+ * first oversized write fails and the link drops to 20 bytes for good.
14
+ */
15
+ maxChunk?: number;
16
+ /** How long to wait for the printer to return a credit before giving up. */
17
+ creditTimeoutMs?: number;
18
+ /** Fires if the printer drops the GATT link. */
19
+ onDisconnect?: () => void;
20
+ }
21
+ /** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
22
+ export interface BluetoothLink extends Link {
23
+ readonly deviceName: string;
24
+ /** The write size currently in use, in bytes. */
25
+ readonly chunkSize: number;
26
+ disconnect(): void;
27
+ }
28
+ /** Whether this browser exposes Web Bluetooth at all (Chromium only). */
29
+ export declare function hasBluetooth(): boolean;
30
+ /** Web Bluetooth is unavailable on insecure origins, localhost excepted. */
31
+ export declare function isSecureContext(): boolean;
32
+ /** Both conditions the browser must meet. */
33
+ export declare function isSupported(): boolean;
34
+ /**
35
+ * Connect to a printer over Web Bluetooth.
36
+ *
37
+ * Discovery matches on device NAME, never on service UUID: a service-UUID
38
+ * filter makes Chrome push a `SetDiscoveryFilter` UUID list to BlueZ, which
39
+ * segfaults `bluetoothd` 5.87 on desktop Linux. `getDevices()` is tried first
40
+ * so an already-permitted printer reconnects with no chooser at all.
41
+ *
42
+ * Must be called from a user gesture, per the Web Bluetooth spec.
43
+ */
44
+ export declare function connect(options?: ConnectOptions): Promise<BluetoothLink>;
45
+ //# sourceMappingURL=web-bluetooth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-bluetooth.d.ts","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAc3C,MAAM,WAAW,cAAc;IAC9B;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gDAAgD;IAChD,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;CAC1B;AAED,mFAAmF;AACnF,MAAM,WAAW,aAAc,SAAQ,IAAI;IAC1C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,iDAAiD;IACjD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,UAAU,IAAI,IAAI,CAAC;CACnB;AAED,yEAAyE;AACzE,wBAAgB,YAAY,IAAI,OAAO,CAEtC;AAED,4EAA4E;AAC5E,wBAAgB,eAAe,IAAI,OAAO,CAEzC;AAED,6CAA6C;AAC7C,wBAAgB,WAAW,IAAI,OAAO,CAErC;AAED;;;;;;;;;GASG;AACH,wBAAsB,OAAO,CAAC,OAAO,GAAE,cAAmB,GAAG,OAAO,CAAC,aAAa,CAAC,CAoElF"}
@@ -0,0 +1,119 @@
1
+ import { CreditGate, parseFlow } from './flow.js';
2
+ /**
3
+ * The module advertises `0x18f0` (write `2af1`), the service most cheap BLE
4
+ * printers carry TSPL on. On the Y43BT that one accepts writes and does
5
+ * nothing with them. The printer is on `ff00`.
6
+ */
7
+ const SERVICE = 0xff00;
8
+ const WRITE_UUID = 0xff02;
9
+ const FLOW_UUID = 0xff03;
10
+ /** The 23-byte default ATT MTU, less the 3-byte write header. Always safe. */
11
+ const SAFE_CHUNK = 20;
12
+ /** Whether this browser exposes Web Bluetooth at all (Chromium only). */
13
+ export function hasBluetooth() {
14
+ return typeof navigator !== 'undefined' && 'bluetooth' in navigator;
15
+ }
16
+ /** Web Bluetooth is unavailable on insecure origins, localhost excepted. */
17
+ export function isSecureContext() {
18
+ return typeof window !== 'undefined' && window.isSecureContext;
19
+ }
20
+ /** Both conditions the browser must meet. */
21
+ export function isSupported() {
22
+ return hasBluetooth() && isSecureContext();
23
+ }
24
+ /**
25
+ * Connect to a printer over Web Bluetooth.
26
+ *
27
+ * Discovery matches on device NAME, never on service UUID: a service-UUID
28
+ * filter makes Chrome push a `SetDiscoveryFilter` UUID list to BlueZ, which
29
+ * segfaults `bluetoothd` 5.87 on desktop Linux. `getDevices()` is tried first
30
+ * so an already-permitted printer reconnects with no chooser at all.
31
+ *
32
+ * Must be called from a user gesture, per the Web Bluetooth spec.
33
+ */
34
+ export async function connect(options = {}) {
35
+ const { namePrefix = 'Y43BT', maxChunk = 240, creditTimeoutMs = 10000, onDisconnect } = options;
36
+ const device = await pickDevice(namePrefix);
37
+ if (!device.gatt)
38
+ throw new Error('device has no GATT server');
39
+ device.addEventListener('gattserverdisconnected', () => onDisconnect?.());
40
+ const service = await (await device.gatt.connect()).getPrimaryService(SERVICE);
41
+ const writeChar = await service.getCharacteristic(WRITE_UUID);
42
+ const flowChar = await service.getCharacteristic(FLOW_UUID);
43
+ const gate = new CreditGate();
44
+ let chunk = SAFE_CHUNK;
45
+ let shrunk = false;
46
+ // The listener goes on before notifications start: the opening credit
47
+ // grant arrives the moment the subscription does, and missing it would
48
+ // leave the link waiting for credits the printer thinks it already gave.
49
+ flowChar.addEventListener('characteristicvaluechanged', (e) => {
50
+ const value = e.target.value;
51
+ if (!value)
52
+ return;
53
+ const msg = parseFlow(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
54
+ if (msg.kind === 'credit')
55
+ gate.grant(msg.count);
56
+ else if (msg.kind === 'mtu' && !shrunk)
57
+ chunk = Math.max(SAFE_CHUNK, Math.min(maxChunk, msg.bytes));
58
+ });
59
+ await flowChar.startNotifications();
60
+ // One job at a time: two interleaved sends would splice two labels' bytes
61
+ // together, which TSPL cannot recover from.
62
+ let queue = Promise.resolve();
63
+ async function sendNow(bytes) {
64
+ let at = 0;
65
+ while (at < bytes.length) {
66
+ await gate.take(creditTimeoutMs);
67
+ const size = chunk;
68
+ try {
69
+ await writeChar.writeValueWithoutResponse(bytes.slice(at, at + size));
70
+ }
71
+ catch (err) {
72
+ // Nothing went out, so the credit is still ours. An oversized write
73
+ // is the one failure worth retrying, smaller; anything else is real.
74
+ gate.grant(1);
75
+ if (size <= SAFE_CHUNK)
76
+ throw err;
77
+ chunk = SAFE_CHUNK;
78
+ shrunk = true;
79
+ continue;
80
+ }
81
+ at += size;
82
+ }
83
+ }
84
+ return {
85
+ deviceName: device.name ?? namePrefix,
86
+ get chunkSize() {
87
+ return chunk;
88
+ },
89
+ send(bytes) {
90
+ const run = queue.then(() => sendNow(bytes));
91
+ queue = run.catch(() => { });
92
+ return run;
93
+ },
94
+ disconnect() {
95
+ device.gatt?.disconnect();
96
+ }
97
+ };
98
+ }
99
+ async function pickDevice(namePrefix) {
100
+ if (navigator.bluetooth.getDevices) {
101
+ try {
102
+ const known = await navigator.bluetooth.getDevices();
103
+ const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
104
+ // a dual-mode printer can leave both of its names permitted; the LE one
105
+ // is the one with the GATT services
106
+ const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
107
+ if (hit)
108
+ return hit;
109
+ }
110
+ catch {
111
+ // permissions backend unavailable: fall through to a chooser
112
+ }
113
+ }
114
+ return navigator.bluetooth.requestDevice({
115
+ filters: [{ namePrefix }],
116
+ optionalServices: [SERVICE]
117
+ });
118
+ }
119
+ //# sourceMappingURL=web-bluetooth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"web-bluetooth.js","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AAAA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;YACpC,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC;YACvE,IAAI,GAAG;gBAAE,OAAO,GAAG,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACR,6DAA6D;QAC9D,CAAC;IACF,CAAC;IACD,OAAO,SAAS,CAAC,SAAS,CAAC,aAAa,CAAC;QACxC,OAAO,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC;QACzB,gBAAgB,EAAE,CAAC,OAAO,CAAC;KAC3B,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
- "name": "@slastra/tsplib",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@slastra/tsplib",
3
+ "version": "0.1.0",
4
+ "description": "TSPL raster label printing over BLE for printers that hide TSPL behind a credit-metered GATT channel (Labeer Y43BT and its white-label siblings). Job builder, 1-bit raster, and a Web Bluetooth transport.",
5
+ "keywords": [
6
+ "tspl",
7
+ "labeer",
8
+ "y43bt",
9
+ "thermal-printer",
10
+ "label-printer",
11
+ "shipping-label",
12
+ "bluetooth-printer",
13
+ "web-bluetooth",
14
+ "raster"
15
+ ],
16
+ "homepage": "https://github.com/slastra/tsplib#readme",
17
+ "bugs": "https://github.com/slastra/tsplib/issues",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/slastra/tsplib.git"
21
+ },
22
+ "license": "MIT",
23
+ "author": "Shaun Lastra <shaun@lastra.us>",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "files": [
27
+ "dist",
28
+ "src",
29
+ "README.md",
30
+ "FINDINGS.md",
31
+ "LICENSE"
32
+ ],
33
+ "exports": {
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "import": "./dist/index.js"
37
+ },
38
+ "./web-bluetooth": {
39
+ "types": "./dist/web-bluetooth.d.ts",
40
+ "import": "./dist/web-bluetooth.js"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "types": "./dist/index.d.ts",
45
+ "main": "./dist/index.js",
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.build.json",
48
+ "test": "bun test test",
49
+ "check": "tsc --noEmit -p tsconfig.json",
50
+ "lint": "prettier --check .",
51
+ "format": "prettier --write .",
52
+ "prepublishOnly": "bun run check && bun run test && bun run build"
53
+ },
54
+ "devDependencies": {
55
+ "@types/bun": "^1.4.4",
56
+ "@types/web-bluetooth": "^0.0.22",
57
+ "prettier": "^3.9.10",
58
+ "typescript": "^6.0.3"
59
+ },
60
+ "engines": {
61
+ "node": ">=18"
62
+ },
63
+ "publishConfig": {
64
+ "access": "public"
65
+ }
66
+ }
package/src/flow.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The credit channel that meters writes into the printer.
3
+ *
4
+ * The Y43BT's BLE module exposes TSPL only on service `ff00`: bytes go in on
5
+ * `ff02`, and `ff03` notifies flow-control messages back. Two kinds have been
6
+ * seen, both on subscribing and throughout a job:
7
+ *
8
+ * 01 nn grant nn more writes (7 on subscribe, then 1 back per write)
9
+ * 02 lo hi the largest write the module takes, little-endian (f4 00 = 244)
10
+ *
11
+ * One credit buys one GATT write of any size up to that limit, NOT one byte:
12
+ * a 20-byte write and a 240-byte write each cost one and each earn one back.
13
+ * Spending credits only as they arrive is the whole of the backpressure, so
14
+ * there is no pacing timer to tune and no buffer depth to guess.
15
+ */
16
+ export type FlowMessage =
17
+ | { kind: 'credit'; count: number }
18
+ | { kind: 'mtu'; bytes: number }
19
+ | { kind: 'unknown'; raw: Uint8Array };
20
+
21
+ export function parseFlow(raw: Uint8Array): FlowMessage {
22
+ if (raw[0] === 0x01 && raw.length >= 2) return { kind: 'credit', count: raw[1] };
23
+ if (raw[0] === 0x02 && raw.length >= 3) return { kind: 'mtu', bytes: raw[1] | (raw[2] << 8) };
24
+ return { kind: 'unknown', raw };
25
+ }
26
+
27
+ /**
28
+ * Counts credits and parks writers until one is free. Writers are served in
29
+ * the order they asked, so a job's chunks cannot overtake each other.
30
+ */
31
+ export class CreditGate {
32
+ private credits = 0;
33
+ private waiters: (() => void)[] = [];
34
+
35
+ get available(): number {
36
+ return this.credits;
37
+ }
38
+
39
+ grant(count: number): void {
40
+ this.credits += count;
41
+ while (this.credits > 0 && this.waiters.length) {
42
+ this.credits--;
43
+ this.waiters.shift()!();
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Spend one credit, waiting up to `timeoutMs` for the printer to return
49
+ * one. No status query has been found that this printer answers, so a
50
+ * stalled credit is the only sign a job gets that something is wrong.
51
+ *
52
+ * There is deliberately no abort here. Stopping between two chunks of a
53
+ * label leaves the TSPL parser owed BITMAP bytes, and it will then read the
54
+ * next job's commands as image data. Cancel between labels instead.
55
+ */
56
+ take(timeoutMs: number): Promise<void> {
57
+ if (this.credits > 0 && this.waiters.length === 0) {
58
+ this.credits--;
59
+ return Promise.resolve();
60
+ }
61
+ return new Promise((resolve, reject) => {
62
+ const done = () => {
63
+ clearTimeout(timer);
64
+ resolve();
65
+ };
66
+ const timer = setTimeout(() => {
67
+ this.waiters = this.waiters.filter((w) => w !== done);
68
+ reject(new Error('printer stopped taking data (out of paper, lid open, or jammed?)'));
69
+ }, timeoutMs);
70
+ this.waiters.push(done);
71
+ });
72
+ }
73
+ }
package/src/index.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * tsplib — TSPL raster label printing, for printers that hide TSPL behind a
3
+ * credit-metered BLE channel.
4
+ *
5
+ * This entry point is pure: no DOM, no Node APIs, no dependencies. The Web
6
+ * Bluetooth transport lives behind `tsplib/web-bluetooth` so importing the job
7
+ * builder never drags browser types in.
8
+ */
9
+
10
+ export {
11
+ DOTS_PER_MM,
12
+ DEFAULT_DENSITY,
13
+ DEFAULT_GAP_MM,
14
+ packBitmap,
15
+ buildLabel,
16
+ type MediaType,
17
+ type LabelOptions
18
+ } from './tspl.js';
19
+
20
+ export {
21
+ THRESHOLD,
22
+ lumaOverWhite,
23
+ imageDataToRows,
24
+ type RasterRow,
25
+ type PixelSource
26
+ } from './raster.js';
27
+
28
+ export { parseFlow, CreditGate, type FlowMessage } from './flow.js';
29
+
30
+ export { printJob, type Link, type PrintJobOptions } from './transport.js';
package/src/raster.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * One row of the label, one entry per dot: 1 where the head fires, 0 where the
3
+ * stock stays bare. The same shape yplib and nblib use, so one renderer can
4
+ * feed all three.
5
+ */
6
+ export type RasterRow = Uint8Array;
7
+
8
+ /**
9
+ * 1-bit cutoff. A pixel at or above this luma leaves the stock bare, below it
10
+ * the head fires.
11
+ */
12
+ export const THRESHOLD = 128;
13
+
14
+ /** The subset of ImageData this module needs, so Node callers need no DOM. */
15
+ export interface PixelSource {
16
+ data: Uint8ClampedArray;
17
+ width: number;
18
+ height: number;
19
+ }
20
+
21
+ /**
22
+ * BT.601 luma composited over white paper. Alpha is composited against white
23
+ * because unburned stock is what shows through, so a half-transparent grey is
24
+ * lighter on paper than it looks on a dark screen.
25
+ *
26
+ * @param data RGBA bytes
27
+ * @param i byte offset of the pixel (4 bytes per pixel)
28
+ */
29
+ export function lumaOverWhite(data: Uint8ClampedArray, i: number): number {
30
+ const a = data[i + 3] / 255;
31
+ return (0.299 * data[i] + 0.587 * data[i + 1] + 0.114 * data[i + 2]) * a + 255 * (1 - a);
32
+ }
33
+
34
+ /**
35
+ * Reduce RGBA pixels to rows of dots. Pure over plain arrays: pass an ImageData
36
+ * in the browser, or any `{data, width, height}` from sharp or node-canvas.
37
+ */
38
+ export function imageDataToRows(src: PixelSource, threshold = THRESHOLD): RasterRow[] {
39
+ const { data, width, height } = src;
40
+ const rows: RasterRow[] = [];
41
+ for (let y = 0; y < height; y++) {
42
+ const row = new Uint8Array(width);
43
+ for (let x = 0; x < width; x++) {
44
+ row[x] = lumaOverWhite(data, (y * width + x) * 4) < threshold ? 1 : 0;
45
+ }
46
+ rows.push(row);
47
+ }
48
+ return rows;
49
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The minimum a transport must provide: push bytes at the printer, resolving
3
+ * once they have all been accepted. Web Bluetooth is the one shipped here, but
4
+ * TSPL itself is transport-agnostic, so a USB `/dev/usb/lpN` writer or a
5
+ * classic SPP socket drives `printJob` just as well.
6
+ *
7
+ * There is no status read. The Y43BT answered none of TSPL's (`~!T`, `ESC !?`)
8
+ * or ESC/POS's status queries on any of its channels, so the link's own flow
9
+ * control is the only fault signal there is.
10
+ */
11
+ export interface Link {
12
+ send(bytes: Uint8Array): Promise<void>;
13
+ }
14
+
15
+ export interface PrintJobOptions {
16
+ /** Called after each label has been handed to the printer. */
17
+ onProgress?: (done: number, total: number) => void;
18
+ /**
19
+ * Abort between labels. A job stops cleanly; it never tears a label in
20
+ * half, because a half-sent BITMAP leaves the printer reading the next
21
+ * job's commands as image data.
22
+ */
23
+ signal?: AbortSignal;
24
+ }
25
+
26
+ /**
27
+ * Run a print job. Each entry builds one label's TSPL job lazily, so a
28
+ * thousand-row batch does not rasterize a thousand labels up front, and label
29
+ * i+1 is built while label i is on the wire.
30
+ *
31
+ * Returns the number of labels sent, which is less than `builds.length` if the
32
+ * signal aborted. "Sent" is as far as anyone can know: the printer reports
33
+ * nothing back once a label has gone in.
34
+ */
35
+ export async function printJob(
36
+ link: Link,
37
+ builds: (() => Promise<Uint8Array>)[],
38
+ { onProgress, signal }: PrintJobOptions = {}
39
+ ): Promise<number> {
40
+ let done = 0;
41
+ let next: Promise<Uint8Array> | undefined = builds[0]?.();
42
+ try {
43
+ for (let i = 0; i < builds.length; i++) {
44
+ if (signal?.aborted) break;
45
+ const job = await next!;
46
+ next = builds[i + 1]?.();
47
+ await link.send(job);
48
+ done = i + 1;
49
+ onProgress?.(done, builds.length);
50
+ }
51
+ } finally {
52
+ // a build already started for a label we are not printing must not
53
+ // surface as an unhandled rejection after the caller has moved on
54
+ next?.catch(() => {});
55
+ }
56
+ return done;
57
+ }
package/src/tspl.ts ADDED
@@ -0,0 +1,137 @@
1
+ import type { RasterRow } from './raster.js';
2
+
3
+ /** Dots per millimetre at 203 dpi, the resolution of every printer verified here. */
4
+ export const DOTS_PER_MM = 8;
5
+
6
+ /**
7
+ * How the printer finds the start of each label.
8
+ *
9
+ * - `gap`: die-cut labels on a liner, found by the see-through gap between them.
10
+ * - `mark`: continuous stock with a black mark printed on the back.
11
+ * - `continuous`: no marks at all; the label is exactly as long as `heightMm`.
12
+ */
13
+ export type MediaType = 'gap' | 'mark' | 'continuous';
14
+
15
+ export interface LabelOptions {
16
+ /** Label width across the head. TSPL clips anything drawn past it. */
17
+ widthMm: number;
18
+ /** Label length along the feed. */
19
+ heightMm: number;
20
+ media?: MediaType;
21
+ /** Gap or mark length. Ignored for continuous stock. */
22
+ gapMm?: number;
23
+ /** Burn darkness, 0–15. */
24
+ density?: number;
25
+ /** Copies of this label. They cost nothing extra on the wire. */
26
+ copies?: number;
27
+ /**
28
+ * TSPL `DIRECTION`: 0 prints the raster as drawn with its top leaving the
29
+ * printer first, 1 turns it half a turn. Not a quarter turn: rotating a
30
+ * design to fit the stock is the caller's job.
31
+ */
32
+ direction?: 0 | 1;
33
+ /** Where the raster's top-left corner lands on the label, in dots. */
34
+ x?: number;
35
+ y?: number;
36
+ }
37
+
38
+ export const DEFAULT_DENSITY = 8;
39
+ export const DEFAULT_GAP_MM = 3;
40
+
41
+ const enc = new TextEncoder();
42
+
43
+ /** TSPL takes decimals but chokes on exponents; two places is finer than a dot. */
44
+ function mm(n: number): string {
45
+ return `${Math.round(n * 100) / 100} mm`;
46
+ }
47
+
48
+ function int(name: string, n: number, min: number, max: number): number {
49
+ if (!Number.isInteger(n) || n < min || n > max) {
50
+ throw new RangeError(`${name} must be an integer from ${min} to ${max}, got ${n}`);
51
+ }
52
+ return n;
53
+ }
54
+
55
+ /**
56
+ * Pack rows of dots into TSPL `BITMAP` data: MSB first, rows padded to whole
57
+ * bytes, and **1 is white**. That last part is the inverse of the row
58
+ * convention above and of most raster formats, so it is the bug to expect:
59
+ * get it backwards and the label comes out a solid black slab with the design
60
+ * cut out of it. Padding is white for the same reason.
61
+ *
62
+ * Every row must be the same width. A ragged row would not hang the printer
63
+ * the way it does under YPL, but it would shear everything below it sideways,
64
+ * so it is refused rather than sent.
65
+ */
66
+ export function packBitmap(rows: RasterRow[]): { widthBytes: number; data: Uint8Array } {
67
+ const width = rows[0]?.length ?? 0;
68
+ const widthBytes = Math.ceil(width / 8);
69
+ const data = new Uint8Array(widthBytes * rows.length).fill(0xff);
70
+ rows.forEach((row, y) => {
71
+ if (row.length !== width) {
72
+ throw new RangeError(`row ${y} is ${row.length} dots wide, expected ${width}`);
73
+ }
74
+ const base = y * widthBytes;
75
+ for (let x = 0; x < width; x++) {
76
+ if (row[x]) data[base + (x >> 3)] &= ~(0x80 >> (x & 7));
77
+ }
78
+ });
79
+ return { widthBytes, data };
80
+ }
81
+
82
+ function concat(parts: Uint8Array[]): Uint8Array {
83
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
84
+ let at = 0;
85
+ for (const p of parts) {
86
+ out.set(p, at);
87
+ at += p.length;
88
+ }
89
+ return out;
90
+ }
91
+
92
+ /**
93
+ * One complete TSPL job for a single raster label: page setup, the bitmap,
94
+ * and the print command. The whole thing is self-contained, so a batch is
95
+ * just these laid end to end and a dropped job never leaves state behind for
96
+ * the next one.
97
+ *
98
+ * Only `BITMAP` draws. The printer's own fonts and barcode symbologies are
99
+ * deliberately unused: a host-side raster is the only way the preview can be
100
+ * trusted to match the paper.
101
+ */
102
+ export function buildLabel(rows: RasterRow[], options: LabelOptions): Uint8Array {
103
+ const {
104
+ widthMm,
105
+ heightMm,
106
+ media = 'gap',
107
+ gapMm = DEFAULT_GAP_MM,
108
+ density = DEFAULT_DENSITY,
109
+ copies = 1,
110
+ direction = 0,
111
+ x = 0,
112
+ y = 0
113
+ } = options;
114
+ if (!(widthMm > 0) || !(heightMm > 0)) {
115
+ throw new RangeError(`label size must be positive, got ${widthMm} x ${heightMm} mm`);
116
+ }
117
+ if (rows.length === 0 || rows[0].length === 0) throw new RangeError('raster is empty');
118
+ int('density', density, 0, 15);
119
+ int('copies', copies, 1, 65535);
120
+ int('x', x, 0, 65535);
121
+ int('y', y, 0, 65535);
122
+
123
+ const gap =
124
+ media === 'mark'
125
+ ? `BLINE ${mm(gapMm)}, 0 mm`
126
+ : `GAP ${media === 'continuous' ? '0 mm' : mm(gapMm)}, 0 mm`;
127
+ const { widthBytes, data } = packBitmap(rows);
128
+ const head = [
129
+ `SIZE ${mm(widthMm)}, ${mm(heightMm)}`,
130
+ gap,
131
+ `DIRECTION ${direction}`,
132
+ `DENSITY ${density}`,
133
+ 'CLS',
134
+ `BITMAP ${x},${y},${widthBytes},${rows.length},0,`
135
+ ].join('\r\n');
136
+ return concat([enc.encode(head), data, enc.encode(`\r\nPRINT 1,${copies}\r\n`)]);
137
+ }