taro-bluetooth-print 2.15.2 → 2.15.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.15.3] - 2026-07-10
4
+
5
+ ### Added
6
+
7
+ - **`BluetoothPrinter.writeRaw(buffer, options?)`** — 原始字节透传通道,绕过 `CommandBuilder` 直接走连接层。
8
+ - 用途:让 `TsplDriver` / `ZplDriver` / `StarPrinter` / `CPCL` 等非 ESC/POS driver 通过统一管线端到端跑通
9
+ - 复用 `PrintJobManager` 的分片 / 重试 / 进度 / 暂停 / 状态机
10
+ - 不触碰 `commandBuilder` 命令队列 — 可与 `text()` / `qr()` / `cut()` 自由混用
11
+ - 抛出 `CONNECTION_FAILED` (未连接) / `PRINT_JOB_FAILED` (adapter 错误) — 与 `print()` 一致
12
+ - 9 个新单元测试覆盖端到端 TSPL 流、进度事件、完成事件、错误处理、空 buffer 等场景
13
+ - **配套**:`examples/weapp/src/pages/label/index.tsx` 端到端跑通 TSPL 标签打印(之前只能到 step 3)
14
+
15
+ - **6 个新 / 扩展 API 文档** — 覆盖 `writeRaw()`、drivers / adapters / factory / errors / plugins 5 个新文件 + bluetooth-printer.md 扩展原始字节透传章节
16
+ - [bluetooth-printer.md (扩展)](./api/bluetooth-printer.md#原始字节透传v2153) — 新增 `writeRaw()` 章节
17
+ - [drivers.md (新)](./api/drivers.md) — TSPL / ZPL / CPCL / StarPRNT 完整 driver 指南
18
+ - [adapters.md (新)](./api/adapters.md) — 平台 adapter 接入 + AdapterFactory 自动选择
19
+ - [errors.md (新)](./api/errors.md) — 完整错误码 + 子类 + retry 模式
20
+ - [factory.md (新)](./api/factory.md) — `createBluetoothPrinter` / `createWebBluetoothPrinter` / `PrinterFactory`
21
+ - [plugins.md (新)](./api/plugins.md) — PluginManager / 内置插件 / 自定义插件
22
+ - `docs/api/index.md` TOC 重构:新增 "服务层"、"工具与模板"、"工厂"、"插件系统"、"类型定义"、"事件总线" 分类块
23
+
24
+ ### Changed
25
+
26
+ - **构建产物按 sub-export 拆分** — 主 bundle `index.es.js` / `index.cjs.js` 从 **630KB → 86KB**(-86%)
27
+ - 5 个 lib entry:`index` / `core` / `drivers` / `adapters` / `encoding`
28
+ - 共享代码 hoist 到 `dist/chunks/shared-*.js`(190KB gzip)
29
+ - 总 dist 大小 2.6MB → ~715KB(-73%)
30
+ - 浏览器端可按需 import:`taro-bluetooth-print/drivers` 只取驱动层
31
+ - 新增独立 UMD 构建配置 `vite.umd.config.ts`(Vite 7 不支持 multi-entry + UMD)
32
+ - 新增 script:`npm run build:umd`
33
+ - **修复**:vitepress public 资源不再 leak 到 dist/`hero-illustration.svg` / `logo.svg` / `manifest.webmanifest` 等
34
+
35
+ ### Testing
36
+
37
+ - 新增 **206 个单元测试**(1,102 → 1,308 个),覆盖率 **62.61% → 66.97%**(lines)
38
+ - 重点补强:
39
+ - `template/engines/TemplateRenderer` 47.69% → **99.67%**
40
+ - `template/parsers/TemplateParser` 73.52% → **97.05%**
41
+ - `utils/platform` 47.61% → **100%**
42
+ - `utils/BoundedOrderedMap` 70.83% → **100%**
43
+ - `utils/normalizeError` 62.5% → **100%**
44
+ - 新增 4 个接口契约测试:`CommandBuilder` / `ConnectionManager` / `PrintJobManager` 各自实现对应 `I*` 接口
45
+ - 新增 1 个 `PrintJobManager` 边界测试集(cancel/pause/resume/start 边界 + 大 buffer 分片 + 错误恢复 + 静态 store)
46
+ - 修复 4 个 spec 假设错误(strict `> 0` 时间比较、`resume()` 早返回、no-op adapter 错误码、清理阈值)
47
+
48
+ ### Follow-up (v3.x)
49
+
50
+ - `TsplDriverAdapter` — 让 `printer.text(...).qr(...).print()` 在 TSPL 模式也能跑(对称体验)。该改动有 4 个 design trade-off(cursor 策略 / init 语义 / image RLE 编码 / 字节累加方式),不在 v2.15.3 hotfix 范围内。
51
+ - `interfaces/*.ts` 0% 覆盖率保留 — 纯 type-only 文件,无运行时代码可测。
52
+ - **剩余 API 文档**(v2.15.4+):`connection-manager` / `command-builder` / `print-job-manager` / `print-scheduler` / `cloud-print-manager` / `qrcode-discovery` / `qrcode-parser` / `text-formatter` / `preview-renderer` / `encoding-service` / `image-processing` / `logger` / `platform` / `output-limiter` / `event-emitter` / `types`(17 个服务层 / 工具 / 类型文档)。v2.15.3 周期内优先保障 writeRaw API + 用户最常用的 4 个模块(drivers / adapters / errors / factory / plugins)有正式文档。
53
+
54
+ ---
55
+
3
56
  ## [2.15.2] - 2026-07-07
4
57
 
5
58
  ### Changed
@@ -0,0 +1 @@
1
+ "use strict";var e=Object.defineProperty,t=Object.defineProperties,r=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable,s=(t,r,i)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[r]=i,n=(e,t,r)=>new Promise((i,a)=>{var c=e=>{try{n(r.next(e))}catch(t){a(t)}},s=e=>{try{n(r.throw(e))}catch(t){a(t)}},n=e=>e.done?i(e.value):Promise.resolve(e.value).then(c,s);n((r=r.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("../chunks/AdapterFactory-B91w5soC.js"),d=require("../chunks/shared-C3EQK7YH.js"),l=globalThis.Platform;class u extends o.C{constructor(){var e;super("ReactNativeAdapter",(e=((e,t)=>{for(var r in t||(t={}))a.call(t,r)&&s(e,r,t[r]);if(i)for(var r of i(t))c.call(t,r)&&s(e,r,t[r]);return e})({},o.D),t(e,r({maxChunkSize:512,connectionCheckInterval:0}))))}computeTimeoutMs(e){return Math.max(2e3,Math.min(1e4,1e3+10*e))}writeSingleChunk(e,t,r){return n(this,null,function*(){if(!r)return{success:!1,error:Error("RNWriteOptions required")};const i=r.arrayBufferToBase64(e.buffer);try{return yield r.bleManager.writeCharacteristicWithResponseForDevice(t.deviceId,t.serviceId,t.characteristicId,i),{success:!0}}catch(a){try{return yield r.bleManager.writeCharacteristicWithoutResponseForDevice(t.deviceId,t.serviceId,t.characteristicId,i),{success:!0}}catch(c){return{success:!1,error:d.C(c)}}}})}}class h extends o.B{constructor(e){if(super(),this.deviceCache=new Map,this.writeStrategy=new u,!(null==e?void 0:e.bleManager))throw new d.B(d.z.INVALID_CONFIGURATION,"ReactNativeAdapter requires a bleManager instance (e.g., react-native-ble-plx). Please pass { bleManager: yourBleManager } in the constructor.");this.bleManager=e.bleManager,l&&"ios"!==l.OS&&"android"!==l.OS&&d.L.scope("ReactNativeAdapter").warn(`Running on unsupported platform: ${l.OS}. BLE may not work correctly.`)}connect(e){return n(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return d.L.scope("ReactNativeAdapter").warn("Device already connected:",e),void this.updateState(d.P.CONNECTED);this.updateState(d.P.CONNECTING),d.L.scope("ReactNativeAdapter").debug("Connecting to device:",e);try{const t=15e3,r=yield d.A(this.performConnect(e),t,"Connection timeout");this.deviceCache.set(e,r),yield this.discoverServices(e,r),this.updateState(d.P.CONNECTED),d.L.scope("ReactNativeAdapter").info("Device connected successfully")}catch(t){throw this.updateState(d.P.DISCONNECTED),this.cleanupDevice(e),this.classifyConnectionError(t,e)}})}performConnect(e){return n(this,null,function*(){const t=yield this.bleManager.connectToDevice(e,{timeout:1e4});try{yield t.requestConnectionPriority()}catch(r){}return t})}disconnect(e){return n(this,null,function*(){this.validateDeviceId(e),this.updateState(d.P.DISCONNECTING),d.L.scope("ReactNativeAdapter").debug("Disconnecting from device:",e);const t=()=>{this.cleanupDevice(e),this.deviceCache.delete(e),this.updateState(d.P.DISCONNECTED),d.L.scope("ReactNativeAdapter").info("Device disconnected successfully")};try{yield this.bleManager.disconnectFromDevice(e,!0),t()}catch(r){d.L.scope("ReactNativeAdapter").warn("Disconnect error (ignored):",r),t()}})}write(e,t,r){return n(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const i=this.getServiceInfo(e),a=this.deviceCache.get(e);if(!a||!a.isConnected)throw this.cleanupDevice(e),new d.B(d.z.DEVICE_DISCONNECTED,`Device ${e} is not connected`);yield this.writeStrategy.execute(t,{deviceId:e,serviceId:i.serviceId,characteristicId:i.characteristicId},null!=r?r:{},{bleManager:this.bleManager,arrayBufferToBase64:this.arrayBufferToBase64.bind(this)})})}startDiscovery(){return new Promise((e,t)=>{try{this.bleManager.startDeviceScan(null,{allowDuplicates:!1},e=>{e&&t(d.C(e))}),e()}catch(r){t(d.C(r))}})}stopDiscovery(){return new Promise(e=>{this.bleManager.stopDeviceScan(),e()})}discoverServices(e,t){return n(this,null,function*(){yield this.discoverAndCacheServices(e,()=>n(this,null,function*(){return((yield this.bleManager.discoverAllServicesAndCharacteristicsForDevice(e)).services||[]).map(e=>({serviceId:e.uuid,characteristics:e.characteristics.map(e=>({characteristicId:e.uuid,isWritable:e.isWritableWithResponse||e.isWritableWithoutResponse}))}))}))})}arrayBufferToBase64(e){var t;const r=new Uint8Array(e);let i="";for(let a=0;a<r.byteLength;a++)i+=String.fromCharCode(null!=(t=r[a])?t:0);return globalThis.btoa(i)}}exports.AdapterFactory=o.A,exports.AlipayAdapter=o.a,exports.BaiduAdapter=o.b,exports.BaseAdapter=o.B,exports.ByteDanceAdapter=o.c,exports.MiniProgramAdapter=o.M,exports.QQAdapter=o.Q,exports.TaroAdapter=o.T,exports.WebBluetoothAdapter=o.W,exports.ReactNativeAdapter=h;
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,t=Object.defineProperties,r=Object.getOwnPropertyDescriptors,i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable,s=(t,r,i)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[r]=i,n=(e,t,r)=>new Promise((i,a)=>{var c=e=>{try{n(r.next(e))}catch(t){a(t)}},s=e=>{try{n(r.throw(e))}catch(t){a(t)}},n=e=>e.done?i(e.value):Promise.resolve(e.value).then(c,s);n((r=r.apply(e,t)).next())});import{B as o,C as d,D as l}from"../chunks/AdapterFactory-sRvkpRnt.js";import{A as u,a as h,b as p,c as v,M as y,Q as f,T as C,W as b}from"../chunks/AdapterFactory-sRvkpRnt.js";import{B as D,z as g,L as m,P as I,A as N,C as w}from"../chunks/shared-DuaS72fL.js";const A=globalThis.Platform;class S extends d{constructor(){var e;super("ReactNativeAdapter",(e=((e,t)=>{for(var r in t||(t={}))a.call(t,r)&&s(e,r,t[r]);if(i)for(var r of i(t))c.call(t,r)&&s(e,r,t[r]);return e})({},l),t(e,r({maxChunkSize:512,connectionCheckInterval:0}))))}computeTimeoutMs(e){return Math.max(2e3,Math.min(1e4,1e3+10*e))}writeSingleChunk(e,t,r){return n(this,null,function*(){if(!r)return{success:!1,error:Error("RNWriteOptions required")};const i=r.arrayBufferToBase64(e.buffer);try{return yield r.bleManager.writeCharacteristicWithResponseForDevice(t.deviceId,t.serviceId,t.characteristicId,i),{success:!0}}catch(a){try{return yield r.bleManager.writeCharacteristicWithoutResponseForDevice(t.deviceId,t.serviceId,t.characteristicId,i),{success:!0}}catch(c){return{success:!1,error:w(c)}}}})}}class O extends o{constructor(e){if(super(),this.deviceCache=/* @__PURE__ */new Map,this.writeStrategy=new S,!(null==e?void 0:e.bleManager))throw new D(g.INVALID_CONFIGURATION,"ReactNativeAdapter requires a bleManager instance (e.g., react-native-ble-plx). Please pass { bleManager: yourBleManager } in the constructor.");this.bleManager=e.bleManager,A&&"ios"!==A.OS&&"android"!==A.OS&&m.scope("ReactNativeAdapter").warn(`Running on unsupported platform: ${A.OS}. BLE may not work correctly.`)}connect(e){return n(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return m.scope("ReactNativeAdapter").warn("Device already connected:",e),void this.updateState(I.CONNECTED);this.updateState(I.CONNECTING),m.scope("ReactNativeAdapter").debug("Connecting to device:",e);try{const t=15e3,r=yield N(this.performConnect(e),t,"Connection timeout");this.deviceCache.set(e,r),yield this.discoverServices(e,r),this.updateState(I.CONNECTED),m.scope("ReactNativeAdapter").info("Device connected successfully")}catch(t){throw this.updateState(I.DISCONNECTED),this.cleanupDevice(e),this.classifyConnectionError(t,e)}})}performConnect(e){return n(this,null,function*(){const t=yield this.bleManager.connectToDevice(e,{timeout:1e4});try{yield t.requestConnectionPriority()}catch(r){}return t})}disconnect(e){return n(this,null,function*(){this.validateDeviceId(e),this.updateState(I.DISCONNECTING),m.scope("ReactNativeAdapter").debug("Disconnecting from device:",e);const t=()=>{this.cleanupDevice(e),this.deviceCache.delete(e),this.updateState(I.DISCONNECTED),m.scope("ReactNativeAdapter").info("Device disconnected successfully")};try{yield this.bleManager.disconnectFromDevice(e,!0),t()}catch(r){m.scope("ReactNativeAdapter").warn("Disconnect error (ignored):",r),t()}})}write(e,t,r){return n(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const i=this.getServiceInfo(e),a=this.deviceCache.get(e);if(!a||!a.isConnected)throw this.cleanupDevice(e),new D(g.DEVICE_DISCONNECTED,`Device ${e} is not connected`);yield this.writeStrategy.execute(t,{deviceId:e,serviceId:i.serviceId,characteristicId:i.characteristicId},null!=r?r:{},{bleManager:this.bleManager,arrayBufferToBase64:this.arrayBufferToBase64.bind(this)})})}startDiscovery(){return new Promise((e,t)=>{try{this.bleManager.startDeviceScan(null,{allowDuplicates:!1},e=>{e&&t(w(e))}),e()}catch(r){t(w(r))}})}stopDiscovery(){return new Promise(e=>{this.bleManager.stopDeviceScan(),e()})}discoverServices(e,t){return n(this,null,function*(){yield this.discoverAndCacheServices(e,()=>n(this,null,function*(){return((yield this.bleManager.discoverAllServicesAndCharacteristicsForDevice(e)).services||[]).map(e=>({serviceId:e.uuid,characteristics:e.characteristics.map(e=>({characteristicId:e.uuid,isWritable:e.isWritableWithResponse||e.isWritableWithoutResponse}))}))}))})}arrayBufferToBase64(e){var t;const r=new Uint8Array(e);let i="";for(let a=0;a<r.byteLength;a++)i+=String.fromCharCode(null!=(t=r[a])?t:0);return globalThis.btoa(i)}}export{u as AdapterFactory,h as AlipayAdapter,p as BaiduAdapter,o as BaseAdapter,v as ByteDanceAdapter,y as MiniProgramAdapter,f as QQAdapter,O as ReactNativeAdapter,C as TaroAdapter,b as WebBluetoothAdapter};
@@ -0,0 +1 @@
1
+ "use strict";var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,c=(t,i,n)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,o=(e,t)=>{for(var i in t||(t={}))r.call(t,i)&&c(e,i,t[i]);if(n)for(var i of n(t))s.call(t,i)&&c(e,i,t[i]);return e},a=(e,t,i)=>new Promise((n,r)=>{var s=e=>{try{o(i.next(e))}catch(t){r(t)}},c=e=>{try{o(i.throw(e))}catch(t){r(t)}},o=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,c);o((i=i.apply(e,t)).next())});const l=require("./shared-C3EQK7YH.js"),u={defaultChunkSize:50,defaultDelay:20,defaultRetries:3,minChunkSize:10,maxChunkSize:256,maxDelay:200,successThreshold:3,failureThreshold:2,connectionCheckInterval:10},h=class e{constructor(e,t={}){this.logger=l.L.scope(e),this.config=o(o({},u),t)}checkConnection(e){return a(this,null,function*(){})}computeTimeoutMs(t){return Math.max(e.TIMEOUT_BASE_MS,Math.min(e.TIMEOUT_MAX_MS,e.TIMEOUT_BASE_MS+t*e.TIMEOUT_PER_BYTE_MS))}getMaxChunkSize(e){return this.config.maxChunkSize}execute(e,t){return a(this,arguments,function*(e,t,i={},n){const r=new Uint8Array(e);if(0===r.length)return void this.logger.warn("No data to write");const s=this.initializeTransmissionParams(r,i),c=this.getMaxChunkSize(t.deviceId),o={successCount:0,consecutiveFailures:0,currentChunkSize:s.chunkSize,baseDelay:s.delay};this.logger.debug(`Writing ${r.length} bytes with initial chunkSize=${o.currentChunkSize}, delay=${o.baseDelay}ms`);for(let a=0;a<r.length;a+=o.currentChunkSize){yield this.maybeCheckConnection(a,o.currentChunkSize,t.deviceId);const e=Math.floor(a/o.currentChunkSize)+1,i=yield this.writeChunkWithRetries(r,a,o.currentChunkSize,t,e,s.retries,o.baseDelay,n);if(!i)return;this.adjustTransmissionParams(o,i,c,s.minChunkSize,s.maxDelay,s.successThreshold,s.failureThreshold,e,a,r.length),yield this.maybeDelay(a,o.currentChunkSize,r.length,o.baseDelay)}this.logger.info(`Successfully wrote ${r.length} bytes`)})}initializeTransmissionParams(e,t){var i,n,r;return{chunkSize:Math.max(1,Math.min(256,null!=(i=t.chunkSize)?i:this.config.defaultChunkSize)),delay:Math.max(10,Math.min(100,null!=(n=t.delay)?n:this.config.defaultDelay)),retries:Math.max(1,Math.min(10,null!=(r=t.retries)?r:this.config.defaultRetries)),minChunkSize:this.config.minChunkSize,maxDelay:this.config.maxDelay,successThreshold:this.config.successThreshold,failureThreshold:this.config.failureThreshold}}maybeCheckConnection(e,t,i){return a(this,null,function*(){e>0&&Math.floor(e/t)%this.config.connectionCheckInterval===0&&(yield this.checkConnection(i))})}writeChunkWithRetries(e,t,i,n,r,s,c,o){return a(this,null,function*(){var a;const u=e.slice(t,t+i),h=Math.ceil(e.length/i);for(let e=0;s>=e;e++){const t=yield this.writeSingleChunk(u,n,o);if(t.success)return this.logger.debug(`Chunk ${r}/${h} written successfully`),!0;if(e>=s)throw this.logger.error(`Chunk ${r} failed after ${s} retries`),new l.B(l.z.WRITE_FAILED,`Failed to write chunk ${r}/${h}`,null!=(a=t.error)?a:Error("Unknown write error"));this.logger.warn(`Chunk ${r} write failed, retry ${e+1}/${s}`);const i=c*Math.pow(2,e);yield new Promise(e=>setTimeout(e,Math.min(i,this.config.maxDelay)))}return!1})}adjustTransmissionParams(t,i,n,r,s,c,o,a,l,u){i?(t.successCount++,t.consecutiveFailures=0,t.successCount%c===0&&t.currentChunkSize<n&&(t.currentChunkSize=Math.min(n,t.currentChunkSize+e.CHUNK_SIZE_STEP),t.baseDelay=Math.max(t.baseDelay/e.DELAY_RECOVERY_FACTOR,this.config.defaultDelay),this.logger.debug(`Increased chunk size to ${t.currentChunkSize}, delay to ${t.baseDelay}ms`))):(t.consecutiveFailures++,t.consecutiveFailures>=o&&t.currentChunkSize>r&&(t.currentChunkSize=Math.max(r,t.currentChunkSize-e.CHUNK_SIZE_STEP),t.baseDelay=Math.min(t.baseDelay*e.DELAY_BACKOFF_FACTOR,s),this.logger.debug(`Decreased chunk size to ${t.currentChunkSize}, delay to ${t.baseDelay}ms`),t.consecutiveFailures=0))}maybeDelay(e,t,i,n){return a(this,null,function*(){i>e+t&&(yield new Promise(e=>setTimeout(e,n)))})}};h.CHUNK_SIZE_STEP=5,h.DELAY_BACKOFF_FACTOR=1.5,h.DELAY_RECOVERY_FACTOR=1.2,h.TIMEOUT_BASE_MS=1e3,h.TIMEOUT_PER_BYTE_MS=5,h.TIMEOUT_MAX_MS=1e4;let d=h;class v extends d{constructor(e){var n;super("MiniProgramAdapter",(n=o({},u),t(n,i({connectionCheckInterval:5})))),this.api=e}writeSingleChunk(e,t){return a(this,null,function*(){const i=this.computeTimeoutMs(e.length);try{const n=this.api.writeBLECharacteristicValue({deviceId:t.deviceId,serviceId:t.serviceId,characteristicId:t.characteristicId,value:e.buffer});let r;const s=new Promise((e,t)=>{r=setTimeout(()=>{t(Error(`Write timeout after ${i}ms`))},i)});return yield Promise.race([n,s]),r&&clearTimeout(r),{success:!0}}catch(n){return{success:!1,error:l.C(n)}}})}checkConnection(e){return a(this,null,function*(){try{if(!(yield this.api.getBLEConnectionState({deviceId:e})).connected)throw new l.B(l.z.DEVICE_DISCONNECTED,"Device disconnected")}catch(t){if(t instanceof l.B)throw t;throw new l.B(l.z.DEVICE_DISCONNECTED,"Device disconnected",l.C(t))}})}}class g{constructor(){this.serviceCache=new Map,this.logger=l.L.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new l.B(l.z.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new l.B(l.z.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,n;return{chunkSize:Math.max(1,Math.min(256,null!=(t=null==e?void 0:e.chunkSize)?t:20)),delay:Math.max(10,Math.min(100,null!=(i=null==e?void 0:e.delay)?i:20)),retries:Math.max(1,Math.min(10,null!=(n=null==e?void 0:e.retries)?n:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new l.B(l.z.SERVICE_NOT_FOUND,"Device not connected or services not discovered. Call connect() first.");return t}isDeviceConnected(e){return this.serviceCache.has(e)}cleanupDevice(e){this.serviceCache.delete(e)}classifyConnectionError(e,t){const i=l.C(e).message;return i.includes("timeout")?new l.B(l.z.CONNECTION_TIMEOUT,`Connection to device ${t} timed out`,l.C(e)):i.includes("not found")||i.includes("not exist")?new l.B(l.z.DEVICE_NOT_FOUND,`Device ${t} not found`,l.C(e)):new l.B(l.z.CONNECTION_FAILED,"Failed to connect to device "+t,l.C(e))}discoverAndCacheServices(e,t){return a(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const i=yield t();for(const t of i){const i=t.characteristics.find(e=>e.isWritable);if(i)return this.serviceCache.set(e,{serviceId:t.serviceId,characteristicId:i.characteristicId}),void this.logger.info("Found writeable characteristic:",{service:t.serviceId,characteristic:i.characteristicId})}throw new l.B(l.z.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(i){if(i instanceof l.B)throw i;throw new l.B(l.z.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",l.C(i))}})}destroy(){this.logger.debug("Destroying BaseAdapter"),this.serviceCache.clear(),this.stateCallback=void 0}}class f extends g{constructor(){super(...arguments),this.writeStrategy=null}getWriteStrategy(){return this.writeStrategy||(this.writeStrategy=new v(this.getApi())),this.writeStrategy}connect(e){return a(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(l.P.CONNECTED);this.updateState(l.P.CONNECTING),this.logger.debug("Connecting to device:",e);try{yield l.A(this.getApi().createBLEConnection({deviceId:e}),1e4,"Connection timeout after 10 seconds"),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(l.P.CONNECTED),this.logger.info("Device connected successfully"),this.getApi().onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(l.P.DISCONNECTED),this.cleanupDevice(e))})}catch(t){throw this.updateState(l.P.DISCONNECTED),this.logger.error("Connection failed:",t),this.classifyConnectionError(t,e)}})}finalizeDisconnect(e){this.cleanupDevice(e),this.updateState(l.P.DISCONNECTED),this.logger.info("Device disconnected successfully")}disconnect(e){return a(this,null,function*(){this.validateDeviceId(e),this.updateState(l.P.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield this.getApi().closeBLEConnection({deviceId:e}),this.finalizeDisconnect(e)}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.finalizeDisconnect(e)}})}write(e,t,i){return a(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const n=this.getServiceInfo(e);yield this.getWriteStrategy().execute(t,{deviceId:e,serviceId:n.serviceId,characteristicId:n.characteristicId},null!=i?i:{})})}discoverServices(e){return a(this,null,function*(){yield this.discoverAndCacheServices(e,()=>a(this,null,function*(){const t=yield this.getApi().getBLEDeviceServices({deviceId:e}),i=[];for(const n of t.services){const t=yield this.getApi().getBLEDeviceCharacteristics({deviceId:e,serviceId:n.uuid});i.push({serviceId:n.uuid,characteristics:t.characteristics.map(e=>({characteristicId:e.uuid,isWritable:!(!e.properties.write&&!e.properties.writeWithoutResponse)}))})}return i}))})}}class C extends f{getApi(){return Taro}}class D extends f{getApi(){return my}}class p extends f{getApi(){return swan}}class m extends f{getApi(){return tt}}class I extends f{getApi(){return qq}}const w=["000018f0-0000-1000-8000-00805f9b34fb","49535343-fe7d-4ae5-8fa9-9fafd205e455","e7810a71-73ae-499d-8c15-faa9aef0c3f2"];class E extends g{constructor(){super(...arguments),this.devices=new Map,this.discoveredDevices=new Map,this.connectionCleanupTimeout=null}static isSupported(){return"undefined"!=typeof navigator&&void 0!==navigator.bluetooth&&"function"==typeof navigator.bluetooth.requestDevice}requestDevice(e){return a(this,null,function*(){if(!E.isSupported())throw new l.B(l.z.PLATFORM_NOT_SUPPORTED,"Web Bluetooth API is not supported in this browser");this.logger.debug("Requesting Bluetooth device");try{const t=this.buildRequestOptions(e),i=yield navigator.bluetooth.requestDevice(t);return this.logger.info("Device selected:",i.name||i.id),i}catch(t){const e=l.C(t).message;if(e.includes("cancelled")||e.includes("canceled"))throw new l.B(l.z.CONNECTION_FAILED,"User cancelled device selection");if(e.includes("permission")||e.includes("denied"))throw new l.B(l.z.CONNECTION_FAILED,"Bluetooth permission denied");throw new l.B(l.z.CONNECTION_FAILED,"Failed to request Bluetooth device",l.C(t))}})}connect(e){return a(this,null,function*(){var t;if(this.validateDeviceId(e),this.devices.has(e)){const t=this.devices.get(e);if(null==t?void 0:t.server.connected)return this.logger.warn("Device already connected:",e),void this.updateState(l.P.CONNECTED);this.cleanupDeviceInfo(e)}this.updateState(l.P.CONNECTING),this.logger.debug("Connecting to device:",e);try{const n=yield this.getOrRequestDevice(e);if(!n.gatt)throw new l.B(l.z.CONNECTION_FAILED,"Device does not support GATT");const r=yield this.connectWithTimeout(n.gatt,1e4);this.logger.info("GATT server connected");const s=yield this.discoverWriteableCharacteristic(r);let c;try{const e=s.service.device;"readRemoteRssi"in e&&"function"==typeof e.readRemoteRssi&&(c=yield e.readRemoteRssi())}catch(i){this.logger.debug("RSSI reading not supported on this device")}const o={device:n,server:r,characteristic:s,discoveredAt:Date.now()};void 0!==c&&(o.rssiAtConnection=c),this.devices.set(e,o),this.serviceCache.set(e,{serviceId:(null==(t=s.service)?void 0:t.uuid)||"",characteristicId:s.uuid}),n.addEventListener("gattserverdisconnected",()=>{this.handleDisconnection(e)},{once:!0}),this.updateState(l.P.CONNECTED),this.logger.info("Device connected successfully")}catch(n){if(this.updateState(l.P.DISCONNECTED),this.logger.error("Connection failed:",n),n instanceof l.B)throw n;if(l.C(n).message.includes("timeout"))throw new l.B(l.z.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,l.C(n));throw new l.B(l.z.CONNECTION_FAILED,"Failed to connect to device "+e,l.C(n))}})}disconnect(e){return a(this,null,function*(){var t;yield Promise.resolve(),this.validateDeviceId(e);const i=this.devices.get(e);if(i){this.updateState(l.P.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null),(null==(t=null==i?void 0:i.server)?void 0:t.connected)&&(i.server.disconnect(),this.logger.debug("GATT server disconnected"))}catch(n){this.logger.warn("Disconnect error:",n)}finally{this.cleanupDeviceInfo(e),this.updateState(l.P.DISCONNECTED),this.logger.info("Device disconnected successfully")}}else this.logger.debug("Device not found in cache, nothing to disconnect")})}write(e,t,i){return a(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const n=this.devices.get(e);if(!n)throw new l.B(l.z.DEVICE_DISCONNECTED,"Device not connected. Call connect() first.");if(!n.server.connected)throw this.cleanupDeviceInfo(e),new l.B(l.z.DEVICE_DISCONNECTED,"Device disconnected");const r=this.validateOptions(i),{chunkSize:s,delay:c,retries:o}=r,a=new Uint8Array(t),u=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${u} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),r=Math.floor(t/s)+1;let d=0;for(;o>=d;)try{if(!n.server.connected)throw this.cleanupDeviceInfo(e),new l.B(l.z.DEVICE_DISCONNECTED,"Device disconnected");yield n.characteristic.writeValueWithoutResponse(i.buffer),this.logger.debug(`Chunk ${r}/${u} written successfully`);break}catch(h){if(d++,d>o)throw this.logger.error(`Chunk ${r} failed after ${o} retries`),new l.B(l.z.WRITE_FAILED,`Failed to write chunk ${r}/${u}`,l.C(h));this.logger.warn(`Chunk ${r} write failed, retry ${d}/${o}`),yield new Promise(e=>setTimeout(e,c*d))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,c)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}getDeviceId(e){if(!e)throw new l.B(l.z.DEVICE_NOT_FOUND,"Device is required");return e.id||this.generateFallbackDeviceId(e)}getDeviceInfo(e){const t=this.devices.get(e);if(!t)return null;const i={deviceId:e,name:t.device.name||"Unknown Device",connected:t.server.connected};return void 0!==t.rssiAtConnection&&(i.rssi=t.rssiAtConnection),i}filterDevices(e,t){return e.filter(e=>{if(void 0!==t.minRSSI&&(void 0===e.rssi||e.rssi<t.minRSSI))return!1;if(void 0!==t.maxRSSI&&(void 0===e.rssi||e.rssi>t.maxRSSI))return!1;if(t.namePrefix&&!e.name.toLowerCase().startsWith(t.namePrefix.toLowerCase()))return!1;if(t.name){const i=t.name.toLowerCase();if(!e.name.toLowerCase().includes(i))return!1}if(t.serviceUUIDs&&t.serviceUUIDs.length>0){const i=e.device,n=Array.from(i.uuids||[]);if(!t.serviceUUIDs.some(e=>n.some(t=>t.toLowerCase()===e.toLowerCase())))return!1}return!0})}sortByRSSI(e,t=!1){return[...e].sort((e,i)=>{var n,r;const s=null!=(n=e.rssi)?n:-1/0,c=null!=(r=i.rssi)?r:-1/0;return t?s-c:c-s})}buildRequestOptions(e){var t,i;const n=[];if(null==e?void 0:e.acceptAllDevices)return{acceptAllDevices:!0,optionalServices:e.optionalServices||w};if((null==(t=null==e?void 0:e.serviceUUIDs)?void 0:t.length)&&n.push({services:e.serviceUUIDs}),(null==e?void 0:e.namePrefix)&&n.push({namePrefix:e.namePrefix}),(null==e?void 0:e.name)&&n.push({name:e.name}),null==(i=null==e?void 0:e.manufacturerDataFilter)?void 0:i.length)for(const r of e.manufacturerDataFilter){const e={manufacturerData:[{companyIdentifier:r.companyIdentifier}]};n.push(e)}return 0===n.length?{acceptAllDevices:!0,optionalServices:(null==e?void 0:e.optionalServices)||w}:{filters:n,optionalServices:(null==e?void 0:e.optionalServices)||w}}getOrRequestDevice(e){return a(this,null,function*(){const t=this.devices.get(e);if(null==t?void 0:t.device)return t.device;const i=this.discoveredDevices.get(e);return(null==i?void 0:i.device)?i.device:this.requestDevice()})}connectWithTimeout(e,t){return a(this,null,function*(){return new Promise((i,n)=>{const r=setTimeout(()=>{n(Error("Connection timeout"))},t);e.connect().then(e=>{clearTimeout(r),i(e)}).catch(e=>{clearTimeout(r),n(l.C(e))})})})}discoverWriteableCharacteristic(e){return a(this,null,function*(){this.logger.debug("Discovering services");try{const i=yield e.getPrimaryServices();for(const e of i)try{const t=yield e.getCharacteristics();for(const i of t)if(i.properties.write||i.properties.writeWithoutResponse)return this.logger.info("Found writeable characteristic:",{service:e.uuid,characteristic:i.uuid}),i}catch(t){this.logger.debug(`Failed to get characteristics for service ${e.uuid}:`,t)}throw new l.B(l.z.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof l.B)throw t;throw new l.B(l.z.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",l.C(t))}})}handleDisconnection(e){this.logger.warn("Device disconnected unexpectedly:",e),this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null),this.cleanupDeviceInfo(e),this.updateState(l.P.DISCONNECTED)}cleanupDeviceInfo(e){this.devices.delete(e),this.cleanupDevice(e)}generateFallbackDeviceId(e){return`fallback_${e.name||"unknown"}_${Date.now().toString(36)}`}destroy(){this.logger.debug("Destroying WebBluetoothAdapter"),this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null);for(const[t,i]of this.devices)try{i.server.connected&&i.server.disconnect()}catch(e){this.logger.warn(`Error disconnecting device ${t}:`,e)}this.devices.clear(),this.discoveredDevices.clear(),super.destroy(),this.logger.info("WebBluetoothAdapter destroyed")}}const y=Object.freeze(Object.defineProperty({__proto__:null,WebBluetoothAdapter:E},Symbol.toStringTag,{value:"Module"}));exports.A=class{static create(){return this.createForPlatform(l.D())}static createForPlatform(e){switch(e){case l.F.WECHAT:return new C;case l.F.ALIPAY:return new D;case l.F.BAIDU:return new p;case l.F.BYTEDANCE:return new m;case l.F.QQ:return new I;case l.F.WEB:if(E.isSupported())return new E;throw new l.B(l.z.PLATFORM_NOT_SUPPORTED,"Web Bluetooth API is not supported in this browser. Please use a supported browser (Chrome, Edge, Opera).");default:throw new l.B(l.z.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}},exports.B=g,exports.C=d,exports.D=u,exports.M=f,exports.Q=I,exports.T=C,exports.W=E,exports.a=D,exports.b=p,exports.c=m,exports.d=y;
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,c=(t,i,n)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,o=(e,t)=>{for(var i in t||(t={}))r.call(t,i)&&c(e,i,t[i]);if(n)for(var i of n(t))s.call(t,i)&&c(e,i,t[i]);return e},a=(e,t,i)=>new Promise((n,r)=>{var s=e=>{try{o(i.next(e))}catch(t){r(t)}},c=e=>{try{o(i.throw(e))}catch(t){r(t)}},o=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,c);o((i=i.apply(e,t)).next())});import{L as l,B as u,z as h,C as d,P as v,A as f,D as g,F as C}from"./shared-DuaS72fL.js";const D={defaultChunkSize:50,defaultDelay:20,defaultRetries:3,minChunkSize:10,maxChunkSize:256,maxDelay:200,successThreshold:3,failureThreshold:2,connectionCheckInterval:10},p=class e{constructor(e,t={}){this.logger=l.scope(e),this.config=o(o({},D),t)}checkConnection(e){return a(this,null,function*(){})}computeTimeoutMs(t){return Math.max(e.TIMEOUT_BASE_MS,Math.min(e.TIMEOUT_MAX_MS,e.TIMEOUT_BASE_MS+t*e.TIMEOUT_PER_BYTE_MS))}getMaxChunkSize(e){return this.config.maxChunkSize}execute(e,t){return a(this,arguments,function*(e,t,i={},n){const r=new Uint8Array(e);if(0===r.length)return void this.logger.warn("No data to write");const s=this.initializeTransmissionParams(r,i),c=this.getMaxChunkSize(t.deviceId),o={successCount:0,consecutiveFailures:0,currentChunkSize:s.chunkSize,baseDelay:s.delay};this.logger.debug(`Writing ${r.length} bytes with initial chunkSize=${o.currentChunkSize}, delay=${o.baseDelay}ms`);for(let a=0;a<r.length;a+=o.currentChunkSize){yield this.maybeCheckConnection(a,o.currentChunkSize,t.deviceId);const e=Math.floor(a/o.currentChunkSize)+1,i=yield this.writeChunkWithRetries(r,a,o.currentChunkSize,t,e,s.retries,o.baseDelay,n);if(!i)return;this.adjustTransmissionParams(o,i,c,s.minChunkSize,s.maxDelay,s.successThreshold,s.failureThreshold,e,a,r.length),yield this.maybeDelay(a,o.currentChunkSize,r.length,o.baseDelay)}this.logger.info(`Successfully wrote ${r.length} bytes`)})}initializeTransmissionParams(e,t){var i,n,r;return{chunkSize:Math.max(1,Math.min(256,null!=(i=t.chunkSize)?i:this.config.defaultChunkSize)),delay:Math.max(10,Math.min(100,null!=(n=t.delay)?n:this.config.defaultDelay)),retries:Math.max(1,Math.min(10,null!=(r=t.retries)?r:this.config.defaultRetries)),minChunkSize:this.config.minChunkSize,maxDelay:this.config.maxDelay,successThreshold:this.config.successThreshold,failureThreshold:this.config.failureThreshold}}maybeCheckConnection(e,t,i){return a(this,null,function*(){e>0&&Math.floor(e/t)%this.config.connectionCheckInterval===0&&(yield this.checkConnection(i))})}writeChunkWithRetries(e,t,i,n,r,s,c,o){return a(this,null,function*(){var a;const l=e.slice(t,t+i),d=Math.ceil(e.length/i);for(let e=0;s>=e;e++){const t=yield this.writeSingleChunk(l,n,o);if(t.success)return this.logger.debug(`Chunk ${r}/${d} written successfully`),!0;if(e>=s)throw this.logger.error(`Chunk ${r} failed after ${s} retries`),new u(h.WRITE_FAILED,`Failed to write chunk ${r}/${d}`,null!=(a=t.error)?a:Error("Unknown write error"));this.logger.warn(`Chunk ${r} write failed, retry ${e+1}/${s}`);const i=c*Math.pow(2,e);yield new Promise(e=>setTimeout(e,Math.min(i,this.config.maxDelay)))}return!1})}adjustTransmissionParams(t,i,n,r,s,c,o,a,l,u){i?(t.successCount++,t.consecutiveFailures=0,t.successCount%c===0&&t.currentChunkSize<n&&(t.currentChunkSize=Math.min(n,t.currentChunkSize+e.CHUNK_SIZE_STEP),t.baseDelay=Math.max(t.baseDelay/e.DELAY_RECOVERY_FACTOR,this.config.defaultDelay),this.logger.debug(`Increased chunk size to ${t.currentChunkSize}, delay to ${t.baseDelay}ms`))):(t.consecutiveFailures++,t.consecutiveFailures>=o&&t.currentChunkSize>r&&(t.currentChunkSize=Math.max(r,t.currentChunkSize-e.CHUNK_SIZE_STEP),t.baseDelay=Math.min(t.baseDelay*e.DELAY_BACKOFF_FACTOR,s),this.logger.debug(`Decreased chunk size to ${t.currentChunkSize}, delay to ${t.baseDelay}ms`),t.consecutiveFailures=0))}maybeDelay(e,t,i,n){return a(this,null,function*(){i>e+t&&(yield new Promise(e=>setTimeout(e,n)))})}};p.CHUNK_SIZE_STEP=5,p.DELAY_BACKOFF_FACTOR=1.5,p.DELAY_RECOVERY_FACTOR=1.2,p.TIMEOUT_BASE_MS=1e3,p.TIMEOUT_PER_BYTE_MS=5,p.TIMEOUT_MAX_MS=1e4;let m=p;class I extends m{constructor(e){var n;super("MiniProgramAdapter",(n=o({},D),t(n,i({connectionCheckInterval:5})))),this.api=e}writeSingleChunk(e,t){return a(this,null,function*(){const i=this.computeTimeoutMs(e.length);try{const n=this.api.writeBLECharacteristicValue({deviceId:t.deviceId,serviceId:t.serviceId,characteristicId:t.characteristicId,value:e.buffer});let r;const s=new Promise((e,t)=>{r=setTimeout(()=>{t(Error(`Write timeout after ${i}ms`))},i)});return yield Promise.race([n,s]),r&&clearTimeout(r),{success:!0}}catch(n){return{success:!1,error:d(n)}}})}checkConnection(e){return a(this,null,function*(){try{if(!(yield this.api.getBLEConnectionState({deviceId:e})).connected)throw new u(h.DEVICE_DISCONNECTED,"Device disconnected")}catch(t){if(t instanceof u)throw t;throw new u(h.DEVICE_DISCONNECTED,"Device disconnected",d(t))}})}}class w{constructor(){this.serviceCache=/* @__PURE__ */new Map,this.logger=l.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new u(h.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new u(h.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,n;return{chunkSize:Math.max(1,Math.min(256,null!=(t=null==e?void 0:e.chunkSize)?t:20)),delay:Math.max(10,Math.min(100,null!=(i=null==e?void 0:e.delay)?i:20)),retries:Math.max(1,Math.min(10,null!=(n=null==e?void 0:e.retries)?n:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new u(h.SERVICE_NOT_FOUND,"Device not connected or services not discovered. Call connect() first.");return t}isDeviceConnected(e){return this.serviceCache.has(e)}cleanupDevice(e){this.serviceCache.delete(e)}classifyConnectionError(e,t){const i=d(e).message;return i.includes("timeout")?new u(h.CONNECTION_TIMEOUT,`Connection to device ${t} timed out`,d(e)):i.includes("not found")||i.includes("not exist")?new u(h.DEVICE_NOT_FOUND,`Device ${t} not found`,d(e)):new u(h.CONNECTION_FAILED,"Failed to connect to device "+t,d(e))}discoverAndCacheServices(e,t){return a(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const i=yield t();for(const t of i){const i=t.characteristics.find(e=>e.isWritable);if(i)return this.serviceCache.set(e,{serviceId:t.serviceId,characteristicId:i.characteristicId}),void this.logger.info("Found writeable characteristic:",{service:t.serviceId,characteristic:i.characteristicId})}throw new u(h.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(i){if(i instanceof u)throw i;throw new u(h.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",d(i))}})}destroy(){this.logger.debug("Destroying BaseAdapter"),this.serviceCache.clear(),this.stateCallback=void 0}}class E extends w{constructor(){super(...arguments),this.writeStrategy=null}getWriteStrategy(){return this.writeStrategy||(this.writeStrategy=new I(this.getApi())),this.writeStrategy}connect(e){return a(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(v.CONNECTED);this.updateState(v.CONNECTING),this.logger.debug("Connecting to device:",e);try{yield f(this.getApi().createBLEConnection({deviceId:e}),1e4,"Connection timeout after 10 seconds"),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(v.CONNECTED),this.logger.info("Device connected successfully"),this.getApi().onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(v.DISCONNECTED),this.cleanupDevice(e))})}catch(t){throw this.updateState(v.DISCONNECTED),this.logger.error("Connection failed:",t),this.classifyConnectionError(t,e)}})}finalizeDisconnect(e){this.cleanupDevice(e),this.updateState(v.DISCONNECTED),this.logger.info("Device disconnected successfully")}disconnect(e){return a(this,null,function*(){this.validateDeviceId(e),this.updateState(v.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield this.getApi().closeBLEConnection({deviceId:e}),this.finalizeDisconnect(e)}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.finalizeDisconnect(e)}})}write(e,t,i){return a(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const n=this.getServiceInfo(e);yield this.getWriteStrategy().execute(t,{deviceId:e,serviceId:n.serviceId,characteristicId:n.characteristicId},null!=i?i:{})})}discoverServices(e){return a(this,null,function*(){yield this.discoverAndCacheServices(e,()=>a(this,null,function*(){const t=yield this.getApi().getBLEDeviceServices({deviceId:e}),i=[];for(const n of t.services){const t=yield this.getApi().getBLEDeviceCharacteristics({deviceId:e,serviceId:n.uuid});i.push({serviceId:n.uuid,characteristics:t.characteristics.map(e=>({characteristicId:e.uuid,isWritable:!(!e.properties.write&&!e.properties.writeWithoutResponse)}))})}return i}))})}}class y extends E{getApi(){return Taro}}class S extends E{getApi(){return my}}class T extends E{getApi(){return swan}}class O extends E{getApi(){return tt}}class N extends E{getApi(){return qq}}const b=["000018f0-0000-1000-8000-00805f9b34fb","49535343-fe7d-4ae5-8fa9-9fafd205e455","e7810a71-73ae-499d-8c15-faa9aef0c3f2"];class A extends w{constructor(){super(...arguments),this.devices=/* @__PURE__ */new Map,this.discoveredDevices=/* @__PURE__ */new Map,this.connectionCleanupTimeout=null}static isSupported(){return"undefined"!=typeof navigator&&void 0!==navigator.bluetooth&&"function"==typeof navigator.bluetooth.requestDevice}requestDevice(e){return a(this,null,function*(){if(!A.isSupported())throw new u(h.PLATFORM_NOT_SUPPORTED,"Web Bluetooth API is not supported in this browser");this.logger.debug("Requesting Bluetooth device");try{const t=this.buildRequestOptions(e),i=yield navigator.bluetooth.requestDevice(t);return this.logger.info("Device selected:",i.name||i.id),i}catch(t){const e=d(t).message;if(e.includes("cancelled")||e.includes("canceled"))throw new u(h.CONNECTION_FAILED,"User cancelled device selection");if(e.includes("permission")||e.includes("denied"))throw new u(h.CONNECTION_FAILED,"Bluetooth permission denied");throw new u(h.CONNECTION_FAILED,"Failed to request Bluetooth device",d(t))}})}connect(e){return a(this,null,function*(){var t;if(this.validateDeviceId(e),this.devices.has(e)){const t=this.devices.get(e);if(null==t?void 0:t.server.connected)return this.logger.warn("Device already connected:",e),void this.updateState(v.CONNECTED);this.cleanupDeviceInfo(e)}this.updateState(v.CONNECTING),this.logger.debug("Connecting to device:",e);try{const n=yield this.getOrRequestDevice(e);if(!n.gatt)throw new u(h.CONNECTION_FAILED,"Device does not support GATT");const r=yield this.connectWithTimeout(n.gatt,1e4);this.logger.info("GATT server connected");const s=yield this.discoverWriteableCharacteristic(r);let c;try{const e=s.service.device;"readRemoteRssi"in e&&"function"==typeof e.readRemoteRssi&&(c=yield e.readRemoteRssi())}catch(i){this.logger.debug("RSSI reading not supported on this device")}const o={device:n,server:r,characteristic:s,discoveredAt:Date.now()};void 0!==c&&(o.rssiAtConnection=c),this.devices.set(e,o),this.serviceCache.set(e,{serviceId:(null==(t=s.service)?void 0:t.uuid)||"",characteristicId:s.uuid}),n.addEventListener("gattserverdisconnected",()=>{this.handleDisconnection(e)},{once:!0}),this.updateState(v.CONNECTED),this.logger.info("Device connected successfully")}catch(n){if(this.updateState(v.DISCONNECTED),this.logger.error("Connection failed:",n),n instanceof u)throw n;if(d(n).message.includes("timeout"))throw new u(h.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,d(n));throw new u(h.CONNECTION_FAILED,"Failed to connect to device "+e,d(n))}})}disconnect(e){return a(this,null,function*(){var t;yield Promise.resolve(),this.validateDeviceId(e);const i=this.devices.get(e);if(i){this.updateState(v.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null),(null==(t=null==i?void 0:i.server)?void 0:t.connected)&&(i.server.disconnect(),this.logger.debug("GATT server disconnected"))}catch(n){this.logger.warn("Disconnect error:",n)}finally{this.cleanupDeviceInfo(e),this.updateState(v.DISCONNECTED),this.logger.info("Device disconnected successfully")}}else this.logger.debug("Device not found in cache, nothing to disconnect")})}write(e,t,i){return a(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const n=this.devices.get(e);if(!n)throw new u(h.DEVICE_DISCONNECTED,"Device not connected. Call connect() first.");if(!n.server.connected)throw this.cleanupDeviceInfo(e),new u(h.DEVICE_DISCONNECTED,"Device disconnected");const r=this.validateOptions(i),{chunkSize:s,delay:c,retries:o}=r,a=new Uint8Array(t),l=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${l} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),r=Math.floor(t/s)+1;let f=0;for(;o>=f;)try{if(!n.server.connected)throw this.cleanupDeviceInfo(e),new u(h.DEVICE_DISCONNECTED,"Device disconnected");yield n.characteristic.writeValueWithoutResponse(i.buffer),this.logger.debug(`Chunk ${r}/${l} written successfully`);break}catch(v){if(f++,f>o)throw this.logger.error(`Chunk ${r} failed after ${o} retries`),new u(h.WRITE_FAILED,`Failed to write chunk ${r}/${l}`,d(v));this.logger.warn(`Chunk ${r} write failed, retry ${f}/${o}`),yield new Promise(e=>setTimeout(e,c*f))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,c)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}getDeviceId(e){if(!e)throw new u(h.DEVICE_NOT_FOUND,"Device is required");return e.id||this.generateFallbackDeviceId(e)}getDeviceInfo(e){const t=this.devices.get(e);if(!t)return null;const i={deviceId:e,name:t.device.name||"Unknown Device",connected:t.server.connected};return void 0!==t.rssiAtConnection&&(i.rssi=t.rssiAtConnection),i}filterDevices(e,t){return e.filter(e=>{if(void 0!==t.minRSSI&&(void 0===e.rssi||e.rssi<t.minRSSI))return!1;if(void 0!==t.maxRSSI&&(void 0===e.rssi||e.rssi>t.maxRSSI))return!1;if(t.namePrefix&&!e.name.toLowerCase().startsWith(t.namePrefix.toLowerCase()))return!1;if(t.name){const i=t.name.toLowerCase();if(!e.name.toLowerCase().includes(i))return!1}if(t.serviceUUIDs&&t.serviceUUIDs.length>0){const i=e.device,n=Array.from(i.uuids||[]);if(!t.serviceUUIDs.some(e=>n.some(t=>t.toLowerCase()===e.toLowerCase())))return!1}return!0})}sortByRSSI(e,t=!1){return[...e].sort((e,i)=>{var n,r;const s=null!=(n=e.rssi)?n:-1/0,c=null!=(r=i.rssi)?r:-1/0;return t?s-c:c-s})}buildRequestOptions(e){var t,i;const n=[];if(null==e?void 0:e.acceptAllDevices)return{acceptAllDevices:!0,optionalServices:e.optionalServices||b};if((null==(t=null==e?void 0:e.serviceUUIDs)?void 0:t.length)&&n.push({services:e.serviceUUIDs}),(null==e?void 0:e.namePrefix)&&n.push({namePrefix:e.namePrefix}),(null==e?void 0:e.name)&&n.push({name:e.name}),null==(i=null==e?void 0:e.manufacturerDataFilter)?void 0:i.length)for(const r of e.manufacturerDataFilter){const e={manufacturerData:[{companyIdentifier:r.companyIdentifier}]};n.push(e)}return 0===n.length?{acceptAllDevices:!0,optionalServices:(null==e?void 0:e.optionalServices)||b}:{filters:n,optionalServices:(null==e?void 0:e.optionalServices)||b}}getOrRequestDevice(e){return a(this,null,function*(){const t=this.devices.get(e);if(null==t?void 0:t.device)return t.device;const i=this.discoveredDevices.get(e);return(null==i?void 0:i.device)?i.device:this.requestDevice()})}connectWithTimeout(e,t){return a(this,null,function*(){return new Promise((i,n)=>{const r=setTimeout(()=>{n(Error("Connection timeout"))},t);e.connect().then(e=>{clearTimeout(r),i(e)}).catch(e=>{clearTimeout(r),n(d(e))})})})}discoverWriteableCharacteristic(e){return a(this,null,function*(){this.logger.debug("Discovering services");try{const i=yield e.getPrimaryServices();for(const e of i)try{const t=yield e.getCharacteristics();for(const i of t)if(i.properties.write||i.properties.writeWithoutResponse)return this.logger.info("Found writeable characteristic:",{service:e.uuid,characteristic:i.uuid}),i}catch(t){this.logger.debug(`Failed to get characteristics for service ${e.uuid}:`,t)}throw new u(h.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof u)throw t;throw new u(h.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",d(t))}})}handleDisconnection(e){this.logger.warn("Device disconnected unexpectedly:",e),this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null),this.cleanupDeviceInfo(e),this.updateState(v.DISCONNECTED)}cleanupDeviceInfo(e){this.devices.delete(e),this.cleanupDevice(e)}generateFallbackDeviceId(e){return`fallback_${e.name||"unknown"}_${Date.now().toString(36)}`}destroy(){this.logger.debug("Destroying WebBluetoothAdapter"),this.connectionCleanupTimeout&&(clearTimeout(this.connectionCleanupTimeout),this.connectionCleanupTimeout=null);for(const[t,i]of this.devices)try{i.server.connected&&i.server.disconnect()}catch(e){this.logger.warn(`Error disconnecting device ${t}:`,e)}this.devices.clear(),this.discoveredDevices.clear(),super.destroy(),this.logger.info("WebBluetoothAdapter destroyed")}}const _=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,WebBluetoothAdapter:A},Symbol.toStringTag,{value:"Module"}));class k{static create(){return this.createForPlatform(g())}static createForPlatform(e){switch(e){case C.WECHAT:return new y;case C.ALIPAY:return new S;case C.BAIDU:return new T;case C.BYTEDANCE:return new O;case C.QQ:return new N;case C.WEB:if(A.isSupported())return new A;throw new u(h.PLATFORM_NOT_SUPPORTED,"Web Bluetooth API is not supported in this browser. Please use a supported browser (Chrome, Edge, Opera).");default:throw new u(h.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}}export{k as A,w as B,m as C,D,E as M,N as Q,y as T,A as W,S as a,T as b,O as c,_ as d};
@@ -0,0 +1 @@
1
+ "use strict";const n=require("./shared-C3EQK7YH.js");exports.E=class{constructor(e){var r,t,i;this.logger=n.L.scope("EscPos"),this.useEncodingService=null==(r=null==e?void 0:e.useEncodingService)||r,this.encodingService=new n.E({showWarnings:null==(t=null==e?void 0:e.showEncodingWarnings)||t,fallbackChar:null!=(i=null==e?void 0:e.fallbackChar)?i:"?"})}init(){return[new Uint8Array([27,64])]}encodeText(e,r){return this.useEncodingService&&this.encodingService.isSupported(r)?this.encodingService.encode(e,r):n.x.encode(e,r)}text(n,e="GBK"){return n&&"string"==typeof n?[this.encodeText(n,e)]:[]}feed(n=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(n)))])]}cut(){return[new Uint8Array([29,86,0])]}image(e,r,t){if(!(e&&e instanceof Uint8Array&&r>0&&t>0))return[];if(e.length!==r*t*4)return this.logger.warn(`Invalid image data length: expected ${r*t*4}, got ${e.length}`),[];const i=n.y.toBitmap(e,r,t),o=Math.ceil(r/8);return[new Uint8Array([29,118,48,0,o%256,Math.floor(o/256),t%256,Math.floor(t/256)]),i]}qr(n,e){var r,t,i,o;if(!n||"string"!=typeof n)return[];const a=null!=(r=null==e?void 0:e.model)?r:2,s=Math.max(1,Math.min(16,null!=(t=null==e?void 0:e.size)?t:6)),l=null!=(i=null==e?void 0:e.errorCorrection)?i:"M",u=[];u.push(new Uint8Array([29,40,107,4,0,49,65,1===a?49:50,0])),u.push(new Uint8Array([29,40,107,3,0,49,67,s]));const c=null!=(o={L:48,M:49,Q:50,H:51}[l])?o:49;u.push(new Uint8Array([29,40,107,3,0,49,69,c]));const h=this.encodeText(n,"GBK"),d=h.length+3,g=d%256,w=Math.floor(d/256);return u.push(new Uint8Array([29,40,107,g,w,49,80,48])),u.push(h),u.push(new Uint8Array([29,40,107,3,0,49,81,48])),u}openCashDrawer(n=0){return[new Uint8Array([27,112,n,50,200])]}beep(n=3,e=50){return[new Uint8Array([27,66,n,e])]}selfTest(){return[new Uint8Array([27,105])]}getStatus(){const n=[];for(let e=1;4>=e;e++)n.push(new Uint8Array([16,4,e]));return n}setCodePage(n){return[new Uint8Array([27,116,n])]}setLeftMargin(n){return[new Uint8Array([27,108,n])]}setPrintWidth(n){return[new Uint8Array([27,87,n])]}};
@@ -0,0 +1 @@
1
+ import{L as n,E as r,x as e,y as t}from"./shared-DuaS72fL.js";class i{constructor(e){var t,i,a;this.logger=n.scope("EscPos"),this.useEncodingService=null==(t=null==e?void 0:e.useEncodingService)||t,this.encodingService=new r({showWarnings:null==(i=null==e?void 0:e.showEncodingWarnings)||i,fallbackChar:null!=(a=null==e?void 0:e.fallbackChar)?a:"?"})}init(){return[new Uint8Array([27,64])]}encodeText(n,r){return this.useEncodingService&&this.encodingService.isSupported(r)?this.encodingService.encode(n,r):e.encode(n,r)}text(n,r="GBK"){return n&&"string"==typeof n?[this.encodeText(n,r)]:[]}feed(n=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(n)))])]}cut(){return[new Uint8Array([29,86,0])]}image(n,r,e){if(!(n&&n instanceof Uint8Array&&r>0&&e>0))return[];if(n.length!==r*e*4)return this.logger.warn(`Invalid image data length: expected ${r*e*4}, got ${n.length}`),[];const i=t.toBitmap(n,r,e),a=Math.ceil(r/8);return[new Uint8Array([29,118,48,0,a%256,Math.floor(a/256),e%256,Math.floor(e/256)]),i]}qr(n,r){var e,t,i,a;if(!n||"string"!=typeof n)return[];const o=null!=(e=null==r?void 0:r.model)?e:2,s=Math.max(1,Math.min(16,null!=(t=null==r?void 0:r.size)?t:6)),l=null!=(i=null==r?void 0:r.errorCorrection)?i:"M",u=[];u.push(new Uint8Array([29,40,107,4,0,49,65,1===o?49:50,0])),u.push(new Uint8Array([29,40,107,3,0,49,67,s]));const h=null!=(a={L:48,M:49,Q:50,H:51}[l])?a:49;u.push(new Uint8Array([29,40,107,3,0,49,69,h]));const c=this.encodeText(n,"GBK"),d=c.length+3,g=d%256,w=Math.floor(d/256);return u.push(new Uint8Array([29,40,107,g,w,49,80,48])),u.push(c),u.push(new Uint8Array([29,40,107,3,0,49,81,48])),u}openCashDrawer(n=0){return[new Uint8Array([27,112,n,50,200])]}beep(n=3,r=50){return[new Uint8Array([27,66,n,r])]}selfTest(){return[new Uint8Array([27,105])]}getStatus(){const n=[];for(let r=1;4>=r;r++)n.push(new Uint8Array([16,4,r]));return n}setCodePage(n){return[new Uint8Array([27,116,n])]}setLeftMargin(n){return[new Uint8Array([27,108,n])]}setPrintWidth(n){return[new Uint8Array([27,87,n])]}}export{i as E};
@@ -0,0 +1 @@
1
+ "use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,s=(t,n,i)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[n]=i,r=(e,r)=>{for(var o in r||(r={}))n.call(r,o)&&s(e,o,r[o]);if(t)for(var o of t(r))i.call(r,o)&&s(e,o,r[o]);return e},o=(e,t,n)=>new Promise((i,s)=>{var r=e=>{try{a(n.next(e))}catch(t){s(t)}},o=e=>{try{a(n.throw(e))}catch(t){s(t)}},a=e=>e.done?i(e.value):Promise.resolve(e.value).then(r,o);a((n=n.apply(e,t)).next())});const a=require("./shared-C3EQK7YH.js"),h=require("./AdapterFactory-B91w5soC.js"),c=require("./EscPosDriver-Byd1u4Jk.js");class l{constructor(){this.listeners={},this.debugMode=!1,this.logger=a.L.scope("EventEmitter")}ensureListeners(e){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e]}on(e,t){return this.ensureListeners(e).add(t),this.debugMode&&this.logger.debug(`EventEmitter: Added listener for "${e+""}"`,{listenerCount:this.listenerCount(e)}),()=>this.off(e,t)}once(e,t){const n=this.wrapOnceHandler(e,t);return this.on(e,n)}prepend(e,t){const n=this.ensureListeners(e),i=new Set;return i.add(t),n.forEach(e=>i.add(e)),this.listeners[e]=i,this.debugMode&&this.logger.debug(`EventEmitter: Prepend listener for "${e+""}"`,{listenerCount:this.listenerCount(e)}),()=>this.off(e,t)}prependOnce(e,t){const n=this.wrapOnceHandler(e,t);return this.prepend(e,n)}wrapOnceHandler(e,t){const n=i=>{t(i),this.off(e,n)};return n}off(e,t){const n=this.listeners[e];n&&(n.delete(t),this.debugMode&&this.logger.debug(`EventEmitter: Removed listener for "${e+""}"`,{listenerCount:n.size}),0===n.size&&(delete this.listeners[e],this.debugMode&&this.logger.debug(`EventEmitter: Removed event "${e+""}" (no more listeners)`)))}getHandlers(e){var t;return null!=(t=this.listeners[e])?t:new Set}emit(e,...t){const n=t[0],i=this.getHandlers(e);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting "${e+""}"`,{data:n,listenerCount:i.size}),0!==i.size)for(const r of i)if("function"==typeof r)try{r(n)}catch(s){this.logger.error(`Error in event handler for "${e+""}":`,s)}}emitAsync(e,...t){return o(this,null,function*(){const n=t[0],i=this.getHandlers(e);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting async "${e+""}"`,{data:n,listenerCount:i.size}),0===i.size)return;const s=[];i.forEach(t=>{s.push((()=>o(this,null,function*(){try{const e=t(n);null!=e&&"function"==typeof e.then&&(yield e)}catch(i){this.logger.error(`Error in event handler for "${e+""}":`,i)}}))())}),yield Promise.all(s),this.debugMode&&this.logger.debug(`EventEmitter: Finished emitting async "${e+""}"`)})}removeAllListeners(e){if(e){const t=this.listenerCount(e);delete this.listeners[e],this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${t} listeners for "${e+""}"`)}else{const e=Object.keys(this.listeners).length;this.listeners={},this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${e} events and their listeners`)}}listenerCount(e){var t,n;return null!=(n=null==(t=this.listeners[e])?void 0:t.size)?n:0}getListeners(e){const t=this.listeners[e];return t?Array.from(t):[]}eventNames(){return Object.keys(this.listeners)}hasListeners(e){return this.listenerCount(e)>0}setDebugMode(e){this.debugMode=e,this.logger.debug("EventEmitter: Debug mode "+(e?"enabled":"disabled"))}isDebugMode(){return this.debugMode}getTotalEvents(){return Object.keys(this.listeners).length}getTotalListeners(){var e,t;let n=0;for(const i of Object.keys(this.listeners))n+=null!=(t=null==(e=this.listeners[i])?void 0:e.size)?t:0;return n}reset(){this.removeAllListeners(),this.debugMode=!1}}const d={heartbeatEnabled:!0,heartbeatInterval:5e3,autoReconnect:!0,maxReconnectAttempts:3,reconnectInterval:2e3,connectionTimeout:1e4};class u extends l{constructor(e,t){var n,i;super(),this.deviceId=null,this.state=a.P.DISCONNECTED,this.connLogger=a.L.scope("ConnectionManager"),this.heartbeatTimer=null,this.reconnectAttempts=0,this.isReconnecting=!1,this.reconnectTimer=null,this.adapter=e||h.A.create(),this.config=r(r({},d),t),null==(i=(n=this.adapter).onStateChange)||i.call(n,e=>{this.handleStateChange(e)})}handleStateChange(e){const t=this.state;this.state=e,this.connLogger.debug("State changed:",{from:t,to:e}),this.emit("state-change",e),t===a.P.CONNECTED&&e===a.P.DISCONNECTED&&this.deviceId&&!this.isReconnecting&&(this.connLogger.warn("Unexpected disconnection detected"),this.emit("disconnected",this.deviceId),this.stopHeartbeat(),this.config.autoReconnect&&this.startReconnect())}connect(e,t){return o(this,null,function*(){this.connLogger.info("Connecting to device:",e);const{retries:n=0,timeout:i=this.config.connectionTimeout}=t||{};let s=0;for(this.reconnectAttempts=0,this.isReconnecting=!1,this.clearReconnectTimer();n>=s;)try{this.deviceId=e,this.state=a.P.CONNECTING,this.emit("state-change",a.P.CONNECTING);const t=this.adapter.connect(e);return yield a.A(t,i,`Connection to device ${e} timed out`),this.state=a.P.CONNECTED,this.emit("state-change",a.P.CONNECTED),this.emit("connected",e),this.connLogger.info("Connected successfully"),void(this.config.heartbeatEnabled&&this.startHeartbeat())}catch(r){if(s++,s>n){this.deviceId=null,this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED);const t=this.classifyConnectError(r,e,s,i);throw this.connLogger.error("Connection failed:",t),this.emit("error",t),t}this.connLogger.warn(`Connection attempt ${s}/${n} failed, retrying...`,r),yield new Promise(e=>setTimeout(e,1e3))}})}classifyConnectError(e,t,n,i){if(e instanceof a.B)return e;const s=a.C(e).message.toLowerCase();return s.includes("timed out")||s.includes("timeout")?new a.B(a.z.CONNECTION_TIMEOUT,`Connection to device ${t} timed out after ${i}ms`):new a.B(a.z.CONNECTION_FAILED,`Connection failed after ${n} attempts`,a.C(e))}disconnect(){return o(this,null,function*(){if(this.stopHeartbeat(),this.clearReconnectTimer(),this.isReconnecting=!1,!this.deviceId)return void this.connLogger.warn("Disconnect called but no device connected");const e=this.deviceId;this.connLogger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED),this.emit("disconnected",e),this.connLogger.info("Disconnected successfully")}catch(t){const e=new a.B(a.z.DEVICE_DISCONNECTED,"Disconnect failed",a.C(t));throw this.connLogger.error("Disconnect failed:",e),this.emit("error",e),e}})}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.checkHeartbeat()},this.config.heartbeatInterval),this.connLogger.debug("Heartbeat started with interval:",this.config.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.connLogger.debug("Heartbeat stopped"))}checkHeartbeat(){if(this.deviceId&&this.state===a.P.CONNECTED)try{this.isConnected()?this.connLogger.debug("Heartbeat OK"):this.handleHeartbeatLost()}catch(e){this.connLogger.warn("Heartbeat check failed:",e),this.handleHeartbeatLost()}}handleHeartbeatLost(){this.deviceId&&(this.connLogger.warn("Heartbeat lost for device:",this.deviceId),this.emit("heartbeat-lost",this.deviceId),this.stopHeartbeat(),this.state=a.P.DISCONNECTED,this.emit("state-change",a.P.DISCONNECTED),this.emit("disconnected",this.deviceId),this.config.autoReconnect&&!this.isReconnecting&&this.startReconnect())}startReconnect(){this.deviceId&&!this.isReconnecting&&(this.isReconnecting=!0,this.reconnectAttempts=0,this.attemptReconnect())}attemptReconnect(){return o(this,null,function*(){if(!this.deviceId)return void(this.isReconnecting=!1);this.reconnectAttempts++;const e=this.deviceId;if(this.reconnectAttempts>this.config.maxReconnectAttempts)return this.connLogger.error("Max reconnect attempts reached"),this.isReconnecting=!1,this.emit("reconnect-failed",{deviceId:e,error:new a.B(a.z.CONNECTION_FAILED,`Reconnection failed after ${this.config.maxReconnectAttempts} attempts`)}),void(this.deviceId=null);this.connLogger.info(`Reconnect attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts}`),this.emit("reconnecting",{deviceId:e,attempt:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}),this.state=a.P.CONNECTING,this.emit("state-change",a.P.CONNECTING);try{yield this.adapter.connect(e),this.connLogger.info("Reconnected successfully"),this.isReconnecting=!1,this.reconnectAttempts=0,this.state=a.P.CONNECTED,this.emit("state-change",a.P.CONNECTED),this.emit("reconnected",e),this.config.heartbeatEnabled&&this.startHeartbeat()}catch(t){this.connLogger.warn(`Reconnect attempt ${this.reconnectAttempts} failed:`,t);const e=this.config.reconnectInterval,n=Math.min(e*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},n)}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}isConnected(){return this.state===a.P.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}getConfig(){return r({},this.config)}getReconnectStatus(){return{isReconnecting:this.isReconnecting,attempts:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}}reconnect(){if(!this.deviceId)throw new a.B(a.z.DEVICE_NOT_FOUND,"No device to reconnect to");this.isReconnecting?this.connLogger.warn("Reconnect already in progress"):this.startReconnect()}stopReconnect(){this.clearReconnectTimer(),this.isReconnecting=!1,this.reconnectAttempts=0,this.connLogger.info("Reconnect stopped")}destroy(){this.stopHeartbeat(),this.clearReconnectTimer(),this.removeAllListeners(),this.deviceId=null,this.state=a.P.DISCONNECTED}}const g=class e{constructor(e){this.instanceJobStateStore=new Map,this.jobBuffer=null,this.jobOffset=0,this.paused=!1,this.inProgress=!1,this.adapterOptions={},this.jobId=null,this.logger=a.L.scope("PrintJobManager"),this.connectionManager=e,this.adapter="function"==typeof e.getAdapter?e.getAdapter():{connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),write:()=>{throw new a.B(a.z.INVALID_CONFIGURATION,"No adapter available for print job write")}}}setProgressCallback(e){this.onProgress=e}setJobStateCallback(e){this.onJobStateChange=e}wrapError(e,t,n){return e instanceof a.B?e:new a.B(t,n,a.C(e))}start(e,t){return o(this,null,function*(){var n;if(this.inProgress)throw new a.B(a.z.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.jobId=null!=(n=null==t?void 0:t.jobId)?n:this.generateJobId(),this.jobBuffer=e,this.jobOffset=0,this.paused=!1,this.inProgress=!0,this.logger.info(`Starting print job ${this.jobId}: ${e.length} bytes`),this.emitJobState("in-progress");try{yield this.processJob(),this.paused?(this.logger.info(`Print job ${this.jobId} paused`),this.saveJobState()):this.completeJob()}catch(i){throw this.logger.error(`Print job ${this.jobId} failed:`,i),this.inProgress=!1,this.paused?this.saveJobState():this.clearJobState(),this.wrapError(i,a.z.PRINT_JOB_FAILED,"Print job failed")}})}resume(e){return o(this,null,function*(){if(!this.inProgress||!this.paused){if(!e)return void this.logger.warn("Resume called but no paused print job");this.loadJobState(e)}this.paused=!1,this.logger.info("Resuming print job "+this.jobId),this.emitJobState("in-progress");try{yield this.processJob(),this.paused||this.completeJob()}catch(t){throw this.logger.error(`Print job ${this.jobId} failed after resume:`,t),this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.wrapError(t,a.z.PRINT_JOB_FAILED,"Print job failed")}})}cancel(){this.inProgress?(this.logger.info("Cancelling print job "+this.jobId),this.paused=!1,this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.logger.info(`Print job ${this.jobId} cancelled`)):this.logger.warn("Cancel called but no print job in progress")}pause(){this.inProgress?(this.paused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}isPaused(){return this.paused}isInProgress(){return this.inProgress}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}setOptions(e){this.adapterOptions=r(r({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions)}destroy(){this.cancel(),this.instanceJobStateStore.clear(),this.onProgress=void 0,this.onJobStateChange=void 0,this.logger.info("PrintJobManager destroyed")}generateJobId(){return`job-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}saveJobState(){if(this.jobBuffer&&this.jobId)try{const t={jobId:this.jobId,jobBuffer:Array.from(this.jobBuffer),jobOffset:this.jobOffset,adapterOptions:r({},this.adapterOptions),timestamp:Date.now()};this.instanceJobStateStore.set(this.jobId,t),e.staticJobStateStore.set(this.jobId,t),e.ensureCleanupTimer(),this.logger.debug(`Saved job state for ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(t){this.logger.error(`Failed to save job state for ${this.jobId}:`,t)}}loadJobState(t){var n;try{this.logger.debug("Loading job state for "+t);const i=null!=(n=this.instanceJobStateStore.get(t))?n:e.staticJobStateStore.get(t);if(!i)throw new a.B(a.z.QUEUE_JOB_NOT_FOUND,"Job state not found for "+t);this.jobId=i.jobId,this.jobBuffer=new Uint8Array(i.jobBuffer),this.jobOffset=i.jobOffset,this.adapterOptions=r({},i.adapterOptions),this.paused=!0,this.inProgress=!0,this.logger.info(`Loaded job ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(i){throw this.logger.error(`Failed to load job state for ${t}:`,i),new a.B(a.z.PRINT_JOB_FAILED,"Failed to load job "+t,a.C(i))}}clearJobState(){this.jobId&&(this.logger.debug("Clearing job state for "+this.jobId),this.instanceJobStateStore.delete(this.jobId),e.staticJobStateStore.delete(this.jobId)),this.jobBuffer=null,this.jobOffset=0,this.jobId=null,this.adapterOptions={}}static ensureCleanupTimer(){e.cleanupTimer||(e.cleanupTimer=setInterval(()=>{e.cleanupExpiredJobs()},3e5),"function"==typeof e.cleanupTimer.unref&&e.cleanupTimer.unref())}static cleanupExpiredJobs(t=36e5){const n=Date.now();let i=0;for(const[s,r]of e.staticJobStateStore.entries())n-r.timestamp>t&&(e.staticJobStateStore.delete(s),i++);return 0===e.staticJobStateStore.size&&e.cleanupTimer&&(clearInterval(e.cleanupTimer),e.cleanupTimer=null),i}static stopCleanupTimer(){e.cleanupTimer&&(clearInterval(e.cleanupTimer),e.cleanupTimer=null)}static getStaticStoreSize(){return e.staticJobStateStore.size}completeJob(){this.logger.info(`Print job ${this.jobId} completed successfully`),this.inProgress=!1,this.clearJobState(),this.emitJobState("completed")}emitJobState(e){var t;null==(t=this.onJobStateChange)||t.call(this,e)}processJob(){return o(this,null,function*(){var e;if(!this.jobBuffer||"function"!=typeof this.adapter.write)throw new a.B(a.z.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const{chunkSize:t=512}=this.adapterOptions,n=this.jobBuffer,i=n.length,s=this.getDeviceId();for(;this.jobOffset<n.length;){if(this.paused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const r=Math.min(this.jobOffset+t,n.length),o=n.slice(this.jobOffset,r);yield this.adapter.write(s,o.buffer,this.adapterOptions),this.jobOffset=r,this.logger.debug(`Processed ${this.jobOffset}/${i} bytes`),null==(e=this.onProgress)||e.call(this,this.jobOffset,i)}})}getDeviceId(){const e=this.connectionManager.getDeviceId();if(!e)throw new a.B(a.z.DEVICE_DISCONNECTED,"Device ID not available");return e}};g.staticJobStateStore=new Map,g.cleanupTimer=null;let p=g;var f=(e=>(e.LEFT="left",e.CENTER="center",e.RIGHT="right",e))(f||{});const m={align:"left",widthScale:1,heightScale:1,bold:!1,underline:!1,inverse:!1},b=27,C=29;class I{constructor(){this.currentStyle=r({},m)}setStyle(e){var t,n;const i=[];if(void 0!==e.align&&e.align!==this.currentStyle.align){const t=this.getAlignValue(e.align);i.push(new Uint8Array([b,97,t])),this.currentStyle.align=e.align}const s=this.clampScale(null!=(t=e.widthScale)?t:this.currentStyle.widthScale),r=this.clampScale(null!=(n=e.heightScale)?n:this.currentStyle.heightScale);if(s!==this.currentStyle.widthScale||r!==this.currentStyle.heightScale){const e=s-1<<4|r-1;i.push(new Uint8Array([C,33,e])),this.currentStyle.widthScale=s,this.currentStyle.heightScale=r}return void 0!==e.bold&&e.bold!==this.currentStyle.bold&&(i.push(new Uint8Array([b,69,e.bold?1:0])),this.currentStyle.bold=e.bold),void 0!==e.underline&&e.underline!==this.currentStyle.underline&&(i.push(new Uint8Array([b,45,e.underline?1:0])),this.currentStyle.underline=e.underline),void 0!==e.inverse&&e.inverse!==this.currentStyle.inverse&&(i.push(new Uint8Array([C,66,e.inverse?1:0])),this.currentStyle.inverse=e.inverse),i}resetStyle(){const e=[];return"left"!==this.currentStyle.align&&e.push(new Uint8Array([b,97,0])),1===this.currentStyle.widthScale&&1===this.currentStyle.heightScale||e.push(new Uint8Array([C,33,0])),this.currentStyle.bold&&e.push(new Uint8Array([b,69,0])),this.currentStyle.underline&&e.push(new Uint8Array([b,45,0])),this.currentStyle.inverse&&e.push(new Uint8Array([C,66,0])),this.currentStyle=r({},m),e}format(e,t){if(!e||"string"!=typeof e)return[];const n=[];return t&&n.push(...this.setStyle(t)),n}align(e){const t=this.getAlignValue(e);return this.currentStyle.align=e,[new Uint8Array([b,97,t])]}setSize(e,t){const n=this.clampScale(e),i=this.clampScale(t),s=n-1<<4|i-1;return this.currentStyle.widthScale=n,this.currentStyle.heightScale=i,[new Uint8Array([C,33,s])]}setBold(e){return this.currentStyle.bold=e,[new Uint8Array([b,69,e?1:0])]}setUnderline(e){return this.currentStyle.underline=e,[new Uint8Array([b,45,e?1:0])]}setInverse(e){return this.currentStyle.inverse=e,[new Uint8Array([C,66,e?1:0])]}getCurrentStyle(){return r({},this.currentStyle)}getAlignValue(e){switch(e){case"left":default:return 0;case"center":return 1;case"right":return 2}}clampScale(e){return Math.max(1,Math.min(8,Math.floor(e)))}}var E=(e=>(e.CODE128="CODE128",e.CODE39="CODE39",e.EAN13="EAN13",e.EAN8="EAN8",e.UPCA="UPCA",e.ITF="ITF",e.CODABAR="CODABAR",e.QR_CODE="QR_CODE",e.PDF417="PDF417",e))(E||{});const v=29,S={UPCA:65,EAN13:67,EAN8:68,CODE39:69,ITF:70,CODABAR:71,CODE128:73,QR_CODE:80,PDF417:81},A={L:48,M:49,Q:50,H:51},y={1:49,2:50},N={none:0,above:1,below:2,both:3},D={0:48,1:49,2:50,3:51};class O{generate(e,t){return this.validate(e,t.format).valid?"QR_CODE"===t.format?this.generateQRCode(e,t):"PDF417"===t.format?this.generatePDF417(e,t):this.generate1DBarcode(e,t):[]}generate1DBarcode(e,t){var n,i;const s=[],r=this.clampHeight(null!=(n=t.height)?n:80);s.push(new Uint8Array([v,104,r]));const o=this.clampWidth(null!=(i=t.width)?i:3);s.push(new Uint8Array([v,119,o]));const a=this.getTextPosition(t);s.push(new Uint8Array([v,72,a]));const h=S[t.format],c=this.encodeContent(e,t.format);return s.push(new Uint8Array([v,107,h,c.length,...c])),s}generateQRCode(e,t){var n,i,s,r,o;const a=[],h=null!=(n=t.qrModel)?n:2,c=this.clampQRSize(null!=(i=t.height)?i:6),l=null!=(s=t.errorCorrection)?s:"M",d=null!=(r=y[h])?r:50;a.push(new Uint8Array([v,40,107,4,0,49,65,80,d])),a.push(new Uint8Array([v,40,107,3,0,49,67,c]));const u=null!=(o=A[l])?o:49;a.push(new Uint8Array([v,40,107,3,0,49,69,u]));const g=this.encodeUTF8(e),p=g.length+3;return a.push(new Uint8Array([v,40,107,255&p,p>>8&255,49,80,48,...g])),a.push(new Uint8Array([v,40,107,3,0,49,81,48])),a}generatePDF417(e,t){var n,i,s,r;const o=[],a=null!=(n=t.pdf417Compression)?n:2,h=null!=(i=t.pdf417Security)?i:2,c=this.clampPDF417Columns(null!=(s=t.pdf417Columns)?s:2);o.push(new Uint8Array([v,40,107,7,0,49,48,c,h,0,0]));const l=null!=(r=D[a])?r:50;o.push(new Uint8Array([27,93,4,l]));const d=this.encodeUTF8(e),u=d.length+3;return o.push(new Uint8Array([v,107,81,255&u,u>>8&255,...d])),o.push(new Uint8Array([v,40,107,3,0,49,81,49])),o}validate(e,t){const n=[];if(null==e)return n.push({field:"content",message:"Barcode content is required",code:"REQUIRED"}),{valid:!1,errors:n};if("string"!=typeof e)return n.push({field:"content",message:"Barcode content must be a string",code:"INVALID_TYPE"}),{valid:!1,errors:n};if(0===e.length)return n.push({field:"content",message:"Barcode content cannot be empty",code:"REQUIRED"}),{valid:!1,errors:n};switch("QR_CODE"===t&&e.length>7089&&n.push({field:"content",message:"QR code content exceeds maximum length (7089 bytes for binary mode)",code:"CONTENT_TOO_LONG"}),"PDF417"===t&&e.length>1850&&n.push({field:"content",message:"PDF417 content exceeds maximum length (~1850 bytes)",code:"CONTENT_TOO_LONG"}),t){case"EAN13":this.validateEAN13(e,n);break;case"EAN8":this.validateEAN8(e,n);break;case"UPCA":this.validateUPCA(e,n);break;case"CODE39":this.validateCode39(e,n);break;case"CODE128":this.validateCode128(e,n);break;case"ITF":this.validateITF(e,n);break;case"CODABAR":this.validateCodabar(e,n);break;case"QR_CODE":this.validateQRCode(e,n);break;case"PDF417":this.validatePDF417(e,n);break;default:n.push({field:"format",message:"Unsupported barcode format: "+t,code:"UNSUPPORTED_FORMAT"})}return{valid:0===n.length,errors:n}}validateQRCode(e,t){0===e.length&&t.push({field:"content",message:"QR code content cannot be empty",code:"REQUIRED"}),e.length>7089&&t.push({field:"content",message:"QR code content exceeds maximum binary mode length",code:"CONTENT_TOO_LONG"})}validatePDF417(e,t){0===e.length&&t.push({field:"content",message:"PDF417 content cannot be empty",code:"REQUIRED"}),e.length>1850&&t.push({field:"content",message:"PDF417 content exceeds maximum length",code:"CONTENT_TOO_LONG"});let n=!1;for(let i=0;i<e.length;i++)if(e.charCodeAt(i)>127){n=!0;break}n&&t.push({field:"content",message:"PDF417 standard mode only supports ASCII characters. Consider using compression mode.",code:"INVALID_CHARACTERS"})}getSupportedFormats(){return Object.values(E)}validateEAN13(e,t){if(/^\d{12,13}$/.test(e)){if(13===e.length){const n=this.calculateEANCheckDigit(e.substring(0,12)),i=e[12];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid EAN-13 check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"EAN-13 must be 12 or 13 digits",code:"INVALID_LENGTH"})}validateEAN8(e,t){if(/^\d{7,8}$/.test(e)){if(8===e.length){const n=this.calculateEANCheckDigit(e.substring(0,7)),i=e[7];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid EAN-8 check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"EAN-8 must be 7 or 8 digits",code:"INVALID_LENGTH"})}validateUPCA(e,t){if(/^\d{11,12}$/.test(e)){if(12===e.length){const n=this.calculateUPCACheckDigit(e.substring(0,11)),i=e[11];void 0!==i&&parseInt(i)!==n&&t.push({field:"content",message:"Invalid UPC-A check digit",code:"INVALID_CHECK_DIGIT"})}}else t.push({field:"content",message:"UPC-A must be 11 or 12 digits",code:"INVALID_LENGTH"})}validateCode39(e,t){/^[0-9A-Z\s\-.$/+%]+$/.test(e.toUpperCase())||t.push({field:"content",message:"Code 39 only supports: 0-9, A-Z, space, - . $ / + %",code:"INVALID_CHARACTERS"}),(0===e.length||e.length>255)&&t.push({field:"content",message:"Code 39 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateCode128(e,t){for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t.push({field:"content",message:"Code 128 only supports ASCII characters (0-127)",code:"INVALID_CHARACTERS"});break}(0===e.length||e.length>255)&&t.push({field:"content",message:"Code 128 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateITF(e,t){/^\d+$/.test(e)||t.push({field:"content",message:"ITF only supports numeric characters",code:"INVALID_CHARACTERS"}),e.length%2!=0&&t.push({field:"content",message:"ITF content must have even number of digits",code:"INVALID_LENGTH"}),(0===e.length||e.length>255)&&t.push({field:"content",message:"ITF content must be 2-254 digits (even)",code:"INVALID_LENGTH"})}validateCodabar(e,t){/^[ABCDabcd][0-9\-$:/.+]+[ABCDabcd]$/.test(e)||t.push({field:"content",message:"CODABAR must start and end with A/B/C/D and contain only 0-9, - $ : / . +",code:"INVALID_FORMAT"}),(3>e.length||e.length>255)&&t.push({field:"content",message:"CODABAR content must be 3-255 characters",code:"INVALID_LENGTH"})}calculateEANCheckDigit(e){let t=0;const n=e.length;for(let i=0;n>i;i++){const n=e[i];void 0!==n&&(t+=parseInt(n)*(i%2==0?1:3))}return(10-t%10)%10}calculateUPCACheckDigit(e){let t=0;for(let n=0;11>n;n++){const i=e[n];void 0!==i&&(t+=parseInt(i)*(n%2==0?3:1))}return(10-t%10)%10}encodeContent(e,t){return"CODE128"===t?[123,/^\d+$/.test(e)&&e.length>=4?67:66,...e.split("").map(e=>e.charCodeAt(0))]:e.split("").map(e=>e.charCodeAt(0))}encodeUTF8(e){const t=[];for(let n=0;n<e.length;n++){const i=e.charCodeAt(n);128>i?t.push(i):2048>i?(t.push(192|i>>6),t.push(128|63&i)):65536>i?(t.push(224|i>>12),t.push(128|i>>6&63),t.push(128|63&i)):(t.push(240|i>>18),t.push(128|i>>12&63),t.push(128|i>>6&63),t.push(128|63&i))}return t}getTextPosition(e){var t,n,i;if(!1===e.showText)return N.none;const s=null!=(t=e.textPosition)?t:"below";return null!=(i=null!=(n=N[s])?n:N.below)?i:2}clampHeight(e){return Math.max(1,Math.min(255,Math.floor(e)))}clampWidth(e){return Math.max(2,Math.min(6,Math.floor(e)))}clampQRSize(e){return Math.max(1,Math.min(16,Math.floor(e)))}clampPDF417Columns(e){return Math.max(1,Math.min(30,Math.floor(e)))}}class w{constructor(e){this.logger=a.L.scope("CommandBuilder"),this.buffer=[],this.cachedBuffer=null,this.driver=null!=e?e:new c.E,this.formatter=new I,this.barcodeGenerator=new O,this.buffer.push(...this.driver.init())}pushCommands(e){e.length>0&&(this.buffer.push(...e),this.cachedBuffer=null)}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.pushCommands(this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.pushCommands(this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.pushCommands(this.driver.cut()),this}image(e,t,n){return this.logger.debug(`Adding image: ${t}x${n}`),this.pushCommands(this.driver.image(e,t,n)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.pushCommands(this.driver.qr(e,t)),this}clear(){return this.buffer=[],this.pushCommands(this.driver.init()),this}align(e){return this.logger.debug("Setting alignment:",e),this.pushCommands(this.formatter.align(e)),this}setSize(e,t){return this.logger.debug(`Setting size: ${e}x${t}`),this.pushCommands(this.formatter.setSize(e,t)),this}setBold(e){return this.logger.debug("Setting bold:",e),this.pushCommands(this.formatter.setBold(e)),this}setUnderline(e){return this.logger.debug("Setting underline:",e),this.pushCommands(this.formatter.setUnderline(e)),this}setInverse(e){return this.logger.debug("Setting inverse:",e),this.pushCommands(this.formatter.setInverse(e)),this}setStyle(e){return this.logger.debug("Setting style:",e),this.pushCommands(this.formatter.setStyle(e)),this}resetStyle(){return this.logger.debug("Resetting style"),this.pushCommands(this.formatter.resetStyle()),this}barcode(e,t){this.logger.debug(`Adding barcode: ${e} (${t.format})`);const n=this.barcodeGenerator.generate(e,t);return n.length>0?this.pushCommands(n):this.logger.warn("Failed to generate barcode for content: "+e),this}getBuffer(){if(this.cachedBuffer)return this.cachedBuffer;const e=this.buffer.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e);let n=0;for(const i of this.buffer)t.set(i,n),n+=i.length;return this.cachedBuffer=t,t}getTotalBytes(){return this.buffer.reduce((e,t)=>e+t.length,0)}}exports.B=class extends l{constructor(e,t,n){super(),this.printerLogger=a.L.scope("BluetoothPrinter"),this.state=a.P.DISCONNECTED,this.connectionManager=this.resolveConnectionManager(e),this.printJobManager=null!=t?t:new p(this.connectionManager),this.commandBuilder=null!=n?n:new w,this.updateState()}resolveConnectionManager(e){return e?"function"==typeof e.getState?e:new u(e):new u}handleError(e,t,n){const i=e instanceof a.B?e:new a.B(t,n,a.C(e));return this.emit("error",i),this.updateState(),i}updateState(){this.printJobManager.isPaused()?this.state=a.P.PAUSED:this.printJobManager.isInProgress()?this.state=a.P.PRINTING:this.state=this.connectionManager.getState(),this.emit("state-change",this.state),this.printerLogger.debug("State updated:",this.state)}connect(e){return o(this,null,function*(){this.printerLogger.info("Connecting to device:",e);try{return yield this.connectionManager.connect(e),this.updateState(),this.emit("connected",e),this.printerLogger.info("Connected successfully"),this}catch(t){throw this.handleError(t,a.z.CONNECTION_FAILED,"Connection failed")}})}disconnect(){return o(this,null,function*(){const e=this.connectionManager.getDeviceId();if(e){this.printerLogger.info("Disconnecting from device:",e);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",e),this.printerLogger.info("Disconnected successfully")}catch(t){throw this.handleError(t,a.z.DEVICE_DISCONNECTED,"Disconnect failed")}}else this.printerLogger.warn("Disconnect called but no device connected")})}text(e,t){return this.commandBuilder.text(e,t),this}feed(e=1){return this.commandBuilder.feed(e),this}cut(){return this.commandBuilder.cut(),this}image(e,t,n){return this.commandBuilder.image(e,t,n),this}qr(e,t){return this.commandBuilder.qr(e,t),this}align(e){return this.commandBuilder.align(e),this}setSize(e,t){return this.commandBuilder.setSize(e,t),this}setBold(e){return this.commandBuilder.setBold(e),this}setUnderline(e){return this.commandBuilder.setUnderline(e),this}resetStyle(){return this.commandBuilder.resetStyle(),this}barcode(e,t,n){return this.commandBuilder.barcode(e,r({format:t},n)),this}setOptions(e){return this.printJobManager.setOptions(e),this}writeRaw(e,t){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new a.B(a.z.CONNECTION_FAILED,"Printer not connected. Call connect() first.");this.printerLogger.info(`writeRaw: ${e.length} bytes`),t&&this.printJobManager.setOptions(t),this.updateState(),this.printJobManager.setProgressCallback((e,t)=>{this.emit("progress",{sent:e,total:t})});try{yield this.printJobManager.start(e),this.printJobManager.isPaused()||this.emit("print-complete")}catch(n){throw this.handleError(n,a.z.PRINT_JOB_FAILED,"writeRaw failed")}finally{this.updateState()}})}pause(){this.printJobManager.pause(),this.updateState(),this.printerLogger.info("Print job paused")}resume(){return o(this,null,function*(){this.printerLogger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.printerLogger.info("Print job resumed")}catch(e){throw this.handleError(e,a.z.PRINT_JOB_FAILED,"Failed to resume print job")}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.printerLogger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new a.B(a.z.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const e=this.commandBuilder.getBuffer();this.printerLogger.info(`Starting print job: ${e.length} bytes`),this.commandBuilder.clear(),this.updateState(),this.printJobManager.setProgressCallback((e,t)=>{this.emit("progress",{sent:e,total:t})});try{yield this.printJobManager.start(e),this.printJobManager.isPaused()?this.printerLogger.info("Print job paused"):(this.emit("print-complete"),this.printerLogger.info("Print job completed successfully"))}catch(t){throw this.printerLogger.error("Print job failed with error:",t),this.handleError(t,a.z.PRINT_JOB_FAILED,"Print job failed")}finally{this.updateState()}})}getConnectionManager(){return this.connectionManager}getCommandBuilder(){return this.commandBuilder}destroy(){this.printerLogger.info("Destroying BluetoothPrinter instance"),this.printJobManager.cancel(),this.commandBuilder.clear(),this.connectionManager.isConnected()&&this.connectionManager.disconnect().catch(e=>{this.printerLogger.warn("Error during disconnect in destroy:",e)}),this.connectionManager.destroy(),this.removeAllListeners(),this.printerLogger.info("BluetoothPrinter instance destroyed")}},exports.C=u,exports.E=l,exports.P=p,exports.T=I,exports.a=O,exports.b=f,exports.c=E,exports.d=w;
@@ -0,0 +1 @@
1
+ var t=Object.defineProperty,e=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,s=(e,n,i)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[n]=i,r=(t,r)=>{for(var o in r||(r={}))n.call(r,o)&&s(t,o,r[o]);if(e)for(var o of e(r))i.call(r,o)&&s(t,o,r[o]);return t},o=(t,e,n)=>new Promise((i,s)=>{var r=t=>{try{a(n.next(t))}catch(e){s(e)}},o=t=>{try{a(n.throw(t))}catch(e){s(e)}},a=t=>t.done?i(t.value):Promise.resolve(t.value).then(r,o);a((n=n.apply(t,e)).next())});import{L as a,P as h,A as c,B as l,C as d,z as u}from"./shared-DuaS72fL.js";import{A as g}from"./AdapterFactory-sRvkpRnt.js";import{E as p}from"./EscPosDriver-DGK4usVf.js";class f{constructor(){this.listeners={},this.debugMode=!1,this.logger=a.scope("EventEmitter")}ensureListeners(t){return this.listeners[t]||(this.listeners[t]=/* @__PURE__ */new Set),this.listeners[t]}on(t,e){return this.ensureListeners(t).add(e),this.debugMode&&this.logger.debug(`EventEmitter: Added listener for "${t+""}"`,{listenerCount:this.listenerCount(t)}),()=>this.off(t,e)}once(t,e){const n=this.wrapOnceHandler(t,e);return this.on(t,n)}prepend(t,e){const n=this.ensureListeners(t),i=/* @__PURE__ */new Set;return i.add(e),n.forEach(t=>i.add(t)),this.listeners[t]=i,this.debugMode&&this.logger.debug(`EventEmitter: Prepend listener for "${t+""}"`,{listenerCount:this.listenerCount(t)}),()=>this.off(t,e)}prependOnce(t,e){const n=this.wrapOnceHandler(t,e);return this.prepend(t,n)}wrapOnceHandler(t,e){const n=i=>{e(i),this.off(t,n)};return n}off(t,e){const n=this.listeners[t];n&&(n.delete(e),this.debugMode&&this.logger.debug(`EventEmitter: Removed listener for "${t+""}"`,{listenerCount:n.size}),0===n.size&&(delete this.listeners[t],this.debugMode&&this.logger.debug(`EventEmitter: Removed event "${t+""}" (no more listeners)`)))}getHandlers(t){var e;return null!=(e=this.listeners[t])?e:/* @__PURE__ */new Set}emit(t,...e){const n=e[0],i=this.getHandlers(t);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting "${t+""}"`,{data:n,listenerCount:i.size}),0!==i.size)for(const r of i)if("function"==typeof r)try{r(n)}catch(s){this.logger.error(`Error in event handler for "${t+""}":`,s)}}emitAsync(t,...e){return o(this,null,function*(){const n=e[0],i=this.getHandlers(t);if(this.debugMode&&this.logger.debug(`EventEmitter: Emitting async "${t+""}"`,{data:n,listenerCount:i.size}),0===i.size)return;const s=[];i.forEach(e=>{s.push((()=>o(this,null,function*(){try{const t=e(n);null!=t&&"function"==typeof t.then&&(yield t)}catch(i){this.logger.error(`Error in event handler for "${t+""}":`,i)}}))())}),yield Promise.all(s),this.debugMode&&this.logger.debug(`EventEmitter: Finished emitting async "${t+""}"`)})}removeAllListeners(t){if(t){const e=this.listenerCount(t);delete this.listeners[t],this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${e} listeners for "${t+""}"`)}else{const t=Object.keys(this.listeners).length;this.listeners={},this.debugMode&&this.logger.debug(`EventEmitter: Removed all ${t} events and their listeners`)}}listenerCount(t){var e,n;return null!=(n=null==(e=this.listeners[t])?void 0:e.size)?n:0}getListeners(t){const e=this.listeners[t];return e?Array.from(e):[]}eventNames(){return Object.keys(this.listeners)}hasListeners(t){return this.listenerCount(t)>0}setDebugMode(t){this.debugMode=t,this.logger.debug("EventEmitter: Debug mode "+(t?"enabled":"disabled"))}isDebugMode(){return this.debugMode}getTotalEvents(){return Object.keys(this.listeners).length}getTotalListeners(){var t,e;let n=0;for(const i of Object.keys(this.listeners))n+=null!=(e=null==(t=this.listeners[i])?void 0:t.size)?e:0;return n}reset(){this.removeAllListeners(),this.debugMode=!1}}const m={heartbeatEnabled:!0,heartbeatInterval:5e3,autoReconnect:!0,maxReconnectAttempts:3,reconnectInterval:2e3,connectionTimeout:1e4};class b extends f{constructor(t,e){var n,i;super(),this.deviceId=null,this.state=h.DISCONNECTED,this.connLogger=a.scope("ConnectionManager"),this.heartbeatTimer=null,this.reconnectAttempts=0,this.isReconnecting=!1,this.reconnectTimer=null,this.adapter=t||g.create(),this.config=r(r({},m),e),null==(i=(n=this.adapter).onStateChange)||i.call(n,t=>{this.handleStateChange(t)})}handleStateChange(t){const e=this.state;this.state=t,this.connLogger.debug("State changed:",{from:e,to:t}),this.emit("state-change",t),e===h.CONNECTED&&t===h.DISCONNECTED&&this.deviceId&&!this.isReconnecting&&(this.connLogger.warn("Unexpected disconnection detected"),this.emit("disconnected",this.deviceId),this.stopHeartbeat(),this.config.autoReconnect&&this.startReconnect())}connect(t,e){return o(this,null,function*(){this.connLogger.info("Connecting to device:",t);const{retries:n=0,timeout:i=this.config.connectionTimeout}=e||{};let s=0;for(this.reconnectAttempts=0,this.isReconnecting=!1,this.clearReconnectTimer();n>=s;)try{this.deviceId=t,this.state=h.CONNECTING,this.emit("state-change",h.CONNECTING);const e=this.adapter.connect(t);return yield c(e,i,`Connection to device ${t} timed out`),this.state=h.CONNECTED,this.emit("state-change",h.CONNECTED),this.emit("connected",t),this.connLogger.info("Connected successfully"),void(this.config.heartbeatEnabled&&this.startHeartbeat())}catch(r){if(s++,s>n){this.deviceId=null,this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED);const e=this.classifyConnectError(r,t,s,i);throw this.connLogger.error("Connection failed:",e),this.emit("error",e),e}this.connLogger.warn(`Connection attempt ${s}/${n} failed, retrying...`,r),yield new Promise(t=>setTimeout(t,1e3))}})}classifyConnectError(t,e,n,i){if(t instanceof l)return t;const s=d(t).message.toLowerCase();return s.includes("timed out")||s.includes("timeout")?new l(u.CONNECTION_TIMEOUT,`Connection to device ${e} timed out after ${i}ms`):new l(u.CONNECTION_FAILED,`Connection failed after ${n} attempts`,d(t))}disconnect(){return o(this,null,function*(){if(this.stopHeartbeat(),this.clearReconnectTimer(),this.isReconnecting=!1,!this.deviceId)return void this.connLogger.warn("Disconnect called but no device connected");const t=this.deviceId;this.connLogger.info("Disconnecting from device:",t);try{yield this.adapter.disconnect(t),this.deviceId=null,this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED),this.emit("disconnected",t),this.connLogger.info("Disconnected successfully")}catch(e){const t=new l(u.DEVICE_DISCONNECTED,"Disconnect failed",d(e));throw this.connLogger.error("Disconnect failed:",t),this.emit("error",t),t}})}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.checkHeartbeat()},this.config.heartbeatInterval),this.connLogger.debug("Heartbeat started with interval:",this.config.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,this.connLogger.debug("Heartbeat stopped"))}checkHeartbeat(){if(this.deviceId&&this.state===h.CONNECTED)try{this.isConnected()?this.connLogger.debug("Heartbeat OK"):this.handleHeartbeatLost()}catch(t){this.connLogger.warn("Heartbeat check failed:",t),this.handleHeartbeatLost()}}handleHeartbeatLost(){this.deviceId&&(this.connLogger.warn("Heartbeat lost for device:",this.deviceId),this.emit("heartbeat-lost",this.deviceId),this.stopHeartbeat(),this.state=h.DISCONNECTED,this.emit("state-change",h.DISCONNECTED),this.emit("disconnected",this.deviceId),this.config.autoReconnect&&!this.isReconnecting&&this.startReconnect())}startReconnect(){this.deviceId&&!this.isReconnecting&&(this.isReconnecting=!0,this.reconnectAttempts=0,this.attemptReconnect())}attemptReconnect(){return o(this,null,function*(){if(!this.deviceId)return void(this.isReconnecting=!1);this.reconnectAttempts++;const t=this.deviceId;if(this.reconnectAttempts>this.config.maxReconnectAttempts)return this.connLogger.error("Max reconnect attempts reached"),this.isReconnecting=!1,this.emit("reconnect-failed",{deviceId:t,error:new l(u.CONNECTION_FAILED,`Reconnection failed after ${this.config.maxReconnectAttempts} attempts`)}),void(this.deviceId=null);this.connLogger.info(`Reconnect attempt ${this.reconnectAttempts}/${this.config.maxReconnectAttempts}`),this.emit("reconnecting",{deviceId:t,attempt:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}),this.state=h.CONNECTING,this.emit("state-change",h.CONNECTING);try{yield this.adapter.connect(t),this.connLogger.info("Reconnected successfully"),this.isReconnecting=!1,this.reconnectAttempts=0,this.state=h.CONNECTED,this.emit("state-change",h.CONNECTED),this.emit("reconnected",t),this.config.heartbeatEnabled&&this.startHeartbeat()}catch(e){this.connLogger.warn(`Reconnect attempt ${this.reconnectAttempts} failed:`,e);const t=this.config.reconnectInterval,n=Math.min(t*Math.pow(2,this.reconnectAttempts-1),3e4);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},n)}})}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}isConnected(){return this.state===h.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}getConfig(){return r({},this.config)}getReconnectStatus(){return{isReconnecting:this.isReconnecting,attempts:this.reconnectAttempts,maxAttempts:this.config.maxReconnectAttempts}}reconnect(){if(!this.deviceId)throw new l(u.DEVICE_NOT_FOUND,"No device to reconnect to");this.isReconnecting?this.connLogger.warn("Reconnect already in progress"):this.startReconnect()}stopReconnect(){this.clearReconnectTimer(),this.isReconnecting=!1,this.reconnectAttempts=0,this.connLogger.info("Reconnect stopped")}destroy(){this.stopHeartbeat(),this.clearReconnectTimer(),this.removeAllListeners(),this.deviceId=null,this.state=h.DISCONNECTED}}const C=class t{constructor(t){this.instanceJobStateStore=/* @__PURE__ */new Map,this.jobBuffer=null,this.jobOffset=0,this.paused=!1,this.inProgress=!1,this.adapterOptions={},this.jobId=null,this.logger=a.scope("PrintJobManager"),this.connectionManager=t,this.adapter="function"==typeof t.getAdapter?t.getAdapter():{connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),write:()=>{throw new l(u.INVALID_CONFIGURATION,"No adapter available for print job write")}}}setProgressCallback(t){this.onProgress=t}setJobStateCallback(t){this.onJobStateChange=t}wrapError(t,e,n){return t instanceof l?t:new l(e,n,d(t))}start(t,e){return o(this,null,function*(){var n;if(this.inProgress)throw new l(u.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.jobId=null!=(n=null==e?void 0:e.jobId)?n:this.generateJobId(),this.jobBuffer=t,this.jobOffset=0,this.paused=!1,this.inProgress=!0,this.logger.info(`Starting print job ${this.jobId}: ${t.length} bytes`),this.emitJobState("in-progress");try{yield this.processJob(),this.paused?(this.logger.info(`Print job ${this.jobId} paused`),this.saveJobState()):this.completeJob()}catch(i){throw this.logger.error(`Print job ${this.jobId} failed:`,i),this.inProgress=!1,this.paused?this.saveJobState():this.clearJobState(),this.wrapError(i,u.PRINT_JOB_FAILED,"Print job failed")}})}resume(t){return o(this,null,function*(){if(!this.inProgress||!this.paused){if(!t)return void this.logger.warn("Resume called but no paused print job");this.loadJobState(t)}this.paused=!1,this.logger.info("Resuming print job "+this.jobId),this.emitJobState("in-progress");try{yield this.processJob(),this.paused||this.completeJob()}catch(e){throw this.logger.error(`Print job ${this.jobId} failed after resume:`,e),this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.wrapError(e,u.PRINT_JOB_FAILED,"Print job failed")}})}cancel(){this.inProgress?(this.logger.info("Cancelling print job "+this.jobId),this.paused=!1,this.inProgress=!1,this.clearJobState(),this.emitJobState("cancelled"),this.logger.info(`Print job ${this.jobId} cancelled`)):this.logger.warn("Cancel called but no print job in progress")}pause(){this.inProgress?(this.paused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}isPaused(){return this.paused}isInProgress(){return this.inProgress}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}setOptions(t){this.adapterOptions=r(r({},this.adapterOptions),t),this.logger.debug("Adapter options updated:",this.adapterOptions)}destroy(){this.cancel(),this.instanceJobStateStore.clear(),this.onProgress=void 0,this.onJobStateChange=void 0,this.logger.info("PrintJobManager destroyed")}generateJobId(){return`job-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}saveJobState(){if(this.jobBuffer&&this.jobId)try{const e={jobId:this.jobId,jobBuffer:Array.from(this.jobBuffer),jobOffset:this.jobOffset,adapterOptions:r({},this.adapterOptions),timestamp:Date.now()};this.instanceJobStateStore.set(this.jobId,e),t.staticJobStateStore.set(this.jobId,e),t.ensureCleanupTimer(),this.logger.debug(`Saved job state for ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(e){this.logger.error(`Failed to save job state for ${this.jobId}:`,e)}}loadJobState(e){var n;try{this.logger.debug("Loading job state for "+e);const i=null!=(n=this.instanceJobStateStore.get(e))?n:t.staticJobStateStore.get(e);if(!i)throw new l(u.QUEUE_JOB_NOT_FOUND,"Job state not found for "+e);this.jobId=i.jobId,this.jobBuffer=new Uint8Array(i.jobBuffer),this.jobOffset=i.jobOffset,this.adapterOptions=r({},i.adapterOptions),this.paused=!0,this.inProgress=!0,this.logger.info(`Loaded job ${this.jobId}: offset=${this.jobOffset}/${this.jobBuffer.length}`)}catch(i){throw this.logger.error(`Failed to load job state for ${e}:`,i),new l(u.PRINT_JOB_FAILED,"Failed to load job "+e,d(i))}}clearJobState(){this.jobId&&(this.logger.debug("Clearing job state for "+this.jobId),this.instanceJobStateStore.delete(this.jobId),t.staticJobStateStore.delete(this.jobId)),this.jobBuffer=null,this.jobOffset=0,this.jobId=null,this.adapterOptions={}}static ensureCleanupTimer(){t.cleanupTimer||(t.cleanupTimer=setInterval(()=>{t.cleanupExpiredJobs()},3e5),"function"==typeof t.cleanupTimer.unref&&t.cleanupTimer.unref())}static cleanupExpiredJobs(e=36e5){const n=Date.now();let i=0;for(const[s,r]of t.staticJobStateStore.entries())n-r.timestamp>e&&(t.staticJobStateStore.delete(s),i++);return 0===t.staticJobStateStore.size&&t.cleanupTimer&&(clearInterval(t.cleanupTimer),t.cleanupTimer=null),i}static stopCleanupTimer(){t.cleanupTimer&&(clearInterval(t.cleanupTimer),t.cleanupTimer=null)}static getStaticStoreSize(){return t.staticJobStateStore.size}completeJob(){this.logger.info(`Print job ${this.jobId} completed successfully`),this.inProgress=!1,this.clearJobState(),this.emitJobState("completed")}emitJobState(t){var e;null==(e=this.onJobStateChange)||e.call(this,t)}processJob(){return o(this,null,function*(){var t;if(!this.jobBuffer||"function"!=typeof this.adapter.write)throw new l(u.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const{chunkSize:e=512}=this.adapterOptions,n=this.jobBuffer,i=n.length,s=this.getDeviceId();for(;this.jobOffset<n.length;){if(this.paused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const r=Math.min(this.jobOffset+e,n.length),o=n.slice(this.jobOffset,r);yield this.adapter.write(s,o.buffer,this.adapterOptions),this.jobOffset=r,this.logger.debug(`Processed ${this.jobOffset}/${i} bytes`),null==(t=this.onProgress)||t.call(this,this.jobOffset,i)}})}getDeviceId(){const t=this.connectionManager.getDeviceId();if(!t)throw new l(u.DEVICE_DISCONNECTED,"Device ID not available");return t}};C.staticJobStateStore=/* @__PURE__ */new Map,C.cleanupTimer=null;let I=C;var E=/* @__PURE__ */(t=>(t.LEFT="left",t.CENTER="center",t.RIGHT="right",t))(E||{});const v={align:"left",widthScale:1,heightScale:1,bold:!1,underline:!1,inverse:!1},S=27,A=29;class y{constructor(){this.currentStyle=r({},v)}setStyle(t){var e,n;const i=[];if(void 0!==t.align&&t.align!==this.currentStyle.align){const e=this.getAlignValue(t.align);i.push(new Uint8Array([S,97,e])),this.currentStyle.align=t.align}const s=this.clampScale(null!=(e=t.widthScale)?e:this.currentStyle.widthScale),r=this.clampScale(null!=(n=t.heightScale)?n:this.currentStyle.heightScale);if(s!==this.currentStyle.widthScale||r!==this.currentStyle.heightScale){const t=s-1<<4|r-1;i.push(new Uint8Array([A,33,t])),this.currentStyle.widthScale=s,this.currentStyle.heightScale=r}return void 0!==t.bold&&t.bold!==this.currentStyle.bold&&(i.push(new Uint8Array([S,69,t.bold?1:0])),this.currentStyle.bold=t.bold),void 0!==t.underline&&t.underline!==this.currentStyle.underline&&(i.push(new Uint8Array([S,45,t.underline?1:0])),this.currentStyle.underline=t.underline),void 0!==t.inverse&&t.inverse!==this.currentStyle.inverse&&(i.push(new Uint8Array([A,66,t.inverse?1:0])),this.currentStyle.inverse=t.inverse),i}resetStyle(){const t=[];return"left"!==this.currentStyle.align&&t.push(new Uint8Array([S,97,0])),1===this.currentStyle.widthScale&&1===this.currentStyle.heightScale||t.push(new Uint8Array([A,33,0])),this.currentStyle.bold&&t.push(new Uint8Array([S,69,0])),this.currentStyle.underline&&t.push(new Uint8Array([S,45,0])),this.currentStyle.inverse&&t.push(new Uint8Array([A,66,0])),this.currentStyle=r({},v),t}format(t,e){if(!t||"string"!=typeof t)return[];const n=[];return e&&n.push(...this.setStyle(e)),n}align(t){const e=this.getAlignValue(t);return this.currentStyle.align=t,[new Uint8Array([S,97,e])]}setSize(t,e){const n=this.clampScale(t),i=this.clampScale(e),s=n-1<<4|i-1;return this.currentStyle.widthScale=n,this.currentStyle.heightScale=i,[new Uint8Array([A,33,s])]}setBold(t){return this.currentStyle.bold=t,[new Uint8Array([S,69,t?1:0])]}setUnderline(t){return this.currentStyle.underline=t,[new Uint8Array([S,45,t?1:0])]}setInverse(t){return this.currentStyle.inverse=t,[new Uint8Array([A,66,t?1:0])]}getCurrentStyle(){return r({},this.currentStyle)}getAlignValue(t){switch(t){case"left":default:return 0;case"center":return 1;case"right":return 2}}clampScale(t){return Math.max(1,Math.min(8,Math.floor(t)))}}var N=/* @__PURE__ */(t=>(t.CODE128="CODE128",t.CODE39="CODE39",t.EAN13="EAN13",t.EAN8="EAN8",t.UPCA="UPCA",t.ITF="ITF",t.CODABAR="CODABAR",t.QR_CODE="QR_CODE",t.PDF417="PDF417",t))(N||{});const D=29,O={UPCA:65,EAN13:67,EAN8:68,CODE39:69,ITF:70,CODABAR:71,CODE128:73,QR_CODE:80,PDF417:81},w={L:48,M:49,Q:50,H:51},T={1:49,2:50},R={none:0,above:1,below:2,both:3},P={0:48,1:49,2:50,3:51};class j{generate(t,e){return this.validate(t,e.format).valid?"QR_CODE"===e.format?this.generateQRCode(t,e):"PDF417"===e.format?this.generatePDF417(t,e):this.generate1DBarcode(t,e):[]}generate1DBarcode(t,e){var n,i;const s=[],r=this.clampHeight(null!=(n=e.height)?n:80);s.push(new Uint8Array([D,104,r]));const o=this.clampWidth(null!=(i=e.width)?i:3);s.push(new Uint8Array([D,119,o]));const a=this.getTextPosition(e);s.push(new Uint8Array([D,72,a]));const h=O[e.format],c=this.encodeContent(t,e.format);return s.push(new Uint8Array([D,107,h,c.length,...c])),s}generateQRCode(t,e){var n,i,s,r,o;const a=[],h=null!=(n=e.qrModel)?n:2,c=this.clampQRSize(null!=(i=e.height)?i:6),l=null!=(s=e.errorCorrection)?s:"M",d=null!=(r=T[h])?r:50;a.push(new Uint8Array([D,40,107,4,0,49,65,80,d])),a.push(new Uint8Array([D,40,107,3,0,49,67,c]));const u=null!=(o=w[l])?o:49;a.push(new Uint8Array([D,40,107,3,0,49,69,u]));const g=this.encodeUTF8(t),p=g.length+3;return a.push(new Uint8Array([D,40,107,255&p,p>>8&255,49,80,48,...g])),a.push(new Uint8Array([D,40,107,3,0,49,81,48])),a}generatePDF417(t,e){var n,i,s,r;const o=[],a=null!=(n=e.pdf417Compression)?n:2,h=null!=(i=e.pdf417Security)?i:2,c=this.clampPDF417Columns(null!=(s=e.pdf417Columns)?s:2);o.push(new Uint8Array([D,40,107,7,0,49,48,c,h,0,0]));const l=null!=(r=P[a])?r:50;o.push(new Uint8Array([27,93,4,l]));const d=this.encodeUTF8(t),u=d.length+3;return o.push(new Uint8Array([D,107,81,255&u,u>>8&255,...d])),o.push(new Uint8Array([D,40,107,3,0,49,81,49])),o}validate(t,e){const n=[];if(null==t)return n.push({field:"content",message:"Barcode content is required",code:"REQUIRED"}),{valid:!1,errors:n};if("string"!=typeof t)return n.push({field:"content",message:"Barcode content must be a string",code:"INVALID_TYPE"}),{valid:!1,errors:n};if(0===t.length)return n.push({field:"content",message:"Barcode content cannot be empty",code:"REQUIRED"}),{valid:!1,errors:n};switch("QR_CODE"===e&&t.length>7089&&n.push({field:"content",message:"QR code content exceeds maximum length (7089 bytes for binary mode)",code:"CONTENT_TOO_LONG"}),"PDF417"===e&&t.length>1850&&n.push({field:"content",message:"PDF417 content exceeds maximum length (~1850 bytes)",code:"CONTENT_TOO_LONG"}),e){case"EAN13":this.validateEAN13(t,n);break;case"EAN8":this.validateEAN8(t,n);break;case"UPCA":this.validateUPCA(t,n);break;case"CODE39":this.validateCode39(t,n);break;case"CODE128":this.validateCode128(t,n);break;case"ITF":this.validateITF(t,n);break;case"CODABAR":this.validateCodabar(t,n);break;case"QR_CODE":this.validateQRCode(t,n);break;case"PDF417":this.validatePDF417(t,n);break;default:n.push({field:"format",message:"Unsupported barcode format: "+e,code:"UNSUPPORTED_FORMAT"})}return{valid:0===n.length,errors:n}}validateQRCode(t,e){0===t.length&&e.push({field:"content",message:"QR code content cannot be empty",code:"REQUIRED"}),t.length>7089&&e.push({field:"content",message:"QR code content exceeds maximum binary mode length",code:"CONTENT_TOO_LONG"})}validatePDF417(t,e){0===t.length&&e.push({field:"content",message:"PDF417 content cannot be empty",code:"REQUIRED"}),t.length>1850&&e.push({field:"content",message:"PDF417 content exceeds maximum length",code:"CONTENT_TOO_LONG"});let n=!1;for(let i=0;i<t.length;i++)if(t.charCodeAt(i)>127){n=!0;break}n&&e.push({field:"content",message:"PDF417 standard mode only supports ASCII characters. Consider using compression mode.",code:"INVALID_CHARACTERS"})}getSupportedFormats(){return Object.values(N)}validateEAN13(t,e){if(/^\d{12,13}$/.test(t)){if(13===t.length){const n=this.calculateEANCheckDigit(t.substring(0,12)),i=t[12];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid EAN-13 check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"EAN-13 must be 12 or 13 digits",code:"INVALID_LENGTH"})}validateEAN8(t,e){if(/^\d{7,8}$/.test(t)){if(8===t.length){const n=this.calculateEANCheckDigit(t.substring(0,7)),i=t[7];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid EAN-8 check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"EAN-8 must be 7 or 8 digits",code:"INVALID_LENGTH"})}validateUPCA(t,e){if(/^\d{11,12}$/.test(t)){if(12===t.length){const n=this.calculateUPCACheckDigit(t.substring(0,11)),i=t[11];void 0!==i&&parseInt(i)!==n&&e.push({field:"content",message:"Invalid UPC-A check digit",code:"INVALID_CHECK_DIGIT"})}}else e.push({field:"content",message:"UPC-A must be 11 or 12 digits",code:"INVALID_LENGTH"})}validateCode39(t,e){/^[0-9A-Z\s\-.$/+%]+$/.test(t.toUpperCase())||e.push({field:"content",message:"Code 39 only supports: 0-9, A-Z, space, - . $ / + %",code:"INVALID_CHARACTERS"}),(0===t.length||t.length>255)&&e.push({field:"content",message:"Code 39 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateCode128(t,e){for(let n=0;n<t.length;n++)if(t.charCodeAt(n)>127){e.push({field:"content",message:"Code 128 only supports ASCII characters (0-127)",code:"INVALID_CHARACTERS"});break}(0===t.length||t.length>255)&&e.push({field:"content",message:"Code 128 content must be 1-255 characters",code:"INVALID_LENGTH"})}validateITF(t,e){/^\d+$/.test(t)||e.push({field:"content",message:"ITF only supports numeric characters",code:"INVALID_CHARACTERS"}),t.length%2!=0&&e.push({field:"content",message:"ITF content must have even number of digits",code:"INVALID_LENGTH"}),(0===t.length||t.length>255)&&e.push({field:"content",message:"ITF content must be 2-254 digits (even)",code:"INVALID_LENGTH"})}validateCodabar(t,e){/^[ABCDabcd][0-9\-$:/.+]+[ABCDabcd]$/.test(t)||e.push({field:"content",message:"CODABAR must start and end with A/B/C/D and contain only 0-9, - $ : / . +",code:"INVALID_FORMAT"}),(3>t.length||t.length>255)&&e.push({field:"content",message:"CODABAR content must be 3-255 characters",code:"INVALID_LENGTH"})}calculateEANCheckDigit(t){let e=0;const n=t.length;for(let i=0;n>i;i++){const n=t[i];void 0!==n&&(e+=parseInt(n)*(i%2==0?1:3))}return(10-e%10)%10}calculateUPCACheckDigit(t){let e=0;for(let n=0;11>n;n++){const i=t[n];void 0!==i&&(e+=parseInt(i)*(n%2==0?3:1))}return(10-e%10)%10}encodeContent(t,e){return"CODE128"===e?[123,/^\d+$/.test(t)&&t.length>=4?67:66,...t.split("").map(t=>t.charCodeAt(0))]:t.split("").map(t=>t.charCodeAt(0))}encodeUTF8(t){const e=[];for(let n=0;n<t.length;n++){const i=t.charCodeAt(n);128>i?e.push(i):2048>i?(e.push(192|i>>6),e.push(128|63&i)):65536>i?(e.push(224|i>>12),e.push(128|i>>6&63),e.push(128|63&i)):(e.push(240|i>>18),e.push(128|i>>12&63),e.push(128|i>>6&63),e.push(128|63&i))}return e}getTextPosition(t){var e,n,i;if(!1===t.showText)return R.none;const s=null!=(e=t.textPosition)?e:"below";return null!=(i=null!=(n=R[s])?n:R.below)?i:2}clampHeight(t){return Math.max(1,Math.min(255,Math.floor(t)))}clampWidth(t){return Math.max(2,Math.min(6,Math.floor(t)))}clampQRSize(t){return Math.max(1,Math.min(16,Math.floor(t)))}clampPDF417Columns(t){return Math.max(1,Math.min(30,Math.floor(t)))}}class L{constructor(t){this.logger=a.scope("CommandBuilder"),this.buffer=[],this.cachedBuffer=null,this.driver=null!=t?t:new p,this.formatter=new y,this.barcodeGenerator=new j,this.buffer.push(...this.driver.init())}pushCommands(t){t.length>0&&(this.buffer.push(...t),this.cachedBuffer=null)}text(t,e){return this.logger.debug("Adding text:",t.substring(0,50)),this.pushCommands(this.driver.text(t,e)),this}feed(t=1){return this.logger.debug("Adding feed:",t),this.pushCommands(this.driver.feed(t)),this}cut(){return this.logger.debug("Adding cut command"),this.pushCommands(this.driver.cut()),this}image(t,e,n){return this.logger.debug(`Adding image: ${e}x${n}`),this.pushCommands(this.driver.image(t,e,n)),this}qr(t,e){return this.logger.debug("Adding QR code:",t.substring(0,50)),this.pushCommands(this.driver.qr(t,e)),this}clear(){return this.buffer=[],this.pushCommands(this.driver.init()),this}align(t){return this.logger.debug("Setting alignment:",t),this.pushCommands(this.formatter.align(t)),this}setSize(t,e){return this.logger.debug(`Setting size: ${t}x${e}`),this.pushCommands(this.formatter.setSize(t,e)),this}setBold(t){return this.logger.debug("Setting bold:",t),this.pushCommands(this.formatter.setBold(t)),this}setUnderline(t){return this.logger.debug("Setting underline:",t),this.pushCommands(this.formatter.setUnderline(t)),this}setInverse(t){return this.logger.debug("Setting inverse:",t),this.pushCommands(this.formatter.setInverse(t)),this}setStyle(t){return this.logger.debug("Setting style:",t),this.pushCommands(this.formatter.setStyle(t)),this}resetStyle(){return this.logger.debug("Resetting style"),this.pushCommands(this.formatter.resetStyle()),this}barcode(t,e){this.logger.debug(`Adding barcode: ${t} (${e.format})`);const n=this.barcodeGenerator.generate(t,e);return n.length>0?this.pushCommands(n):this.logger.warn("Failed to generate barcode for content: "+t),this}getBuffer(){if(this.cachedBuffer)return this.cachedBuffer;const t=this.buffer.reduce((t,e)=>t+e.length,0),e=new Uint8Array(t);let n=0;for(const i of this.buffer)e.set(i,n),n+=i.length;return this.cachedBuffer=e,e}getTotalBytes(){return this.buffer.reduce((t,e)=>t+e.length,0)}}class M extends f{constructor(t,e,n){super(),this.printerLogger=a.scope("BluetoothPrinter"),this.state=h.DISCONNECTED,this.connectionManager=this.resolveConnectionManager(t),this.printJobManager=null!=e?e:new I(this.connectionManager),this.commandBuilder=null!=n?n:new L,this.updateState()}resolveConnectionManager(t){return t?"function"==typeof t.getState?t:new b(t):new b}handleError(t,e,n){const i=t instanceof l?t:new l(e,n,d(t));return this.emit("error",i),this.updateState(),i}updateState(){this.printJobManager.isPaused()?this.state=h.PAUSED:this.printJobManager.isInProgress()?this.state=h.PRINTING:this.state=this.connectionManager.getState(),this.emit("state-change",this.state),this.printerLogger.debug("State updated:",this.state)}connect(t){return o(this,null,function*(){this.printerLogger.info("Connecting to device:",t);try{return yield this.connectionManager.connect(t),this.updateState(),this.emit("connected",t),this.printerLogger.info("Connected successfully"),this}catch(e){throw this.handleError(e,u.CONNECTION_FAILED,"Connection failed")}})}disconnect(){return o(this,null,function*(){const t=this.connectionManager.getDeviceId();if(t){this.printerLogger.info("Disconnecting from device:",t);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",t),this.printerLogger.info("Disconnected successfully")}catch(e){throw this.handleError(e,u.DEVICE_DISCONNECTED,"Disconnect failed")}}else this.printerLogger.warn("Disconnect called but no device connected")})}text(t,e){return this.commandBuilder.text(t,e),this}feed(t=1){return this.commandBuilder.feed(t),this}cut(){return this.commandBuilder.cut(),this}image(t,e,n){return this.commandBuilder.image(t,e,n),this}qr(t,e){return this.commandBuilder.qr(t,e),this}align(t){return this.commandBuilder.align(t),this}setSize(t,e){return this.commandBuilder.setSize(t,e),this}setBold(t){return this.commandBuilder.setBold(t),this}setUnderline(t){return this.commandBuilder.setUnderline(t),this}resetStyle(){return this.commandBuilder.resetStyle(),this}barcode(t,e,n){return this.commandBuilder.barcode(t,r({format:e},n)),this}setOptions(t){return this.printJobManager.setOptions(t),this}writeRaw(t,e){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new l(u.CONNECTION_FAILED,"Printer not connected. Call connect() first.");this.printerLogger.info(`writeRaw: ${t.length} bytes`),e&&this.printJobManager.setOptions(e),this.updateState(),this.printJobManager.setProgressCallback((t,e)=>{this.emit("progress",{sent:t,total:e})});try{yield this.printJobManager.start(t),this.printJobManager.isPaused()||this.emit("print-complete")}catch(n){throw this.handleError(n,u.PRINT_JOB_FAILED,"writeRaw failed")}finally{this.updateState()}})}pause(){this.printJobManager.pause(),this.updateState(),this.printerLogger.info("Print job paused")}resume(){return o(this,null,function*(){this.printerLogger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.printerLogger.info("Print job resumed")}catch(t){throw this.handleError(t,u.PRINT_JOB_FAILED,"Failed to resume print job")}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.printerLogger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new l(u.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const t=this.commandBuilder.getBuffer();this.printerLogger.info(`Starting print job: ${t.length} bytes`),this.commandBuilder.clear(),this.updateState(),this.printJobManager.setProgressCallback((t,e)=>{this.emit("progress",{sent:t,total:e})});try{yield this.printJobManager.start(t),this.printJobManager.isPaused()?this.printerLogger.info("Print job paused"):(this.emit("print-complete"),this.printerLogger.info("Print job completed successfully"))}catch(e){throw this.printerLogger.error("Print job failed with error:",e),this.handleError(e,u.PRINT_JOB_FAILED,"Print job failed")}finally{this.updateState()}})}getConnectionManager(){return this.connectionManager}getCommandBuilder(){return this.commandBuilder}destroy(){this.printerLogger.info("Destroying BluetoothPrinter instance"),this.printJobManager.cancel(),this.commandBuilder.clear(),this.connectionManager.isConnected()&&this.connectionManager.disconnect().catch(t=>{this.printerLogger.warn("Error during disconnect in destroy:",t)}),this.connectionManager.destroy(),this.removeAllListeners(),this.printerLogger.info("BluetoothPrinter instance destroyed")}}export{M as B,b as C,f as E,I as P,y as T,j as a,E as b,N as c,L as d};