libniimai 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,1603 @@
1
+ // src/ble.ts
2
+ /** The standard NIIMBOT service, followed by serial-over-BLE services common on budget printers. */
3
+ var CANDIDATE_SERVICES = [
4
+ "e7810a71-73ae-499d-8c15-faa9aef0c3f2",
5
+ "0000e0ff-3c17-d293-8e48-14fe2e4da212",
6
+ "0000ae30-0000-1000-8000-00805f9b34fb",
7
+ "0000ff00-0000-1000-8000-00805f9b34fb",
8
+ "0000ffe0-0000-1000-8000-00805f9b34fb",
9
+ "0000fff0-0000-1000-8000-00805f9b34fb",
10
+ "000018f0-0000-1000-8000-00805f9b34fb",
11
+ "49535343-fe7d-4ae5-8fa9-9fafd205e455",
12
+ "6e400001-b5a3-f393-e0a9-e50e24dcca9e"
13
+ ];
14
+ /** Name prefixes of NIIMBOT printers; the chooser lists only these and known cat printers. */
15
+ var NAME_PREFIXES = [
16
+ "A",
17
+ "B",
18
+ "C",
19
+ "D",
20
+ "E",
21
+ "F",
22
+ "H",
23
+ "J",
24
+ "K",
25
+ "M",
26
+ "N",
27
+ "P",
28
+ "S",
29
+ "T",
30
+ "Z"
31
+ ];
32
+ /** Opens the browser's printer chooser. */
33
+ function requestPrinter(extraPrefixes = []) {
34
+ return navigator.bluetooth.requestDevice({
35
+ filters: [...[...NAME_PREFIXES, ...extraPrefixes].map((namePrefix) => ({ namePrefix })), { services: [CANDIDATE_SERVICES[0]] }],
36
+ optionalServices: CANDIDATE_SERVICES
37
+ });
38
+ }
39
+ /**
40
+ * Picks the characteristics to talk through. A single characteristic that both
41
+ * notifies and accepts writes wins (the NIIMBOT layout); otherwise a write and
42
+ * a notify characteristic from the same service are paired.
43
+ */
44
+ async function pickChannel(services) {
45
+ const all = [];
46
+ for (const service of services) all.push({
47
+ service: service.uuid,
48
+ chars: await service.getCharacteristics()
49
+ });
50
+ const canWrite = (c) => c.properties.writeWithoutResponse || c.properties.write;
51
+ const canNotify = (c) => c.properties.notify || !!c.properties.indicate;
52
+ for (const { chars } of all) {
53
+ const both = chars.find((c) => c.properties.writeWithoutResponse && c.properties.notify);
54
+ if (both) return {
55
+ write: both,
56
+ notify: both
57
+ };
58
+ }
59
+ for (const { chars } of all) {
60
+ const write = chars.find(canWrite);
61
+ const notify = chars.find(canNotify);
62
+ if (write && notify) return {
63
+ write,
64
+ notify
65
+ };
66
+ }
67
+ return null;
68
+ }
69
+ /** Turns Chrome's terse GATT errors into something a person can act on. */
70
+ function describeBleError(err, found = []) {
71
+ const msg = err instanceof Error ? err.message : String(err);
72
+ if (/no services found/i.test(msg) || found.length === 0 && /characteristic/i.test(msg)) return /* @__PURE__ */ new Error("This printer uses an unknown Bluetooth service. See Help → Printer not recognised.");
73
+ if (/characteristic/i.test(msg)) return /* @__PURE__ */ new Error(`No usable channel. Services: ${found.join(", ")}`);
74
+ return err instanceof Error ? err : new Error(msg);
75
+ }
76
+ /**
77
+ * A Web Bluetooth client that accepts more service layouts than niimbluelib's
78
+ * own, which only knows the standard NIIMBOT service. The protocol handling
79
+ * (packets, negotiation, heartbeat) is inherited unchanged.
80
+ */
81
+ function createBleClient(lib, chosen) {
82
+ class FlexibleBleClient extends lib.NiimbotAbstractClient {
83
+ server;
84
+ channel;
85
+ async connect() {
86
+ await this.disconnect();
87
+ const device = chosen ?? await requestPrinter();
88
+ if (!device.gatt) throw new Error("Device has no GATT server");
89
+ const onDisconnect = () => {
90
+ this.server = void 0;
91
+ this.channel = void 0;
92
+ this.emit("disconnect", new lib.DisconnectEvent());
93
+ device.removeEventListener("gattserverdisconnected", onDisconnect);
94
+ };
95
+ device.addEventListener("gattserverdisconnected", onDisconnect);
96
+ const server = await device.gatt.connect();
97
+ let found = [];
98
+ try {
99
+ const services = await server.getPrimaryServices();
100
+ found = services.map((s) => s.uuid);
101
+ console.info("[niimai] services", found);
102
+ const channel = await pickChannel(services);
103
+ if (!channel) throw new Error("Suitable characteristic not found");
104
+ console.info("[niimai] channel", channel.write.uuid, channel.notify.uuid);
105
+ channel.notify.addEventListener("characteristicvaluechanged", (e) => {
106
+ const value = e.target.value;
107
+ if (value) this.processRawPacket(value);
108
+ });
109
+ await channel.notify.startNotifications();
110
+ this.server = server;
111
+ this.channel = channel;
112
+ } catch (err) {
113
+ server.disconnect();
114
+ throw describeBleError(err, found);
115
+ }
116
+ await this.negotiateAndGetPrinterInfo(() => this.disconnect());
117
+ const result = {
118
+ deviceName: device.name,
119
+ result: this.printerInfo.connectResult ?? lib.ConnectResult.FirmwareErrors
120
+ };
121
+ this.emit("connect", new lib.ConnectEvent(result));
122
+ return result;
123
+ }
124
+ isConnected() {
125
+ return !!this.server && !!this.channel;
126
+ }
127
+ async disconnect() {
128
+ this.stopHeartbeat();
129
+ this.server?.disconnect();
130
+ this.server = void 0;
131
+ this.channel = void 0;
132
+ }
133
+ async sendRaw(data, force) {
134
+ const send = async () => {
135
+ const c = this.channel?.write;
136
+ if (!c) throw new Error("Channel is closed");
137
+ await lib.Utils.sleep(this.packetIntervalMs);
138
+ const buf = data.slice().buffer;
139
+ if (c.properties.writeWithoutResponse) await c.writeValueWithoutResponse(buf);
140
+ else await c.writeValueWithResponse(buf);
141
+ this.emit("rawpacketsent", new lib.RawPacketSentEvent(data));
142
+ };
143
+ if (force) await send();
144
+ else await this.mutex.runExclusive(send);
145
+ }
146
+ getType() {
147
+ return "bluetooth";
148
+ }
149
+ }
150
+ return new FlexibleBleClient();
151
+ }
152
+ // src/thermal.ts
153
+ /** Dots across the head: 48 mm at 203 dpi. */
154
+ var THERMAL_HEAD_DOTS = 384;
155
+ /** The print width in whole millimetres, the widest a design on continuous paper can be. */
156
+ var THERMAL_HEAD_MM = 48;
157
+ /** The known model a Bluetooth name belongs to, longest prefix first. */
158
+ function modelFor(models, name) {
159
+ if (!name) return null;
160
+ return [...models].sort((a, b) => b.prefix.length - a.prefix.length).find((m) => name.startsWith(m.prefix)) ?? null;
161
+ }
162
+ /** Sizes that suit 58 mm continuous paper: the full 48 mm print width at common lengths. */
163
+ var THERMAL_SIZES = [
164
+ 15,
165
+ 20,
166
+ 30,
167
+ 48,
168
+ 80
169
+ ].map((heightMm) => ({
170
+ widthMm: 48,
171
+ heightMm
172
+ }));
173
+ var THERMAL_DEFAULT_SIZE = {
174
+ widthMm: 48,
175
+ heightMm: 30
176
+ };
177
+ /**
178
+ * Packs a 1-bit page (RGBA, dark = black) into rows as wide as the head, centred across
179
+ * the head. Cat printers want the leftmost dot in the lowest bit, ESC/POS in
180
+ * the highest.
181
+ */
182
+ function packRows(data, width, height, order, head = 384) {
183
+ const offset = Math.max(0, Math.floor((head - width) / 2));
184
+ const rows = [];
185
+ for (let y = 0; y < height; y++) {
186
+ const row = new Uint8Array(head / 8);
187
+ for (let x = 0; x < width && x + offset < head; x++) if (data[(y * width + x) * 4] < 128) {
188
+ const dot = x + offset;
189
+ row[dot >> 3] |= order === "lsb" ? 1 << (dot & 7) : 128 >> (dot & 7);
190
+ }
191
+ rows.push(row);
192
+ }
193
+ return rows;
194
+ }
195
+ var sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
196
+ /**
197
+ * A thermal printer behind the same interface as a NIIMBOT client, so the
198
+ * printer service drives both. It reports itself through model metadata with
199
+ * kind "thermal"; it has no roll tags, battery or heartbeat to offer.
200
+ * Subclasses supply the row encoding and the bytes for a job.
201
+ */
202
+ var ThermalPrinterClient = class {
203
+ transport;
204
+ pace;
205
+ listeners = /* @__PURE__ */ new Map();
206
+ connected = false;
207
+ /** Set while the printer asks to wait (cat printers' flow control). */
208
+ paused = false;
209
+ /** Bytes per write. Starts large and halves if the link refuses it. */
210
+ chunk;
211
+ /** Dots across the head. */
212
+ headDots = 384;
213
+ /** "left": the label runs sideways through the head, as on NIIMBOT D-series printers. */
214
+ printDirection = "top";
215
+ /** Continuous-paper printers report "thermal"; label printers report nothing and get the roll UI. */
216
+ kind = "thermal";
217
+ /** Label sizes common for this printer, offered in place of NIIMBOT roll sizes. */
218
+ labelSizes = void 0;
219
+ /** Called after each page is sent; printers that confirm a job wait here. */
220
+ async afterPage() {}
221
+ constructor(transport, pace, firstChunk) {
222
+ this.transport = transport;
223
+ this.pace = pace;
224
+ this.chunk = firstChunk;
225
+ transport.onDisconnect(() => {
226
+ this.connected = false;
227
+ this.emit("disconnect", {});
228
+ });
229
+ }
230
+ async connect() {
231
+ this.connected = true;
232
+ return { deviceName: this.transport.name };
233
+ }
234
+ async disconnect() {
235
+ this.connected = false;
236
+ await this.transport.disconnect();
237
+ }
238
+ isConnected() {
239
+ return this.connected;
240
+ }
241
+ on(event, fn) {
242
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
243
+ this.listeners.get(event).add(fn);
244
+ }
245
+ off(event, fn) {
246
+ this.listeners.get(event)?.delete(fn);
247
+ }
248
+ emit(event, e) {
249
+ this.listeners.get(event)?.forEach((fn) => fn(e));
250
+ }
251
+ getPrinterInfo() {
252
+ return {};
253
+ }
254
+ getModelMetadata() {
255
+ return {
256
+ model: this.modelName,
257
+ ...this.kind ? { kind: this.kind } : {},
258
+ ...this.labelSizes ? { labelSizes: this.labelSizes } : {},
259
+ dpi: 203,
260
+ printheadPixels: this.headDots,
261
+ printDirection: this.printDirection,
262
+ densityMin: 1,
263
+ densityMax: this.densityLevels,
264
+ densityDefault: Math.ceil(this.densityLevels / 2)
265
+ };
266
+ }
267
+ getPrintTaskType() {
268
+ return "B1";
269
+ }
270
+ getRfidInfo() {
271
+ return {};
272
+ }
273
+ async fetchRfidInfo() {}
274
+ startHeartbeat() {}
275
+ stopHeartbeat() {}
276
+ /** Pages arrive as 1-bit canvases; the service hands them here instead of to niimbluelib's encoder. */
277
+ encodePage(canvas) {
278
+ const ctx = canvas.getContext("2d");
279
+ if (!ctx) throw new Error("Canvas is unavailable");
280
+ return this.encodeRows(ctx.getImageData(0, 0, canvas.width, canvas.height).data, canvas.width, canvas.height);
281
+ }
282
+ /** Sends bytes in chunks, waiting while the printer asks for a pause. `onSent` hears the share sent, 0–1. */
283
+ async send(bytes, onSent) {
284
+ for (let i = 0; i < bytes.length;) {
285
+ while (this.paused) await sleep$1(this.pace.pauseMs);
286
+ const part = bytes.subarray(i, i + this.chunk);
287
+ try {
288
+ await this.transport.write(part);
289
+ } catch (err) {
290
+ if (this.chunk <= 20) throw err;
291
+ this.chunk = Math.max(20, this.chunk >> 1);
292
+ continue;
293
+ }
294
+ i += part.length;
295
+ onSent?.(i / bytes.length);
296
+ await sleep$1(this.pace.chunkMs);
297
+ }
298
+ }
299
+ protocol = {
300
+ printEnd: async () => true,
301
+ newPrintTask: (_name, options) => {
302
+ const density = Number(options.density ?? 1);
303
+ const labelType = Number(options.labelType ?? 1);
304
+ let printed = 0;
305
+ return {
306
+ printInit: async () => {},
307
+ printPage: async (image, quantity = 1) => {
308
+ const total = () => Math.max(printed, Number(options.totalPages ?? printed));
309
+ let shown = -1;
310
+ await this.send(this.job(image, density, Math.max(1, quantity), labelType), (share) => {
311
+ const sending = Math.floor(share * 100);
312
+ if (sending === shown) return;
313
+ shown = sending;
314
+ this.emit("printprogress", {
315
+ page: printed,
316
+ pagesTotal: total(),
317
+ pagePrintProgress: 0,
318
+ pageFeedProgress: 0,
319
+ sending
320
+ });
321
+ });
322
+ await this.afterPage();
323
+ printed += Math.max(1, quantity);
324
+ this.emit("printprogress", {
325
+ page: printed,
326
+ pagesTotal: total(),
327
+ pagePrintProgress: 100,
328
+ pageFeedProgress: 100
329
+ });
330
+ },
331
+ waitForFinished: async () => {},
332
+ printEnd: async () => true
333
+ };
334
+ }
335
+ };
336
+ };
337
+ /** A Web Bluetooth link through one service: a write characteristic and, if present, a notify one. */
338
+ async function webTransport(device, server, ids) {
339
+ const service = await server.getPrimaryService(ids.service);
340
+ const tx = await service.getCharacteristic(ids.write);
341
+ const notify = [];
342
+ if (ids.notify) {
343
+ const rx = await service.getCharacteristic(ids.notify);
344
+ rx.addEventListener("characteristicvaluechanged", (e) => {
345
+ const v = e.target.value;
346
+ if (v) notify.forEach((fn) => fn(new Uint8Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength))));
347
+ });
348
+ await rx.startNotifications();
349
+ }
350
+ return {
351
+ name: device.name,
352
+ write: async (chunk) => {
353
+ const buf = chunk.slice().buffer;
354
+ if (tx.properties.writeWithoutResponse) await tx.writeValueWithoutResponse(buf);
355
+ else await tx.writeValueWithResponse(buf);
356
+ },
357
+ onNotify: (fn) => notify.push(fn),
358
+ onDisconnect: (fn) => device.addEventListener("gattserverdisconnected", fn),
359
+ disconnect: async () => server.disconnect()
360
+ };
361
+ }
362
+ // src/cat.ts
363
+ /**
364
+ * "Cat printers": the small Bluetooth thermal printers sold as GB01, MX06 and
365
+ * the like. See thermal.ts for what they share with other extras.
366
+ *
367
+ * Protocol, from rbaron/catprinter and NaitLee/Cat-Printer: packets are
368
+ * 51 78 <cmd> 00 <len> 00 <payload> <crc8(payload)> FF over service AE30,
369
+ * written to AE01. The printer sends flow control on AE02.
370
+ */
371
+ var CAT_SERVICE = "0000ae30-0000-1000-8000-00805f9b34fb";
372
+ var CAT_TX = "0000ae01-0000-1000-8000-00805f9b34fb";
373
+ var CAT_RX = "0000ae02-0000-1000-8000-00805f9b34fb";
374
+ var ROW_BYTES$1 = 48;
375
+ /**
376
+ * Models known to speak this protocol. "high": supported by both reference
377
+ * projects and widely used. "medium": listed by Cat-Printer, fewer reports.
378
+ * "tested": printed with niimai on real hardware.
379
+ */
380
+ var CAT_MODELS = [
381
+ {
382
+ prefix: "GB01",
383
+ confidence: "high"
384
+ },
385
+ {
386
+ prefix: "GB02",
387
+ confidence: "high"
388
+ },
389
+ {
390
+ prefix: "GB03",
391
+ confidence: "high",
392
+ newKind: true
393
+ },
394
+ {
395
+ prefix: "MX05",
396
+ confidence: "high",
397
+ feedWithRows: true
398
+ },
399
+ {
400
+ prefix: "MX06",
401
+ confidence: "high",
402
+ feedWithRows: true
403
+ },
404
+ {
405
+ prefix: "MX10",
406
+ confidence: "high",
407
+ feedWithRows: true
408
+ },
409
+ {
410
+ prefix: "MX08",
411
+ confidence: "medium",
412
+ feedWithRows: true
413
+ },
414
+ {
415
+ prefix: "MX09",
416
+ confidence: "medium",
417
+ feedWithRows: true
418
+ },
419
+ {
420
+ prefix: "MX11",
421
+ confidence: "medium"
422
+ },
423
+ {
424
+ prefix: "GT01",
425
+ confidence: "medium"
426
+ },
427
+ {
428
+ prefix: "YT01",
429
+ confidence: "medium"
430
+ },
431
+ {
432
+ prefix: "PD01",
433
+ confidence: "medium"
434
+ },
435
+ {
436
+ prefix: "MXTP",
437
+ confidence: "medium"
438
+ },
439
+ {
440
+ prefix: "SC03h",
441
+ confidence: "medium"
442
+ }
443
+ ];
444
+ /** Look-alikes that use other protocols. Listed in Help and docs/thermal-printers.md. */
445
+ var CAT_UNSUPPORTED = [
446
+ {
447
+ name: "MXW01",
448
+ note: "Newer protocol"
449
+ },
450
+ {
451
+ name: "PeriPage",
452
+ note: "Different protocol"
453
+ },
454
+ {
455
+ name: "Phomemo M02 / T02",
456
+ note: "Different protocol"
457
+ }
458
+ ];
459
+ var catModelFor = (name) => modelFor(CAT_MODELS, name);
460
+ var CRC_TABLE = Array.from({ length: 256 }, (_, i) => {
461
+ let c = i;
462
+ for (let b = 0; b < 8; b++) c = c & 128 ? (c << 1 ^ 7) & 255 : c << 1 & 255;
463
+ return c;
464
+ });
465
+ var crc8 = (data) => {
466
+ let c = 0;
467
+ for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 255];
468
+ return c;
469
+ };
470
+ function packet(cmd, payload) {
471
+ if (payload.length > 255) throw new Error("Payload too long");
472
+ return [
473
+ 81,
474
+ 120,
475
+ cmd,
476
+ 0,
477
+ payload.length,
478
+ 0,
479
+ ...Array.from(payload),
480
+ crc8(payload),
481
+ 255
482
+ ];
483
+ }
484
+ var u16 = (v) => [v & 255, v >> 8 & 255];
485
+ var CMD = {
486
+ feed: 161,
487
+ row: 162,
488
+ state: 163,
489
+ quality: 164,
490
+ lattice: 166,
491
+ update: 169,
492
+ energy: 175,
493
+ speed: 189,
494
+ applyEnergy: 190
495
+ };
496
+ var LATTICE_START = [
497
+ 170,
498
+ 85,
499
+ 23,
500
+ 56,
501
+ 68,
502
+ 95,
503
+ 95,
504
+ 95,
505
+ 68,
506
+ 56,
507
+ 44
508
+ ];
509
+ var LATTICE_END = [
510
+ 170,
511
+ 85,
512
+ 23,
513
+ 0,
514
+ 0,
515
+ 0,
516
+ 0,
517
+ 0,
518
+ 0,
519
+ 0,
520
+ 23
521
+ ];
522
+ /** Flow control the printer sends on AE02 when its buffer fills and drains. */
523
+ var FLOW_PAUSE = [
524
+ 81,
525
+ 120,
526
+ 174,
527
+ 1,
528
+ 1,
529
+ 0,
530
+ 16,
531
+ 112,
532
+ 255
533
+ ];
534
+ var FLOW_RESUME = [
535
+ 81,
536
+ 120,
537
+ 174,
538
+ 1,
539
+ 1,
540
+ 0,
541
+ 0,
542
+ 0,
543
+ 255
544
+ ];
545
+ /** Heat energy for each darkness step; Cat-Printer prints images at 0x4000. */
546
+ var ENERGY = [
547
+ 8192,
548
+ 12288,
549
+ 16384,
550
+ 24576,
551
+ 36864
552
+ ];
553
+ /** Rows fed after the last copy, so the print clears the tear bar. */
554
+ var FEED_AFTER = 128;
555
+ /** Blank rows between copies. */
556
+ var GAP_BETWEEN = 24;
557
+ /** Rows for a cat printer: leftmost dot in the lowest bit. */
558
+ var encodeRows$2 = (data, width, height) => packRows(data, width, height, "lsb");
559
+ /** Everything sent for one job: setup, the rows for each copy, then feed and finish. */
560
+ function printJob(rows, { density, copies, model }) {
561
+ const out = [];
562
+ const push = (cmd, payload) => out.push(...packet(cmd, payload));
563
+ push(CMD.state, [0]);
564
+ if (model?.newKind) out.push(18);
565
+ push(CMD.state, [0]);
566
+ push(CMD.quality, [50]);
567
+ push(CMD.speed, [32]);
568
+ push(CMD.energy, u16(ENERGY[Math.min(ENERGY.length, Math.max(1, Math.round(density))) - 1]));
569
+ push(CMD.applyEnergy, [1]);
570
+ push(CMD.update, [0]);
571
+ push(CMD.lattice, LATTICE_START);
572
+ const blank = new Uint8Array(ROW_BYTES$1);
573
+ for (let c = 0; c < copies; c++) {
574
+ if (c > 0) for (let i = 0; i < GAP_BETWEEN; i++) push(CMD.row, blank);
575
+ for (const row of rows) push(CMD.row, row);
576
+ }
577
+ push(CMD.lattice, LATTICE_END);
578
+ push(CMD.speed, [8]);
579
+ if (model?.feedWithRows) for (let i = 0; i < FEED_AFTER; i++) push(CMD.row, blank);
580
+ else push(CMD.feed, u16(FEED_AFTER));
581
+ push(CMD.state, [0]);
582
+ return Uint8Array.from(out);
583
+ }
584
+ /** A cat printer: the shared thermal client with cat packets and flow control. */
585
+ var CatPrinterClient = class extends ThermalPrinterClient {
586
+ model;
587
+ densityLevels = ENERGY.length;
588
+ modelName;
589
+ constructor(transport, model, pace = {
590
+ chunkMs: 20,
591
+ pauseMs: 100
592
+ }) {
593
+ super(transport, pace, 180);
594
+ this.model = model;
595
+ this.modelName = model?.prefix ?? (transport.name || "Cat printer");
596
+ transport.onNotify((data) => {
597
+ if (same(data, FLOW_PAUSE)) this.paused = true;
598
+ else if (same(data, FLOW_RESUME)) this.paused = false;
599
+ });
600
+ }
601
+ encodeRows(data, width, height) {
602
+ return encodeRows$2(data, width, height);
603
+ }
604
+ job(rows, density, copies) {
605
+ return printJob(rows, {
606
+ density,
607
+ copies,
608
+ model: this.model
609
+ });
610
+ }
611
+ };
612
+ var same = (a, b) => a.length === b.length && b.every((v, i) => a[i] === v);
613
+ // src/escpos.ts
614
+ /**
615
+ * ESC/POS mini printers: 58 mm Bluetooth receipt printers such as the MP583
616
+ * (YAEN MPT-II). They take standard raster images (GS v 0) over the 18F0
617
+ * printer service. See thermal.ts for what they share with other extras.
618
+ */
619
+ var ESCPOS_SERVICE = "000018f0-0000-1000-8000-00805f9b34fb";
620
+ var ESCPOS_WRITE = "00002af1-0000-1000-8000-00805f9b34fb";
621
+ /**
622
+ * Models known to take ESC/POS raster images over 18F0. "tested": printed
623
+ * with niimai on real hardware. "medium": the same chipset and service are
624
+ * widely reported, untested here.
625
+ */
626
+ var ESCPOS_MODELS = [
627
+ {
628
+ prefix: "MP583",
629
+ confidence: "tested",
630
+ note: "Sold as YAEN MPT-II"
631
+ },
632
+ {
633
+ prefix: "MPT-II",
634
+ confidence: "high"
635
+ },
636
+ {
637
+ prefix: "MP58",
638
+ confidence: "medium"
639
+ },
640
+ {
641
+ prefix: "MTP-II",
642
+ confidence: "medium"
643
+ },
644
+ {
645
+ prefix: "PT-210",
646
+ confidence: "medium"
647
+ },
648
+ {
649
+ prefix: "PT-200",
650
+ confidence: "medium"
651
+ },
652
+ {
653
+ prefix: "RPP02",
654
+ confidence: "medium"
655
+ },
656
+ {
657
+ prefix: "ZJ-58",
658
+ confidence: "medium"
659
+ }
660
+ ];
661
+ var escposModelFor = (name) => modelFor(ESCPOS_MODELS, name);
662
+ var ROW_BYTES = 48;
663
+ /** Rows per raster command; small bands keep the printer's buffer from overflowing. */
664
+ var BAND = 24;
665
+ /** Dots fed between copies. */
666
+ var GAP_DOTS = 24;
667
+ /** Lines fed after the last copy, so the print clears the tear bar. */
668
+ var FEED_LINES = 4;
669
+ /** Rows for an ESC/POS printer: leftmost dot in the highest bit. */
670
+ var encodeRows$1 = (data, width, height) => packRows(data, width, height, "msb");
671
+ /** ESC @, then each copy as GS v 0 bands with a gap between, then a feed. */
672
+ function escposJob(rows, copies) {
673
+ const out = [27, 64];
674
+ for (let c = 0; c < copies; c++) {
675
+ if (c > 0) out.push(27, 74, GAP_DOTS);
676
+ for (let i = 0; i < rows.length; i += BAND) {
677
+ const band = rows.slice(i, i + BAND);
678
+ out.push(29, 118, 48, 0, ROW_BYTES & 255, ROW_BYTES >> 8, band.length & 255, band.length >> 8);
679
+ for (const row of band) out.push(...row);
680
+ }
681
+ }
682
+ out.push(27, 100, FEED_LINES);
683
+ return Uint8Array.from(out);
684
+ }
685
+ /**
686
+ * An ESC/POS printer: the shared thermal client with raster commands. These
687
+ * printers send no flow control, so writes are paced. Heat settings vary by
688
+ * vendor, so darkness is left to the printer.
689
+ */
690
+ var EscPosPrinterClient = class extends ThermalPrinterClient {
691
+ model;
692
+ densityLevels = 1;
693
+ modelName;
694
+ constructor(transport, model, pace = {
695
+ chunkMs: 30,
696
+ pauseMs: 100
697
+ }) {
698
+ super(transport, pace, 100);
699
+ this.model = model;
700
+ this.modelName = model?.prefix ?? (transport.name || "Thermal printer");
701
+ }
702
+ encodeRows(data, width, height) {
703
+ return encodeRows$1(data, width, height);
704
+ }
705
+ job(rows, _density, copies) {
706
+ return escposJob(rows, copies);
707
+ }
708
+ };
709
+ // src/tspl.ts
710
+ var TSPL_SERVICE = "000018f0-0000-1000-8000-00805f9b34fb";
711
+ var TSPL_WRITE = "00002af1-0000-1000-8000-00805f9b34fb";
712
+ var TSPL_NOTIFY = "00002af0-0000-1000-8000-00805f9b34fb";
713
+ var DOTS_PER_MM = 8;
714
+ /**
715
+ * Models known to take TSPL over 18F0. "tested": printed with niimai on real
716
+ * hardware.
717
+ */
718
+ var TSPL_MODELS = [{
719
+ prefix: "QR380A",
720
+ confidence: "tested",
721
+ note: "Sold as CC390"
722
+ }];
723
+ var tsplModelFor = (name) => modelFor(TSPL_MODELS, name);
724
+ /** Common 2- to 3-inch label sizes, width × height in mm, smallest first. */
725
+ var TSPL_SIZES = [
726
+ [40, 30],
727
+ [50, 25],
728
+ [50, 30],
729
+ [50, 40],
730
+ [57, 32],
731
+ [60, 40],
732
+ [50, 50],
733
+ [70, 50],
734
+ [75, 50],
735
+ [80, 50],
736
+ [60, 60],
737
+ [80, 60],
738
+ [80, 80],
739
+ [75, 100]
740
+ ].map(([widthMm, heightMm]) => ({
741
+ widthMm,
742
+ heightMm
743
+ }));
744
+ /** TSPL's darkness steps, 0 to 15; niimai offers 1 to 15. */
745
+ var DENSITY_LEVELS = 15;
746
+ /** The gap between labels, for printers that look for it. */
747
+ var GAP_MM = 2;
748
+ /** NIIMBOT label types, as the print dialog passes them. */
749
+ var LABEL_TYPE = {
750
+ blackmark: 2,
751
+ continuous: 3
752
+ };
753
+ /** The status query, and the bits of its answer that stop a print. */
754
+ var STATUS_QUERY = [
755
+ 27,
756
+ 33,
757
+ 63
758
+ ];
759
+ var STATUS_FAULTS = [
760
+ [1, "Printer cover is open"],
761
+ [2, "Paper jam"],
762
+ [4, "Out of paper"],
763
+ [8, "Out of ribbon"]
764
+ ];
765
+ /** Replies that mean a job was taken: "OK". */
766
+ var OK = [79, 75];
767
+ /** How long to wait for "OK" before asking the printer what is wrong. */
768
+ var ACK_TIMEOUT_MS = 2e4;
769
+ /** How long to wait for the answer to a status query. */
770
+ var STATUS_TIMEOUT_MS = 2e3;
771
+ /**
772
+ * Rows for a TSPL BITMAP: as wide as the page, leftmost dot in the highest
773
+ * bit, and 0 for a dark dot.
774
+ */
775
+ function encodeRows(data, width, height) {
776
+ const bytes = Math.ceil(width / 8);
777
+ const rows = [];
778
+ for (let y = 0; y < height; y++) {
779
+ const row = new Uint8Array(bytes).fill(255);
780
+ for (let x = 0; x < width; x++) if (data[(y * width + x) * 4] < 128) row[x >> 3] &= ~(128 >> (x & 7));
781
+ rows.push(row);
782
+ }
783
+ return rows;
784
+ }
785
+ var ascii = (s) => Array.from(s, (c) => c.charCodeAt(0));
786
+ var mm = (dots) => `${Math.round(dots / DOTS_PER_MM * 10) / 10} mm`;
787
+ /** How the printer finds the start of each label. */
788
+ function paperCommand(labelType) {
789
+ if (labelType === LABEL_TYPE.continuous) return "GAP 0 mm,0 mm";
790
+ if (labelType === LABEL_TYPE.blackmark) return `BLINE ${GAP_MM} mm,0 mm`;
791
+ return `GAP ${GAP_MM} mm,0 mm`;
792
+ }
793
+ /** One label: setup, the page as one bitmap at the top left, then print it `copies` times. */
794
+ function tsplJob(rows, { density, copies, labelType }) {
795
+ const bytes = rows[0]?.length ?? 0;
796
+ const height = rows.length;
797
+ const out = ascii([
798
+ `SIZE ${mm(bytes * 8)},${mm(height)}`,
799
+ paperCommand(labelType),
800
+ "DIRECTION 0",
801
+ `DENSITY ${Math.min(DENSITY_LEVELS, Math.max(0, Math.round(density)))}`,
802
+ "CLS"
803
+ ].map((l) => `${l}\r\n`).join("") + `BITMAP 0,0,${bytes},${height},0,`);
804
+ for (const row of rows) for (const b of row) out.push(b);
805
+ out.push(...ascii(`\r\nPRINT ${Math.max(1, copies)},1\r\n`));
806
+ return Uint8Array.from(out);
807
+ }
808
+ /**
809
+ * A TSPL label printer: the shared thermal client with TSPL jobs. It shows
810
+ * as a label printer (roll sizes, paper types). Writes are paced at the size
811
+ * these printers' BLE modules take without dropping data.
812
+ */
813
+ var TsplPrinterClient = class extends ThermalPrinterClient {
814
+ model;
815
+ ackTimeoutMs;
816
+ densityLevels = DENSITY_LEVELS;
817
+ modelName;
818
+ headDots = 640;
819
+ kind = void 0;
820
+ labelSizes = TSPL_SIZES;
821
+ oks = 0;
822
+ status = null;
823
+ wake = null;
824
+ constructor(transport, model, pace = {
825
+ chunkMs: 30,
826
+ pauseMs: 100
827
+ }, ackTimeoutMs = ACK_TIMEOUT_MS) {
828
+ super(transport, pace, 100);
829
+ this.model = model;
830
+ this.ackTimeoutMs = ackTimeoutMs;
831
+ this.modelName = model?.prefix ?? (transport.name || "Label printer");
832
+ transport.onNotify((data) => {
833
+ if (data.length >= 2 && data[0] === OK[0] && data[1] === OK[1]) this.oks++;
834
+ else if (data.length === 1) this.status = data[0];
835
+ else return;
836
+ this.wake?.();
837
+ });
838
+ }
839
+ encodeRows(data, width, height) {
840
+ return encodeRows(data, width, height);
841
+ }
842
+ /** These printers cannot sense the roll; its size is remembered per printer. */
843
+ rollKey() {
844
+ return `printer:${this.transport.name || this.modelName}`;
845
+ }
846
+ job(rows, density, copies, labelType) {
847
+ this.oks = 0;
848
+ return tsplJob(rows, {
849
+ density,
850
+ copies,
851
+ labelType
852
+ });
853
+ }
854
+ /** Resolves when `done` holds or the time runs out. */
855
+ async until(done, ms) {
856
+ const deadline = Date.now() + ms;
857
+ while (!done() && Date.now() < deadline) await new Promise((resolve) => {
858
+ const t = setTimeout(resolve, deadline - Date.now());
859
+ this.wake = () => (clearTimeout(t), resolve());
860
+ });
861
+ this.wake = null;
862
+ }
863
+ /**
864
+ * Waits for the printer's "OK", so the next label never lands on a busy
865
+ * printer. Without one, asks for its status: a fault fails the print, and a
866
+ * printer that is merely quiet is left to carry on.
867
+ */
868
+ async afterPage() {
869
+ await this.until(() => this.oks > 0, this.ackTimeoutMs);
870
+ if (this.oks > 0) return;
871
+ this.status = null;
872
+ await this.send(Uint8Array.from(STATUS_QUERY));
873
+ await this.until(() => this.status !== null, STATUS_TIMEOUT_MS);
874
+ const fault = STATUS_FAULTS.find(([bit]) => (this.status ?? 0) & bit);
875
+ if (fault) throw new Error(fault[1]);
876
+ console.warn("[niimai] Label printer did not confirm the job");
877
+ }
878
+ };
879
+ // src/bluetooth.ts
880
+ /**
881
+ * The Bluetooth printer behind the Connect button. One chooser lists NIIMBOT
882
+ * printers and the known extra thermal printers. A known cat printer offering
883
+ * AE30 gets the cat client, a known ESC/POS printer offering 18F0 the ESC/POS
884
+ * client, a known TSPL label printer offering 18F0 the TSPL client, and
885
+ * everything else the NIIMBOT client exactly as before. Known names never
886
+ * overlap, so each printer matches one client at most.
887
+ */
888
+ var BluetoothPrinter = class {
889
+ lib;
890
+ inner = null;
891
+ constructor(lib) {
892
+ this.lib = lib;
893
+ }
894
+ get client() {
895
+ if (!this.inner) throw new Error("Not connected");
896
+ return this.inner;
897
+ }
898
+ async connect() {
899
+ const device = await requestPrinter([
900
+ ...CAT_MODELS,
901
+ ...ESCPOS_MODELS,
902
+ ...TSPL_MODELS
903
+ ].map((m) => m.prefix));
904
+ const cat = catModelFor(device.name);
905
+ const escpos = escposModelFor(device.name);
906
+ const tspl = tsplModelFor(device.name);
907
+ if ((cat || escpos || tspl) && device.gatt) {
908
+ const server = await device.gatt.connect();
909
+ const services = (await server.getPrimaryServices().catch(() => [])).map((s) => s.uuid);
910
+ if (cat && services.includes("0000ae30-0000-1000-8000-00805f9b34fb")) this.inner = new CatPrinterClient(await webTransport(device, server, {
911
+ service: CAT_SERVICE,
912
+ write: CAT_TX,
913
+ notify: CAT_RX
914
+ }), cat);
915
+ else if (escpos && services.includes("000018f0-0000-1000-8000-00805f9b34fb")) this.inner = new EscPosPrinterClient(await webTransport(device, server, {
916
+ service: ESCPOS_SERVICE,
917
+ write: ESCPOS_WRITE
918
+ }), escpos);
919
+ else if (tspl && services.includes("000018f0-0000-1000-8000-00805f9b34fb")) this.inner = new TsplPrinterClient(await webTransport(device, server, {
920
+ service: TSPL_SERVICE,
921
+ write: TSPL_WRITE,
922
+ notify: TSPL_NOTIFY
923
+ }), tspl);
924
+ if (this.inner) return this.inner.connect();
925
+ }
926
+ this.inner = createBleClient(await this.lib(), device);
927
+ return this.inner.connect();
928
+ }
929
+ async disconnect() {
930
+ await this.inner?.disconnect();
931
+ }
932
+ isConnected() {
933
+ return !!this.inner?.isConnected();
934
+ }
935
+ on(event, fn) {
936
+ return this.client.on(event, fn);
937
+ }
938
+ off(event, fn) {
939
+ return this.inner?.off(event, fn);
940
+ }
941
+ getPrinterInfo() {
942
+ return this.inner?.getPrinterInfo() ?? {};
943
+ }
944
+ getModelMetadata() {
945
+ return this.inner?.getModelMetadata();
946
+ }
947
+ getPrintTaskType() {
948
+ return this.inner?.getPrintTaskType();
949
+ }
950
+ getRfidInfo() {
951
+ return this.inner?.getRfidInfo() ?? {};
952
+ }
953
+ fetchRfidInfo() {
954
+ return this.client.fetchRfidInfo();
955
+ }
956
+ startHeartbeat() {
957
+ this.inner?.startHeartbeat();
958
+ }
959
+ stopHeartbeat() {
960
+ this.inner?.stopHeartbeat();
961
+ }
962
+ isHeartbeatStarted() {
963
+ return !!this.inner?.isHeartbeatStarted?.();
964
+ }
965
+ get protocol() {
966
+ return this.client.protocol;
967
+ }
968
+ get encodePage() {
969
+ return this.inner?.encodePage?.bind(this.inner);
970
+ }
971
+ get rollKey() {
972
+ return this.inner?.rollKey?.bind(this.inner);
973
+ }
974
+ };
975
+ // src/mock.ts
976
+ /** A printer that only exists in memory. Used by the demo mode and the tests. */
977
+ var MockClient = class {
978
+ meta;
979
+ connected = false;
980
+ printed = [];
981
+ failNextPrint = null;
982
+ listeners = /* @__PURE__ */ new Map();
983
+ /** Pass null to act as a model the library does not recognise. */
984
+ constructor(meta = DEMO_META) {
985
+ this.meta = meta;
986
+ }
987
+ async connect() {
988
+ this.connected = true;
989
+ this.emit("connect", { info: { deviceName: "Demo printer" } });
990
+ return { deviceName: "Demo printer" };
991
+ }
992
+ async disconnect() {
993
+ this.connected = false;
994
+ this.emit("disconnect", {});
995
+ }
996
+ isConnected() {
997
+ return this.connected;
998
+ }
999
+ on(event, fn) {
1000
+ if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
1001
+ this.listeners.get(event).add(fn);
1002
+ return this;
1003
+ }
1004
+ off(event, fn) {
1005
+ this.listeners.get(event)?.delete(fn);
1006
+ return this;
1007
+ }
1008
+ emit(event, e) {
1009
+ this.listeners.get(event)?.forEach((fn) => fn(e));
1010
+ }
1011
+ protocolVersion = 1;
1012
+ getPrinterInfo() {
1013
+ return {
1014
+ batteryPercents: 80,
1015
+ modelId: 512,
1016
+ printheadWidth: 96,
1017
+ protocolVersion: this.protocolVersion
1018
+ };
1019
+ }
1020
+ getModelMetadata() {
1021
+ return this.meta ?? void 0;
1022
+ }
1023
+ getPrintTaskType() {
1024
+ return this.meta ? "D11_V1" : void 0;
1025
+ }
1026
+ /** Set false to act like printers that report only the roll's barcode. */
1027
+ reportsPaperSize = true;
1028
+ getRfidInfo() {
1029
+ return {
1030
+ labelRfidInfo: {
1031
+ tagPresent: true,
1032
+ barCode: "6971501227941",
1033
+ allPaper: 210,
1034
+ usedPaper: 12,
1035
+ consumablesType: 1
1036
+ },
1037
+ paperInfo: this.reportsPaperSize ? {
1038
+ valid: true,
1039
+ paperWidth: 40,
1040
+ paperHeight: 12
1041
+ } : void 0
1042
+ };
1043
+ }
1044
+ async fetchRfidInfo() {
1045
+ return this.getRfidInfo();
1046
+ }
1047
+ startHeartbeat() {
1048
+ this.heartbeat = true;
1049
+ this.emit("heartbeat", { data: {
1050
+ batteryPercents: 80,
1051
+ lidClosed: true,
1052
+ paperInserted: true
1053
+ } });
1054
+ }
1055
+ heartbeat = false;
1056
+ stopHeartbeat() {
1057
+ this.heartbeat = false;
1058
+ }
1059
+ /** How many "print end" polls answer false before the printer reports done. */
1060
+ printEndPending = 0;
1061
+ protocol = {
1062
+ printEnd: async () => {
1063
+ if (this.printEndPending > 0) {
1064
+ this.printEndPending--;
1065
+ return false;
1066
+ }
1067
+ return true;
1068
+ },
1069
+ newPrintTask: (_name, options) => {
1070
+ const total = Number(options.totalPages ?? 1);
1071
+ return {
1072
+ printInit: async () => {
1073
+ if (this.failNextPrint) {
1074
+ const msg = this.failNextPrint;
1075
+ this.failNextPrint = null;
1076
+ throw new Error(msg);
1077
+ }
1078
+ },
1079
+ printPage: async (image, quantity = 1) => {
1080
+ this.printed.push({
1081
+ image,
1082
+ quantity,
1083
+ heartbeat: this.heartbeat
1084
+ });
1085
+ },
1086
+ waitForFinished: async () => {
1087
+ for (let page = 1; page <= total; page++) this.emit("printprogress", {
1088
+ page,
1089
+ pagesTotal: total,
1090
+ pagePrintProgress: 100,
1091
+ pageFeedProgress: 100
1092
+ });
1093
+ },
1094
+ printEnd: async () => true
1095
+ };
1096
+ }
1097
+ };
1098
+ };
1099
+ var DEMO_META = {
1100
+ model: "D11",
1101
+ id: [512],
1102
+ dpi: 203,
1103
+ printDirection: "left",
1104
+ printheadPixels: 96,
1105
+ paperTypes: [1],
1106
+ densityMin: 1,
1107
+ densityMax: 3,
1108
+ densityDefault: 2
1109
+ };
1110
+ // src/paper.ts
1111
+ var PAPER_TYPES = [
1112
+ {
1113
+ value: "gaps",
1114
+ label: "Labels with gaps",
1115
+ labelType: 1
1116
+ },
1117
+ {
1118
+ value: "blackmark",
1119
+ label: "Black mark",
1120
+ labelType: 2
1121
+ },
1122
+ {
1123
+ value: "continuous",
1124
+ label: "Continuous",
1125
+ labelType: 3
1126
+ },
1127
+ {
1128
+ value: "perforated",
1129
+ label: "Perforated",
1130
+ labelType: 4
1131
+ },
1132
+ {
1133
+ value: "transparent",
1134
+ label: "Transparent",
1135
+ labelType: 5
1136
+ }
1137
+ ];
1138
+ var paperFromLabelType = (n) => PAPER_TYPES.find((p) => p.labelType === n)?.value;
1139
+ var labelTypeOf = (p) => PAPER_TYPES.find((x) => x.value === p).labelType;
1140
+ var paperName = (p) => PAPER_TYPES.find((x) => x.value === p).label;
1141
+ /** The paper to print on: the label's own choice, then what the roll reports, then labels with gaps. */
1142
+ var effectivePaper = (chosen, fromRoll) => chosen ?? fromRoll ?? "gaps";
1143
+ // src/profiles.ts
1144
+ /** Manual profiles for printers niimbluelib does not recognise yet. Each mirrors a known model family. */
1145
+ var MANUAL_PROFILES = [
1146
+ {
1147
+ id: "d11",
1148
+ name: "D11 family",
1149
+ dpi: 203,
1150
+ printheadPixels: 96,
1151
+ printDirection: "left",
1152
+ printTask: "D11_V1",
1153
+ densityMin: 1,
1154
+ densityMax: 3,
1155
+ densityDefault: 2
1156
+ },
1157
+ {
1158
+ id: "d110",
1159
+ name: "D110 family",
1160
+ dpi: 203,
1161
+ printheadPixels: 96,
1162
+ printDirection: "left",
1163
+ printTask: "D110",
1164
+ densityMin: 1,
1165
+ densityMax: 3,
1166
+ densityDefault: 2
1167
+ },
1168
+ {
1169
+ id: "b1",
1170
+ name: "B1 family",
1171
+ dpi: 203,
1172
+ printheadPixels: 384,
1173
+ printDirection: "top",
1174
+ printTask: "B1",
1175
+ densityMin: 1,
1176
+ densityMax: 5,
1177
+ densityDefault: 3
1178
+ },
1179
+ {
1180
+ id: "b21",
1181
+ name: "B21 family",
1182
+ dpi: 203,
1183
+ printheadPixels: 384,
1184
+ printDirection: "top",
1185
+ printTask: "B21_V1",
1186
+ densityMin: 1,
1187
+ densityMax: 5,
1188
+ densityDefault: 3
1189
+ }
1190
+ ];
1191
+ var findManualProfile = (id) => MANUAL_PROFILES.find((p) => p.id === id);
1192
+ /**
1193
+ * Print tasks verified on hardware where niimbluelib's choice prints blank.
1194
+ * A B21 C2B on protocol 0 needs the original B21 packet formats; the library
1195
+ * gives every B21 C2B the B1 task, which that firmware accepts but never prints.
1196
+ */
1197
+ var TASK_QUIRKS = [{
1198
+ model: "B21_C2B",
1199
+ maxProtocol: 0,
1200
+ task: "B21_V1"
1201
+ }];
1202
+ function correctTask(model, protocolVersion, task) {
1203
+ return TASK_QUIRKS.find((q) => q.model === model && (protocolVersion ?? 0) <= q.maxProtocol)?.task ?? task;
1204
+ }
1205
+ /**
1206
+ * The profile to print with: the library's model data when it recognises the
1207
+ * printer, otherwise the manual choice. A detected model always wins, so a
1208
+ * choice left over from another printer cannot send the wrong settings.
1209
+ */
1210
+ function resolveProfile(meta, libraryTask, manual, protocolVersion) {
1211
+ const task = meta ? correctTask(meta.model, protocolVersion, libraryTask) : void 0;
1212
+ if (!meta || !task) return manual ?? null;
1213
+ return {
1214
+ id: `auto:${meta.model}`,
1215
+ name: meta.model.replace(/_/g, " "),
1216
+ dpi: meta.dpi,
1217
+ printheadPixels: meta.printheadPixels,
1218
+ printDirection: meta.printDirection,
1219
+ printTask: task,
1220
+ densityMin: meta.densityMin,
1221
+ densityMax: meta.densityMax,
1222
+ densityDefault: meta.densityDefault,
1223
+ ...meta.kind === "thermal" ? { kind: "thermal" } : {},
1224
+ ...meta.labelSizes ? { sizes: meta.labelSizes } : {}
1225
+ };
1226
+ }
1227
+ /** Widest label edge the printhead covers, in millimetres. */
1228
+ var printheadMm = (p) => p.printheadPixels / p.dpi * 25.4;
1229
+ /**
1230
+ * The part of a page the printhead can print, centred across the head. Pages
1231
+ * wider than the head are cropped: printers discard rows longer than the head.
1232
+ */
1233
+ function printheadCrop(width, height, p) {
1234
+ const acrossIsWidth = p.printDirection === "top";
1235
+ const across = acrossIsWidth ? width : height;
1236
+ const keep = Math.min(across, p.printheadPixels);
1237
+ const offset = Math.floor((across - keep) / 2);
1238
+ return acrossIsWidth ? {
1239
+ x: offset,
1240
+ y: 0,
1241
+ width: keep,
1242
+ height,
1243
+ cropped: keep < across
1244
+ } : {
1245
+ x: 0,
1246
+ y: offset,
1247
+ width,
1248
+ height: keep,
1249
+ cropped: keep < across
1250
+ };
1251
+ }
1252
+ /**
1253
+ * True when any black pixel of a page (RGBA, as from getImageData) falls
1254
+ * outside what the printhead covers, so part of the design would not print.
1255
+ */
1256
+ function inkOutsideHead(data, width, height, p) {
1257
+ const crop = printheadCrop(width, height, p);
1258
+ if (!crop.cropped) return false;
1259
+ for (let y = 0; y < height; y++) {
1260
+ const insideRow = y >= crop.y && y < crop.y + crop.height;
1261
+ for (let x = 0; x < width; x++) {
1262
+ if (insideRow && x >= crop.x && x < crop.x + crop.width) {
1263
+ x = crop.x + crop.width - 1;
1264
+ continue;
1265
+ }
1266
+ if (data[(y * width + x) * 4] < 128) return true;
1267
+ }
1268
+ }
1269
+ return false;
1270
+ }
1271
+ // src/service.ts
1272
+ var DISCONNECTED = {
1273
+ state: "disconnected",
1274
+ profile: null
1275
+ };
1276
+ /** What the demo printer is called wherever a printer's name shows. */
1277
+ var DEMO_NAME = "Demo printer";
1278
+ var PRINT_TIMEOUT_MS = 2e4;
1279
+ var PAGE_TIMEOUT_MS = 1e4;
1280
+ var PRINT_END_POLL_MS = 300;
1281
+ var mmToPx = (mm, dpi) => mm / 25.4 * dpi;
1282
+ /** The page moved by whole pixels on a white canvas of the same size. */
1283
+ function shiftCanvas(canvas, dx, dy) {
1284
+ dx = Math.round(dx);
1285
+ dy = Math.round(dy);
1286
+ if (!dx && !dy) return canvas;
1287
+ const out = document.createElement("canvas");
1288
+ out.width = canvas.width;
1289
+ out.height = canvas.height;
1290
+ const ctx = out.getContext("2d");
1291
+ if (!ctx) return canvas;
1292
+ ctx.fillStyle = "#fff";
1293
+ ctx.fillRect(0, 0, out.width, out.height);
1294
+ ctx.drawImage(canvas, dx, dy);
1295
+ return out;
1296
+ }
1297
+ /** Crops the page to what the printhead covers. Returns the canvas itself when it already fits. */
1298
+ function fitToPrinthead(canvas, profile) {
1299
+ const crop = printheadCrop(canvas.width, canvas.height, profile);
1300
+ if (!crop.cropped) return canvas;
1301
+ const out = document.createElement("canvas");
1302
+ out.width = crop.width;
1303
+ out.height = crop.height;
1304
+ const ctx = out.getContext("2d");
1305
+ if (!ctx) return canvas;
1306
+ ctx.drawImage(canvas, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
1307
+ return out;
1308
+ }
1309
+ /** Black pixels on the page, for the print log. A zero here means the page itself was blank. */
1310
+ function inkPixels(canvas) {
1311
+ const ctx = canvas.getContext("2d");
1312
+ if (!ctx) return null;
1313
+ const { data } = ctx.getImageData(0, 0, canvas.width, canvas.height);
1314
+ let n = 0;
1315
+ for (let i = 0; i < data.length; i += 4) if (data[i] < 128) n++;
1316
+ return n;
1317
+ }
1318
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1319
+ function withTimeout(p, ms) {
1320
+ return new Promise((resolve, reject) => {
1321
+ const t = setTimeout(() => reject(/* @__PURE__ */ new Error("Timeout waiting for the printer to finish")), ms);
1322
+ p.then((v) => (clearTimeout(t), resolve(v)), (e) => (clearTimeout(t), reject(e)));
1323
+ });
1324
+ }
1325
+ /** Translates the library's error codes and messages into short, readable ones. */
1326
+ function friendlyError(err) {
1327
+ const msg = err instanceof Error ? err.message : String(err);
1328
+ if (/user cancelled|no device selected|chooser/i.test(msg)) return "Connection cancelled";
1329
+ if (/timeout waiting for the printer to finish/i.test(msg)) return "The printer did not confirm the print";
1330
+ if (/timeout/i.test(msg)) return "Printer stopped responding";
1331
+ if (/lid|cover/i.test(msg)) return "Close the printer lid";
1332
+ if (/paper|label/i.test(msg) && /no|out|missing/i.test(msg)) return "Load a label roll";
1333
+ if (/unknown Bluetooth service|No usable channel/i.test(msg)) return msg;
1334
+ if (/disconnected|gatt/i.test(msg)) return "Printer disconnected";
1335
+ return msg || "Something went wrong";
1336
+ }
1337
+ /**
1338
+ * Owns the printer connection. The UI subscribes to status updates and calls
1339
+ * connect/print; the raw protocol stays inside niimbluelib.
1340
+ */
1341
+ var PrinterService = class {
1342
+ createClient;
1343
+ encode;
1344
+ client = null;
1345
+ status = DISCONNECTED;
1346
+ listeners = /* @__PURE__ */ new Set();
1347
+ manualProfileId = null;
1348
+ detach = null;
1349
+ /** How the current printer is connected. */
1350
+ kind = null;
1351
+ constructor(createClient, encode) {
1352
+ this.createClient = createClient;
1353
+ this.encode = encode;
1354
+ }
1355
+ getStatus() {
1356
+ return this.status;
1357
+ }
1358
+ subscribe(fn) {
1359
+ this.listeners.add(fn);
1360
+ return () => this.listeners.delete(fn);
1361
+ }
1362
+ set(patch) {
1363
+ this.replace({
1364
+ ...this.status,
1365
+ ...patch
1366
+ });
1367
+ }
1368
+ /** Swaps the whole status, so fields from an earlier connection never linger. */
1369
+ replace(status) {
1370
+ this.status = status;
1371
+ this.listeners.forEach((fn) => fn(this.status));
1372
+ }
1373
+ setManualProfile(id) {
1374
+ this.manualProfileId = id;
1375
+ if (this.client) this.set({ profile: this.currentProfile() });
1376
+ }
1377
+ currentProfile() {
1378
+ const c = this.client;
1379
+ const profile = resolveProfile(c?.getModelMetadata(), c?.getPrintTaskType(), findManualProfile(this.manualProfileId), c?.getPrinterInfo().protocolVersion);
1380
+ return profile && this.kind === "demo" ? {
1381
+ ...profile,
1382
+ name: DEMO_NAME
1383
+ } : profile;
1384
+ }
1385
+ readRfid() {
1386
+ const manual = this.client?.rollKey?.();
1387
+ if (manual) return {
1388
+ barcode: manual,
1389
+ manual: true
1390
+ };
1391
+ const info = this.client?.getRfidInfo();
1392
+ if (!info) return void 0;
1393
+ const paper = info.paperInfo?.valid ? info.paperInfo : void 0;
1394
+ const tag = info.labelRfidInfo?.tagPresent ? info.labelRfidInfo : void 0;
1395
+ if (!paper && !tag) return void 0;
1396
+ return {
1397
+ widthMm: paper?.paperWidth,
1398
+ heightMm: paper?.paperHeight,
1399
+ remaining: tag && tag.allPaper !== void 0 && tag.allPaper >= 0 ? Math.max(0, tag.allPaper - (tag.usedPaper ?? 0)) : void 0,
1400
+ capacity: tag && tag.allPaper !== void 0 && tag.allPaper > 0 ? tag.allPaper : void 0,
1401
+ barcode: tag?.barCode || void 0,
1402
+ paper: paperFromLabelType(tag?.consumablesType ?? paper?.paperType)
1403
+ };
1404
+ }
1405
+ async connect(kind) {
1406
+ if (this.client) await this.disconnect();
1407
+ this.kind = kind;
1408
+ this.replace({
1409
+ ...DISCONNECTED,
1410
+ state: "connecting"
1411
+ });
1412
+ let client;
1413
+ try {
1414
+ client = await this.createClient(kind);
1415
+ const info = await client.connect();
1416
+ this.client = client;
1417
+ this.set({ deviceName: info.deviceName });
1418
+ } catch (err) {
1419
+ this.client = null;
1420
+ this.replace(DISCONNECTED);
1421
+ throw new Error(friendlyError(err));
1422
+ }
1423
+ const onDisconnect = () => this.handleDisconnect();
1424
+ const onHeartbeat = (e) => this.set({
1425
+ battery: e.data.batteryPercents ?? this.status.battery,
1426
+ lidClosed: e.data.lidClosed,
1427
+ paperInserted: e.data.paperInserted
1428
+ });
1429
+ const onRfid = () => this.set({ label: this.readRfid() });
1430
+ const onProgress = (e) => this.set({ progress: {
1431
+ page: e.page,
1432
+ total: e.pagesTotal,
1433
+ ...e.sending !== void 0 ? { sending: e.sending } : {}
1434
+ } });
1435
+ client.on("disconnect", onDisconnect);
1436
+ client.on("heartbeat", onHeartbeat);
1437
+ client.on("rfidinfofetched", onRfid);
1438
+ client.on("printprogress", onProgress);
1439
+ this.detach = () => {
1440
+ client.off("disconnect", onDisconnect);
1441
+ client.off("heartbeat", onHeartbeat);
1442
+ client.off("rfidinfofetched", onRfid);
1443
+ client.off("printprogress", onProgress);
1444
+ };
1445
+ const meta = client.getModelMetadata();
1446
+ this.set({
1447
+ state: "ready",
1448
+ battery: client.getPrinterInfo().batteryPercents,
1449
+ detectedModel: meta?.model,
1450
+ profile: this.currentProfile(),
1451
+ label: this.readRfid()
1452
+ });
1453
+ client.startHeartbeat();
1454
+ }
1455
+ handleDisconnect() {
1456
+ this.detach?.();
1457
+ this.detach = null;
1458
+ this.client = null;
1459
+ this.replace(DISCONNECTED);
1460
+ }
1461
+ async disconnect() {
1462
+ const c = this.client;
1463
+ if (!c) return;
1464
+ c.stopHeartbeat();
1465
+ try {
1466
+ await c.disconnect();
1467
+ } finally {
1468
+ this.handleDisconnect();
1469
+ }
1470
+ }
1471
+ /**
1472
+ * B21_V1 finishes by polling "print end", but niimbluelib's poll cancels its
1473
+ * own timer on the first reply, so it never resolves unless the printer is
1474
+ * already done. That task polls here instead.
1475
+ */
1476
+ async waitForFinished(client, task, name, copies) {
1477
+ if (name !== "B21_V1") return task.waitForFinished();
1478
+ this.set({ progress: {
1479
+ page: 0,
1480
+ total: copies
1481
+ } });
1482
+ while (!await client.protocol.printEnd()) await sleep(PRINT_END_POLL_MS);
1483
+ this.set({ progress: {
1484
+ page: copies,
1485
+ total: copies
1486
+ } });
1487
+ }
1488
+ async print(source, opts) {
1489
+ const client = this.client;
1490
+ const profile = this.status.profile;
1491
+ if (!client) throw new Error("Connect a printer first");
1492
+ if (!profile) throw new Error("Choose your printer type");
1493
+ if (this.status.state === "printing") throw new Error("Already printing");
1494
+ const pages = "page" in source ? source : {
1495
+ count: 1,
1496
+ page: async () => source
1497
+ };
1498
+ const copies = Math.max(1, Math.floor(opts.copies));
1499
+ const total = copies * Math.max(1, pages.count);
1500
+ const density = Math.min(profile.densityMax, Math.max(profile.densityMin, Math.round(opts.density)));
1501
+ const task = client.protocol.newPrintTask(profile.printTask, {
1502
+ totalPages: total,
1503
+ density,
1504
+ labelType: opts.labelType ?? 1,
1505
+ pageColor: 0,
1506
+ statusPollIntervalMs: 100,
1507
+ statusTimeoutMs: 8e3
1508
+ });
1509
+ client.stopHeartbeat();
1510
+ this.set({
1511
+ state: "printing",
1512
+ progress: {
1513
+ page: 0,
1514
+ total
1515
+ }
1516
+ });
1517
+ try {
1518
+ const offset = opts.offset ?? {
1519
+ x: 0,
1520
+ y: 0
1521
+ };
1522
+ for (let i = 0; i < pages.count; i++) {
1523
+ const canvas = await pages.page(i);
1524
+ const page = fitToPrinthead(shiftCanvas(canvas, mmToPx(offset.x, profile.dpi), mmToPx(offset.y, profile.dpi)), profile);
1525
+ const image = client.encodePage ? await client.encodePage(page) : await this.encode(page, profile.printDirection);
1526
+ if (i === 0) {
1527
+ console.info("[niimai] print", {
1528
+ profile: profile.id,
1529
+ task: profile.printTask,
1530
+ direction: profile.printDirection,
1531
+ printhead: profile.printheadPixels,
1532
+ page: `${canvas.width}x${canvas.height}`,
1533
+ sent: `${page.width}x${page.height}`,
1534
+ density,
1535
+ copies,
1536
+ pages: pages.count,
1537
+ ink: inkPixels(page)
1538
+ });
1539
+ await task.printInit();
1540
+ }
1541
+ await task.printPage(image, copies);
1542
+ }
1543
+ await withTimeout(this.waitForFinished(client, task, profile.printTask, total), PRINT_TIMEOUT_MS + total * PAGE_TIMEOUT_MS);
1544
+ } catch (err) {
1545
+ throw new Error(friendlyError(err));
1546
+ } finally {
1547
+ try {
1548
+ await task.printEnd();
1549
+ } catch {}
1550
+ if (this.client) {
1551
+ client.startHeartbeat();
1552
+ this.set({
1553
+ state: "ready",
1554
+ progress: void 0
1555
+ });
1556
+ client.fetchRfidInfo().then(() => this.set({ label: this.readRfid() }), () => {});
1557
+ }
1558
+ }
1559
+ }
1560
+ };
1561
+ // src/client.ts
1562
+ var supportsBluetooth = () => typeof navigator !== "undefined" && "bluetooth" in navigator;
1563
+ var supportsSerial = () => typeof navigator !== "undefined" && "serial" in navigator;
1564
+ function detectPlatform(ua = typeof navigator === "undefined" ? "" : navigator.userAgent, touchPoints = typeof navigator === "undefined" ? 0 : navigator.maxTouchPoints) {
1565
+ if (/iPhone|iPad|iPod/.test(ua) || /Macintosh/.test(ua) && touchPoints > 1) return "ios";
1566
+ if (/Android/.test(ua)) return "android";
1567
+ return "desktop";
1568
+ }
1569
+ /**
1570
+ * Why a connection type cannot be used in this browser, in a few words, or
1571
+ * null when it can. iOS browsers all run on WebKit, which has neither Web
1572
+ * Bluetooth nor Web Serial; Bluefy adds Web Bluetooth there.
1573
+ */
1574
+ function unsupportedReason(kind, platform = detectPlatform()) {
1575
+ if (kind === "demo") return null;
1576
+ if (kind === "bluetooth" ? supportsBluetooth() : supportsSerial()) return null;
1577
+ if (platform === "ios") return kind === "bluetooth" ? "On iPhone and iPad, use the Bluefy browser" : "Not available on iPhone and iPad";
1578
+ if (platform === "android") return "Open niimai in Chrome";
1579
+ return "Needs Chrome or Edge";
1580
+ }
1581
+ // src/index.ts
1582
+ /**
1583
+ * libniimai: connect to NIIMBOT, TSPL, ESC/POS and cat printers from the
1584
+ * browser over Web Bluetooth or Web Serial, and print a canvas on them.
1585
+ */
1586
+ var niimbot = () => import("@mmote/niimbluelib");
1587
+ /**
1588
+ * A client for one kind of connection. Bluetooth finds the printer family
1589
+ * from the device the user picks; serial is NIIMBOT only; demo is a printer
1590
+ * in memory.
1591
+ */
1592
+ async function createClient(kind) {
1593
+ if (kind === "demo") return new MockClient();
1594
+ if (kind === "bluetooth") return new BluetoothPrinter(niimbot);
1595
+ return new (await (niimbot())).NiimbotSerialClient();
1596
+ }
1597
+ /** A ready printer service: connect, watch its status, print canvases. */
1598
+ function createPrinter() {
1599
+ return new PrinterService(createClient, async (canvas, direction) => (await niimbot()).ImageEncoder.encodeCanvas(canvas, 0, direction));
1600
+ }
1601
+ export { BluetoothPrinter, CAT_MODELS, CAT_UNSUPPORTED, CatPrinterClient, DEMO_META, DEMO_NAME, ESCPOS_MODELS, EscPosPrinterClient, MANUAL_PROFILES, MockClient, PAPER_TYPES, PrinterService, THERMAL_DEFAULT_SIZE, THERMAL_HEAD_DOTS, THERMAL_HEAD_MM, THERMAL_SIZES, TSPL_MODELS, TSPL_SIZES, ThermalPrinterClient, TsplPrinterClient, printJob as catJob, catModelFor, correctTask, createClient, createPrinter, describeBleError, detectPlatform, effectivePaper, escposJob, escposModelFor, findManualProfile, fitToPrinthead, friendlyError, inkOutsideHead, labelTypeOf, modelFor, paperFromLabelType, paperName, printheadCrop, printheadMm, resolveProfile, shiftCanvas, supportsBluetooth, supportsSerial, tsplJob, tsplModelFor, unsupportedReason, webTransport };
1602
+
1603
+ //# sourceMappingURL=libniimai.js.map