@slastra/tsplib 0.0.0-stage → 0.2.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/FINDINGS.md +89 -0
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/flow.d.ts +47 -0
- package/dist/flow.d.ts.map +1 -0
- package/dist/flow.js +52 -0
- package/dist/flow.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/raster.d.ts +32 -0
- package/dist/raster.d.ts.map +1 -0
- package/dist/raster.js +34 -0
- package/dist/raster.js.map +1 -0
- package/dist/transport.d.ts +34 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +31 -0
- package/dist/transport.js.map +1 -0
- package/dist/tspl.d.ts +62 -0
- package/dist/tspl.d.ts.map +1 -0
- package/dist/tspl.js +87 -0
- package/dist/tspl.js.map +1 -0
- package/dist/web-bluetooth.d.ts +54 -0
- package/dist/web-bluetooth.d.ts.map +1 -0
- package/dist/web-bluetooth.js +121 -0
- package/dist/web-bluetooth.js.map +1 -0
- package/package.json +67 -5
- package/src/flow.ts +73 -0
- package/src/index.ts +30 -0
- package/src/raster.ts +49 -0
- package/src/transport.ts +57 -0
- package/src/tspl.ts +137 -0
- package/src/web-bluetooth.ts +171 -0
package/dist/tspl.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Dots per millimetre at 203 dpi, the resolution of every printer verified here. */
|
|
2
|
+
export const DOTS_PER_MM = 8;
|
|
3
|
+
export const DEFAULT_DENSITY = 8;
|
|
4
|
+
export const DEFAULT_GAP_MM = 3;
|
|
5
|
+
const enc = new TextEncoder();
|
|
6
|
+
/** TSPL takes decimals but chokes on exponents; two places is finer than a dot. */
|
|
7
|
+
function mm(n) {
|
|
8
|
+
return `${Math.round(n * 100) / 100} mm`;
|
|
9
|
+
}
|
|
10
|
+
function int(name, n, min, max) {
|
|
11
|
+
if (!Number.isInteger(n) || n < min || n > max) {
|
|
12
|
+
throw new RangeError(`${name} must be an integer from ${min} to ${max}, got ${n}`);
|
|
13
|
+
}
|
|
14
|
+
return n;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Pack rows of dots into TSPL `BITMAP` data: MSB first, rows padded to whole
|
|
18
|
+
* bytes, and **1 is white**. That last part is the inverse of the row
|
|
19
|
+
* convention above and of most raster formats, so it is the bug to expect:
|
|
20
|
+
* get it backwards and the label comes out a solid black slab with the design
|
|
21
|
+
* cut out of it. Padding is white for the same reason.
|
|
22
|
+
*
|
|
23
|
+
* Every row must be the same width. A ragged row would not hang the printer
|
|
24
|
+
* the way it does under YPL, but it would shear everything below it sideways,
|
|
25
|
+
* so it is refused rather than sent.
|
|
26
|
+
*/
|
|
27
|
+
export function packBitmap(rows) {
|
|
28
|
+
const width = rows[0]?.length ?? 0;
|
|
29
|
+
const widthBytes = Math.ceil(width / 8);
|
|
30
|
+
const data = new Uint8Array(widthBytes * rows.length).fill(0xff);
|
|
31
|
+
rows.forEach((row, y) => {
|
|
32
|
+
if (row.length !== width) {
|
|
33
|
+
throw new RangeError(`row ${y} is ${row.length} dots wide, expected ${width}`);
|
|
34
|
+
}
|
|
35
|
+
const base = y * widthBytes;
|
|
36
|
+
for (let x = 0; x < width; x++) {
|
|
37
|
+
if (row[x])
|
|
38
|
+
data[base + (x >> 3)] &= ~(0x80 >> (x & 7));
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
return { widthBytes, data };
|
|
42
|
+
}
|
|
43
|
+
function concat(parts) {
|
|
44
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
45
|
+
let at = 0;
|
|
46
|
+
for (const p of parts) {
|
|
47
|
+
out.set(p, at);
|
|
48
|
+
at += p.length;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* One complete TSPL job for a single raster label: page setup, the bitmap,
|
|
54
|
+
* and the print command. The whole thing is self-contained, so a batch is
|
|
55
|
+
* just these laid end to end and a dropped job never leaves state behind for
|
|
56
|
+
* the next one.
|
|
57
|
+
*
|
|
58
|
+
* Only `BITMAP` draws. The printer's own fonts and barcode symbologies are
|
|
59
|
+
* deliberately unused: a host-side raster is the only way the preview can be
|
|
60
|
+
* trusted to match the paper.
|
|
61
|
+
*/
|
|
62
|
+
export function buildLabel(rows, options) {
|
|
63
|
+
const { widthMm, heightMm, media = 'gap', gapMm = DEFAULT_GAP_MM, density = DEFAULT_DENSITY, copies = 1, direction = 0, x = 0, y = 0 } = options;
|
|
64
|
+
if (!(widthMm > 0) || !(heightMm > 0)) {
|
|
65
|
+
throw new RangeError(`label size must be positive, got ${widthMm} x ${heightMm} mm`);
|
|
66
|
+
}
|
|
67
|
+
if (rows.length === 0 || rows[0].length === 0)
|
|
68
|
+
throw new RangeError('raster is empty');
|
|
69
|
+
int('density', density, 0, 15);
|
|
70
|
+
int('copies', copies, 1, 65535);
|
|
71
|
+
int('x', x, 0, 65535);
|
|
72
|
+
int('y', y, 0, 65535);
|
|
73
|
+
const gap = media === 'mark'
|
|
74
|
+
? `BLINE ${mm(gapMm)}, 0 mm`
|
|
75
|
+
: `GAP ${media === 'continuous' ? '0 mm' : mm(gapMm)}, 0 mm`;
|
|
76
|
+
const { widthBytes, data } = packBitmap(rows);
|
|
77
|
+
const head = [
|
|
78
|
+
`SIZE ${mm(widthMm)}, ${mm(heightMm)}`,
|
|
79
|
+
gap,
|
|
80
|
+
`DIRECTION ${direction}`,
|
|
81
|
+
`DENSITY ${density}`,
|
|
82
|
+
'CLS',
|
|
83
|
+
`BITMAP ${x},${y},${widthBytes},${rows.length},0,`
|
|
84
|
+
].join('\r\n');
|
|
85
|
+
return concat([enc.encode(head), data, enc.encode(`\r\nPRINT 1,${copies}\r\n`)]);
|
|
86
|
+
}
|
|
87
|
+
//# sourceMappingURL=tspl.js.map
|
package/dist/tspl.js.map
AD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AM,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,eAAe,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC;AAClF,CAAC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
/**
|
|
19
|
+
* Whether to meter writes by the credits on the flow channel. The Y43BT
|
|
20
|
+
* returns one credit per write; the Core Innovations CTP800BD grants ten
|
|
21
|
+
* on subscribing and never returns another, so metering it stalls on the
|
|
22
|
+
* eleventh write. With `false` the writes go out back to back, which that
|
|
23
|
+
* printer takes without loss, but a jammed or empty printer then no longer
|
|
24
|
+
* fails the send: there is no fault signal left.
|
|
25
|
+
*/
|
|
26
|
+
credits?: boolean;
|
|
27
|
+
/** Fires if the printer drops the GATT link. */
|
|
28
|
+
onDisconnect?: () => void;
|
|
29
|
+
}
|
|
30
|
+
/** A connected printer. Extends {@link Link}, so it drives `printJob` directly. */
|
|
31
|
+
export interface BluetoothLink extends Link {
|
|
32
|
+
readonly deviceName: string;
|
|
33
|
+
/** The write size currently in use, in bytes. */
|
|
34
|
+
readonly chunkSize: number;
|
|
35
|
+
disconnect(): void;
|
|
36
|
+
}
|
|
37
|
+
/** Whether this browser exposes Web Bluetooth at all (Chromium only). */
|
|
38
|
+
export declare function hasBluetooth(): boolean;
|
|
39
|
+
/** Web Bluetooth is unavailable on insecure origins, localhost excepted. */
|
|
40
|
+
export declare function isSecureContext(): boolean;
|
|
41
|
+
/** Both conditions the browser must meet. */
|
|
42
|
+
export declare function isSupported(): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Connect to a printer over Web Bluetooth.
|
|
45
|
+
*
|
|
46
|
+
* Discovery matches on device NAME, never on service UUID: a service-UUID
|
|
47
|
+
* filter makes Chrome push a `SetDiscoveryFilter` UUID list to BlueZ, which
|
|
48
|
+
* segfaults `bluetoothd` 5.87 on desktop Linux. `getDevices()` is tried first
|
|
49
|
+
* so an already-permitted printer reconnects with no chooser at all.
|
|
50
|
+
*
|
|
51
|
+
* Must be called from a user gesture, per the Web Bluetooth spec.
|
|
52
|
+
*/
|
|
53
|
+
export declare function connect(options?: ConnectOptions): Promise<BluetoothLink>;
|
|
54
|
+
//# 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;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,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,CA0ElF"}
|
|
@@ -0,0 +1,121 @@
|
|
|
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, credits = true, 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
|
+
if (credits)
|
|
67
|
+
await gate.take(creditTimeoutMs);
|
|
68
|
+
const size = chunk;
|
|
69
|
+
try {
|
|
70
|
+
await writeChar.writeValueWithoutResponse(bytes.slice(at, at + size));
|
|
71
|
+
}
|
|
72
|
+
catch (err) {
|
|
73
|
+
// Nothing went out, so the credit is still ours. An oversized write
|
|
74
|
+
// is the one failure worth retrying, smaller; anything else is real.
|
|
75
|
+
if (credits)
|
|
76
|
+
gate.grant(1);
|
|
77
|
+
if (size <= SAFE_CHUNK)
|
|
78
|
+
throw err;
|
|
79
|
+
chunk = SAFE_CHUNK;
|
|
80
|
+
shrunk = true;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
at += size;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
deviceName: device.name ?? namePrefix,
|
|
88
|
+
get chunkSize() {
|
|
89
|
+
return chunk;
|
|
90
|
+
},
|
|
91
|
+
send(bytes) {
|
|
92
|
+
const run = queue.then(() => sendNow(bytes));
|
|
93
|
+
queue = run.catch(() => { });
|
|
94
|
+
return run;
|
|
95
|
+
},
|
|
96
|
+
disconnect() {
|
|
97
|
+
device.gatt?.disconnect();
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
async function pickDevice(namePrefix) {
|
|
102
|
+
if (navigator.bluetooth.getDevices) {
|
|
103
|
+
try {
|
|
104
|
+
const known = await navigator.bluetooth.getDevices();
|
|
105
|
+
const matches = known.filter((d) => (d.name ?? '').startsWith(namePrefix));
|
|
106
|
+
// a dual-mode printer can leave both of its names permitted; the LE one
|
|
107
|
+
// is the one with the GATT services
|
|
108
|
+
const hit = matches.find((d) => d.name?.endsWith('_LE')) ?? matches[0];
|
|
109
|
+
if (hit)
|
|
110
|
+
return hit;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// permissions backend unavailable: fall through to a chooser
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return navigator.bluetooth.requestDevice({
|
|
117
|
+
filters: [{ namePrefix }],
|
|
118
|
+
optionalServices: [SERVICE]
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
//# sourceMappingURL=web-bluetooth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"web-bluetooth.js","sourceRoot":"","sources":["../src/web-bluetooth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGlD;;;;GAIG;AACH,MAAM,OAAO,GAAG,MAAM,CAAC;AACvB,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,SAAS,GAAG,MAAM,CAAC;AAEzB,8EAA8E;AAC9E,MAAM,UAAU,GAAG,EAAE,CAAC;AAuCtB,yEAAyE;AACzE,MAAM,UAAU,YAAY;IAC3B,OAAO,OAAO,SAAS,KAAK,WAAW,IAAI,WAAW,IAAI,SAAS,CAAC;AACrE,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,eAAe;IAC9B,OAAO,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,eAAe,CAAC;AAChE,CAAC;AAED,6CAA6C;AAC7C,MAAM,UAAU,WAAW;IAC1B,OAAO,YAAY,EAAE,IAAI,eAAe,EAAE,CAAC;AAC5C,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,UAA0B,EAAE;IACzD,MAAM,EACL,UAAU,GAAG,OAAO,EACpB,QAAQ,GAAG,GAAG,EACd,eAAe,GAAG,KAAK,EACvB,OAAO,GAAG,IAAI,EACd,YAAY,EACZ,GAAG,OAAO,CAAC;IAEZ,MAAM,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AO,GAAG,CAAC;QACZ,CAAC;QACD,UAAU;YACT,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,CAAC;QAC3B,CAAC;KACD,CAAC;AACH,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,UAAkB;IAC3C,IAAI,SAAS,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;QACpC,IAAI,CAAC;YACJ,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,SAAS,CAAC,UAAU,EAAE,CAAC;YACrD,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;YAC3E,wEAAwE;YACxE,oCAAoC;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,68 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@slastra/tsplib",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "TSPL raster label printing over BLE for printers that hide TSPL behind a credit-metered GATT channel (Labeer Y43BT, Core Innovations CTP800BD, and their white-label siblings). Job builder, 1-bit raster, and a Web Bluetooth transport.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"tspl",
|
|
7
|
+
"labeer",
|
|
8
|
+
"y43bt",
|
|
9
|
+
"ctp800bd",
|
|
10
|
+
"core-innovations",
|
|
11
|
+
"thermal-printer",
|
|
12
|
+
"label-printer",
|
|
13
|
+
"shipping-label",
|
|
14
|
+
"bluetooth-printer",
|
|
15
|
+
"web-bluetooth",
|
|
16
|
+
"raster"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://github.com/slastra/tsplib#readme",
|
|
19
|
+
"bugs": "https://github.com/slastra/tsplib/issues",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/slastra/tsplib.git"
|
|
23
|
+
},
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"author": "Shaun Lastra <shaun@lastra.us>",
|
|
26
|
+
"type": "module",
|
|
27
|
+
"sideEffects": false,
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"src",
|
|
31
|
+
"README.md",
|
|
32
|
+
"FINDINGS.md",
|
|
33
|
+
"LICENSE"
|
|
34
|
+
],
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"import": "./dist/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./web-bluetooth": {
|
|
41
|
+
"types": "./dist/web-bluetooth.d.ts",
|
|
42
|
+
"import": "./dist/web-bluetooth.js"
|
|
43
|
+
},
|
|
44
|
+
"./package.json": "./package.json"
|
|
45
|
+
},
|
|
46
|
+
"types": "./dist/index.d.ts",
|
|
47
|
+
"main": "./dist/index.js",
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "tsc -p tsconfig.build.json",
|
|
50
|
+
"test": "bun test test",
|
|
51
|
+
"check": "tsc --noEmit -p tsconfig.json",
|
|
52
|
+
"lint": "prettier --check .",
|
|
53
|
+
"format": "prettier --write .",
|
|
54
|
+
"prepublishOnly": "bun run check && bun run test && bun run build"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@types/bun": "^1.4.4",
|
|
58
|
+
"@types/web-bluetooth": "^0.0.22",
|
|
59
|
+
"prettier": "^3.9.10",
|
|
60
|
+
"typescript": "^6.0.3"
|
|
61
|
+
},
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": ">=18"
|
|
64
|
+
},
|
|
65
|
+
"publishConfig": {
|
|
66
|
+
"access": "public"
|
|
67
|
+
}
|
|
68
|
+
}
|
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
|
+
}
|
package/src/transport.ts
ADDED
|
@@ -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
|
+
}
|