taro-bluetooth-print 2.1.0 → 2.1.1

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
@@ -5,9 +5,35 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [2.1.0] - 2024-11-25
8
+ ## [2.1.1] - 2025-12-02
9
9
 
10
10
  ### Added
11
+
12
+ - Encoding类添加了配置选项,支持禁用GBK编码警告
13
+ - Logger类添加了自定义日志处理选项
14
+ - EventEmitter类添加了prepend和prependOnce方法
15
+ - EventEmitter类添加了emitAsync方法,支持异步事件处理
16
+ - EventEmitter类添加了getListeners和eventNames方法
17
+
18
+ ### Changed
19
+
20
+ - 优化了Encoding类的警告机制,只在第一次使用时显示警告
21
+ - 改进了Logger类的日志格式,保持与测试期望一致
22
+ - 增强了EventEmitter类的API灵活性
23
+ - 提高了代码质量,减少了any类型的使用
24
+
25
+ ### Fixed
26
+
27
+ - 修复了Jest未正常退出问题,添加了定时器清理逻辑
28
+ - 修复了TypeScript编译错误
29
+ - 修复了变量赋值前使用的问题
30
+ - 修复了重复标识符问题
31
+ - 确保了所有异步操作都有正确的清理机制
32
+
33
+ ## [2.1.0] - 2025-11-25
34
+
35
+ ### Added
36
+
11
37
  - 支持支付宝小程序平台
12
38
  - 支持百度小程序平台
13
39
  - 支持字节跳动小程序平台
@@ -17,35 +43,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
17
43
  - 完善了平台检测工具
18
44
 
19
45
  ### Changed
46
+
20
47
  - 优化了BluetoothPrinter类,使其使用AdapterFactory自动选择适配器
21
48
  - 更新了README.md,添加了跨平台支持信息
22
49
  - 优化了构建配置,提高了构建效率
23
50
 
24
51
  ### Fixed
52
+
25
53
  - 修复了TypeScript错误
26
54
  - 修复了测试用例中的问题
27
55
  - 优化了代码结构,提高了代码可读性
28
56
 
29
- ## [2.0.3] - 2024-08-15
57
+ ## [2.0.3] - 2025-11-22
30
58
 
31
59
  ### Changed
60
+
32
61
  - 优化了构建配置
33
62
  - 完善了文档
34
63
 
35
- ## [2.0.2] - 2024-08-10
64
+ ## [2.0.2] - 2025-11-21
36
65
 
37
66
  ### Fixed
67
+
38
68
  - 修复了部分TypeScript错误
39
69
 
40
- ## [2.0.1] - 2024-08-05
70
+ ## [2.0.1] - 2025-11-21
41
71
 
42
72
  ### Changed
73
+
43
74
  - 优化了代码结构
44
75
  - 完善了文档
45
76
 
46
- ## [2.0.0] - 2024-08-01
77
+ ## [2.0.0] - 2025-10-25
47
78
 
48
79
  ### Added
80
+
49
81
  - 全新的架构设计
50
82
  - 支持断点续传
51
83
  - 支持弱网适配
@@ -55,13 +87,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
55
87
  - 详细的文档
56
88
 
57
89
  ### Changed
90
+
58
91
  - 重写了核心代码
59
92
  - 优化了API设计
60
93
  - 提高了性能和可靠性
61
94
 
62
- ## [1.0.0] - 2023-12-01
95
+ ## [1.0.0] - 2025-03-01
63
96
 
64
97
  ### Added
98
+
65
99
  - 初始版本
66
100
  - 基本的蓝牙打印功能
67
101
  - 支持微信小程序
package/dist/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable,n=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,s=(e,s)=>{for(var o in s||(s={}))i.call(s,o)&&n(e,o,s[o]);if(t)for(var o of t(s))r.call(s,o)&&n(e,o,s[o]);return e},o=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{c(i.next(e))}catch(t){n(t)}},o=e=>{try{c(i.throw(e))}catch(t){n(t)}},c=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);c((i=i.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var c=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.DISCONNECTING="disconnecting",e.PRINTING="printing",e.PAUSED="paused",e))(c||{}),a=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(a||{});const d=class e{static setLevel(e){this.level=e}static getLevel(){return this.level}static debug(e,...t){this.level}static info(e,...t){this.level}static warn(e,...t){this.level}static error(e,...t){this.level}static scope(t){this.prefix;return{debug:(t,...i)=>{e.level},info:(t,...i)=>{e.level},warn:(t,...i)=>{e.level},error:(t,...i)=>{e.level}}}};d.level=2,d.prefix="[TaroBTPrint]";let h=d;const l=h.scope("Encoding"),u=class{static encode(e,t="GBK"){if(!e||"string"!=typeof e)return new Uint8Array(0);const i=t.toUpperCase().replace("-","");return"UTF8"===i||"UTF-8"===i||this.warningShown||(l.warn(`Encoding ${t} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(e)}static isSupported(e){if(!e||"string"!=typeof e)return!1;const t=e.toUpperCase().replace("-","");return"UTF8"===t||"UTF-8"===t}};u.utf8Encoder=new TextEncoder,u.warningShown=!1;let g=u;class f{static toBitmap(e,t,i){if(!e||!(e instanceof Uint8Array)||t<=0||i<=0)return new Uint8Array(0);if(e.length!==t*i*4)throw new Error(`Invalid image data length: expected ${t*i*4}, got ${e.length}`);const r=Math.ceil(t/8),n=new Uint8Array(r*i),s=new Float32Array(t*i);for(let o=0;o<e.length;o+=4){const t=o/4,i=e[o]||0,r=e[o+1]||0,n=e[o+2]||0;s[t]=.299*i+.587*r+.114*n}for(let o=0;o<i;o++)for(let e=0;e<t;e++){const c=s[o*t+e]||0,a=c<128?0:255;if(0===a){const t=o*r+Math.floor(e/8),i=7-e%8;n[t]=(n[t]||0)|1<<i}const d=c-a;this.distributeError(s,t,i,e,o,d)}return n}static distributeError(e,t,i,r,n,s){const o=(o,c,a)=>{const d=r+o,h=n+c;if(d>=0&&d<t&&h>=0&&h<i){const i=h*t+d;e[i]=Math.max(0,Math.min(255,(e[i]||0)+s*a))}};o(1,0,7/16),o(-1,1,3/16),o(0,1,5/16),o(1,1,1/16)}}class E{constructor(){this.logger=h.scope("EscPos")}init(){return[new Uint8Array([27,64])]}text(e,t="GBK"){if(!e||"string"!=typeof e)return[];return[g.encode(e,t)]}feed(e=1){const t=Math.max(1,Math.min(255,Math.floor(e)));return[new Uint8Array([27,100,t])]}cut(){return[new Uint8Array([29,86,0])]}image(e,t,i){if(!e||!(e instanceof Uint8Array)||t<=0||i<=0)return[];if(e.length!==t*i*4)return this.logger.warn(`Invalid image data length: expected ${t*i*4}, got ${e.length}`),[];const r=f.toBitmap(e,t,i),n=Math.ceil(t/8),s=n%256,o=Math.floor(n/256),c=i%256,a=Math.floor(i/256);return[new Uint8Array([29,118,48,0,s,o,c,a]),r]}qr(e,t){var i,r,n,s;if(!e||"string"!=typeof e)return[];const o=null!=(i=null==t?void 0:t.model)?i:2,c=Math.max(1,Math.min(16,null!=(r=null==t?void 0:t.size)?r:6)),a=null!=(n=null==t?void 0:t.errorCorrection)?n:"M",d=[];d.push(new Uint8Array([29,40,107,4,0,49,65,1===o?49:50,0])),d.push(new Uint8Array([29,40,107,3,0,49,67,c]));const h=null!=(s={L:48,M:49,Q:50,H:51}[a])?s:49;d.push(new Uint8Array([29,40,107,3,0,49,69,h]));const l=g.encode(e,"GBK"),u=l.length+3,f=u%256,E=Math.floor(u/256);return d.push(new Uint8Array([29,40,107,f,E,49,80,48])),d.push(l),d.push(new Uint8Array([29,40,107,3,0,49,81,48])),d}}var v=(e=>(e.CONNECTION_FAILED="CONNECTION_FAILED",e.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",e.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",e.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",e.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",e.WRITE_FAILED="WRITE_FAILED",e.WRITE_TIMEOUT="WRITE_TIMEOUT",e.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",e.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",e.PRINT_JOB_FAILED="PRINT_JOB_FAILED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",e.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",e.INVALID_QR_DATA="INVALID_QR_DATA",e.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",e))(v||{});class C extends Error{constructor(e,t,i){super(t),this.code=e,this.originalError=i,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,C)}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+=`\nCaused by: ${this.originalError.message}`),e}}class I{constructor(){this.serviceCache=new Map,this.logger=h.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new C(v.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new C(v.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,r;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!=(r=null==e?void 0:e.retries)?r:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new C(v.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)}}class D extends I{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{const t=Taro.createBLEConnection({deviceId:e}),i=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([t,i]),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),Taro.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new C(v.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new C(v.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new C(v.CONNECTION_FAILED,`Failed to connect to device ${e}`,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield Taro.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield Taro.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),d=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${d} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;l<=c;)try{const t=Taro.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${d} written successfully`);break}catch(h){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new C(v.WRITE_FAILED,`Failed to write chunk ${n}/${d}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield Taro.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield Taro.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new C(v.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof C)throw t;throw new C(v.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class N extends I{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{const t=my.createBLEConnection({deviceId:e}),i=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([t,i]),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),my.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new C(v.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new C(v.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new C(v.CONNECTION_FAILED,`Failed to connect to device ${e}`,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield my.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield my.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),d=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${d} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;l<=c;)try{const t=my.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${d} written successfully`);break}catch(h){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new C(v.WRITE_FAILED,`Failed to write chunk ${n}/${d}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield my.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield my.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new C(v.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof C)throw t;throw new C(v.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class w extends I{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{const t=swan.createBLEConnection({deviceId:e}),i=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([t,i]),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),swan.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new C(v.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new C(v.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new C(v.CONNECTION_FAILED,`Failed to connect to device ${e}`,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield swan.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield swan.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),d=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${d} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;l<=c;)try{const t=swan.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${d} written successfully`);break}catch(h){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new C(v.WRITE_FAILED,`Failed to write chunk ${n}/${d}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield swan.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield swan.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new C(v.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof C)throw t;throw new C(v.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class p extends I{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{const t=tt.createBLEConnection({deviceId:e}),i=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([t,i]),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),tt.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new C(v.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new C(v.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new C(v.CONNECTION_FAILED,`Failed to connect to device ${e}`,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield tt.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield tt.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new C(v.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,a=new Uint8Array(t),d=Math.ceil(a.length/s);if(this.logger.debug(`Writing ${a.length} bytes in ${d} chunks`),0!==a.length){for(let t=0;t<a.length;t+=s){const i=a.slice(t,t+s),n=Math.floor(t/s)+1;let l=0;for(;l<=c;)try{const t=tt.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(new Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${d} written successfully`);break}catch(h){if(l++,l>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new C(v.WRITE_FAILED,`Failed to write chunk ${n}/${d}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${l}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield tt.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield tt.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new C(v.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof C)throw t;throw new C(v.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}var O=(e=>(e.WECHAT="wechat",e.ALIPAY="alipay",e.BAIDU="baidu",e.BYTEDANCE="bytedance",e.WEB="web",e.UNKNOWN="unknown",e))(O||{});class T{static create(){const e="undefined"!=typeof wx&&wx.request?"wechat":"undefined"!=typeof my&&my.request?"alipay":"undefined"!=typeof swan&&swan.request?"baidu":"undefined"!=typeof tt&&tt.request?"bytedance":"undefined"!=typeof window&&window.navigator?"web":"unknown";switch(e){case O.WECHAT:return new D;case O.ALIPAY:return new N;case O.BAIDU:return new w;case O.BYTEDANCE:return new p;default:throw new C(v.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}static createForPlatform(e){switch(e){case O.WECHAT:return new D;case O.ALIPAY:return new N;case O.BAIDU:return new w;case O.BYTEDANCE:return new p;default:throw new C(v.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported.`)}}}class y{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=r=>{t(r),this.off(e,i)};return this.on(e,i)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}emit(e,t){const i=this.listeners.get(e);if(!i||0===i.size)return;new Set(i).forEach(e=>{try{e(void 0===t&&null===t?"":t)}catch(i){}})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,i;return null!=(i=null==(t=this.listeners.get(e))?void 0:t.size)?i:0}hasListeners(e){return this.listenerCount(e)>0}}const S={adapter:{chunkSize:20,delay:20,retries:3,timeout:1e4},driver:{encoding:"GBK",paperWidth:58},logging:{level:a.WARN}};exports.BluetoothPrintError=C,exports.BluetoothPrinter=class extends y{constructor(e,t){var i,r;super(),this.deviceId=null,this.buffer=[],this.adapterOptions={},this.isPaused=!1,this.jobBuffer=null,this.jobOffset=0,this.logger=h.scope("BluetoothPrinter"),this.state=c.DISCONNECTED,this.adapter=e||T.create(),this.driver=t||new E,null==(r=(i=this.adapter).onStateChange)||r.call(i,e=>{this.state=e,this.emit("state-change",e),this.logger.debug("State changed:",e)})}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{return this.deviceId=e,yield this.adapter.connect(e),this.buffer.push(...this.driver.init()),this.emit("connected",e),this.logger.info("Connected successfully"),this}catch(t){this.deviceId=null;const e=t instanceof C?t:new C(v.CONNECTION_FAILED,"Connection failed",t);throw this.emit("error",e),e}})}disconnect(){return o(this,null,function*(){if(!this.deviceId)return void this.logger.warn("Disconnect called but no device connected");const e=this.deviceId;this.logger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.buffer=[],this.jobBuffer=null,this.jobOffset=0,this.emit("disconnected",e),this.logger.info("Disconnected successfully")}catch(t){const e=new C(v.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.emit("error",e),e}})}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.buffer.push(...this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.buffer.push(...this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.buffer.push(...this.driver.cut()),this}image(e,t,i){return this.logger.debug(`Adding image: ${t}x${i}`),this.buffer.push(...this.driver.image(e,t,i)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.buffer.push(...this.driver.qr(e,t)),this}setOptions(e){return this.adapterOptions=s(s({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions),this}pause(){this.isPaused=!0,this.state=c.PAUSED,this.emit("state-change",c.PAUSED),this.logger.info("Print job paused")}resume(){return o(this,null,function*(){if(this.isPaused&&this.jobBuffer){this.isPaused=!1,this.state=c.PRINTING,this.emit("state-change",c.PRINTING),this.logger.info("Print job resumed");try{yield this.processJob()}catch(e){const t=new C(v.PRINT_JOB_FAILED,"Failed to resume print job",e);throw this.emit("error",t),t}}else this.logger.warn("Resume called but job not paused or no job buffer")})}cancel(){this.isPaused=!1,this.jobBuffer=null,this.jobOffset=0,this.buffer=[],this.state=this.deviceId?c.CONNECTED:c.DISCONNECTED,this.emit("state-change",this.state),this.logger.info("Print job cancelled")}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:this.buffer.reduce((e,t)=>e+t.length,0)}print(){return o(this,null,function*(){if(!this.deviceId)throw new C(v.CONNECTION_FAILED,"Printer not connected. Call connect() first.");if(this.jobBuffer)throw new C(v.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");const e=this.buffer.reduce((e,t)=>e+t.length,0);this.logger.info(`Starting print job: ${e} bytes`);const t=new Uint8Array(e);let i=0;for(const n of this.buffer)t.set(n,i),i+=n.length;this.jobBuffer=t,this.jobOffset=0,this.buffer=[],this.isPaused=!1,this.state=c.PRINTING,this.emit("state-change",this.state);try{yield this.processJob(),this.isPaused?this.logger.info("Print job paused"):(this.emit("print-complete"),this.logger.info("Print job completed successfully"),this.state=c.CONNECTED,this.emit("state-change",this.state))}catch(r){const e=r instanceof C?r:new C(v.PRINT_JOB_FAILED,"Print job failed",r);throw this.emit("error",e),this.state=c.CONNECTED,this.emit("state-change",this.state),e}})}processJob(){return o(this,null,function*(){if(!this.jobBuffer||!this.deviceId)return;const e=this.jobBuffer.length,t=this.deviceId,i=this.jobBuffer;try{for(;this.jobOffset<i.length;){if(this.isPaused)return void this.logger.debug("Job paused at offset:",this.jobOffset);if(this.state!==c.CONNECTED&&this.state!==c.PRINTING&&this.state!==c.PAUSED)throw new C(v.DEVICE_DISCONNECTED,"Device disconnected during print job");const r=Math.min(this.jobOffset+512,i.length),n=i.slice(this.jobOffset,r);yield this.adapter.write(t,n.buffer,this.adapterOptions),this.jobOffset=r,this.hasListeners("progress")&&this.emit("progress",{sent:this.jobOffset,total:e})}}finally{this.jobOffset>=i.length&&(this.jobBuffer=null,this.jobOffset=0)}})}},exports.DEFAULT_CONFIG=S,exports.Encoding=g,exports.ErrorCode=v,exports.EscPos=E,exports.EventEmitter=y,exports.ImageProcessing=f,exports.LogLevel=a,exports.Logger=h,exports.PrinterState=c,exports.TaroAdapter=D,exports.mergeConfig=function(e,t){return{adapter:s(s(s({},S.adapter),e.adapter),t.adapter),driver:s(s(s({},S.driver),e.driver),t.driver),logging:s(s(s({},S.logging),e.logging),t.logging)}};
1
+ "use strict";var e=Object.defineProperty,t=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable,n=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,s=(e,s)=>{for(var o in s||(s={}))i.call(s,o)&&n(e,o,s[o]);if(t)for(var o of t(s))r.call(s,o)&&n(e,o,s[o]);return e},o=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{c(i.next(e))}catch(t){n(t)}},o=e=>{try{c(i.throw(e))}catch(t){n(t)}},c=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,o);c((i=i.apply(e,t)).next())});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var c=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.DISCONNECTING="disconnecting",e.PRINTING="printing",e.PAUSED="paused",e))(c||{});class a{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}once(e,t){const i=r=>{t(r),this.off(e,i)};return this.on(e,i)}prepend(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const i=this.listeners.get(e),r=new Set;return r.add(t),i.forEach(e=>r.add(e)),this.listeners.set(e,r),()=>this.off(e,t)}prependOnce(e,t){const i=r=>{t(r),this.off(e,i)};return this.prepend(e,i)}off(e,t){const i=this.listeners.get(e);i&&(i.delete(t),0===i.size&&this.listeners.delete(e))}emit(e,t){const i=this.listeners.get(e);i&&0!==i.size&&new Set(i).forEach(e=>{try{null==t?e():e(t)}catch(i){}})}emitAsync(e,t){return o(this,null,function*(){const i=this.listeners.get(e);if(!i||0===i.size)return;const r=new Set(i),n=[];r.forEach(e=>{n.push(new Promise(i=>{try{null==t?e():e(t)}catch(r){}finally{i()}}))}),yield Promise.all(n)})}removeAllListeners(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,i;return null!=(i=null==(t=this.listeners.get(e))?void 0:t.size)?i:0}getListeners(e){const t=this.listeners.get(e);return t?Array.from(t):[]}eventNames(){return Array.from(this.listeners.keys())}hasListeners(e){return this.listenerCount(e)>0}}var l=(e=>(e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE",e))(l||{});const h=class e{static configure(e){this.config=s(s({},this.config),e)}static setLevel(e){this.config.level=e}static getLevel(){return this.config.level}static formatPrefix(e,t){return`${t?`${this.config.prefix}:${t}`:this.config.prefix} [${{0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"NONE"}[e]}]`}static formatMessage(e,t,i,r){return`${this.formatPrefix(e,r)} ${t}`}static log(e,t,i,r){if(this.config.level>e)return;this.formatPrefix(e,r);const n=this.formatMessage(e,t,i,r),s={level:e,message:t,args:i,timestamp:new Date,scope:r,formatted:n};this.config.handler&&this.config.handler(s)}static debug(e,...t){this.log(0,e,t)}static info(e,...t){this.log(1,e,t)}static warn(e,...t){this.log(2,e,t)}static error(e,...t){this.log(3,e,t)}static scope(t){return{debug:(i,...r)=>{e.log(0,i,r,t)},info:(i,...r)=>{e.log(1,i,r,t)},warn:(i,...r)=>{e.log(2,i,r,t)},error:(i,...r)=>{e.log(3,i,r,t)}}}};h.config={level:2,prefix:"[TaroBTPrint]"};let u=h;var d=(e=>(e.CONNECTION_FAILED="CONNECTION_FAILED",e.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.DEVICE_DISCONNECTED="DEVICE_DISCONNECTED",e.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",e.CHARACTERISTIC_NOT_FOUND="CHARACTERISTIC_NOT_FOUND",e.SERVICE_DISCOVERY_FAILED="SERVICE_DISCOVERY_FAILED",e.WRITE_FAILED="WRITE_FAILED",e.WRITE_TIMEOUT="WRITE_TIMEOUT",e.PRINT_JOB_IN_PROGRESS="PRINT_JOB_IN_PROGRESS",e.PRINT_JOB_CANCELLED="PRINT_JOB_CANCELLED",e.PRINT_JOB_FAILED="PRINT_JOB_FAILED",e.INVALID_CONFIGURATION="INVALID_CONFIGURATION",e.ENCODING_NOT_SUPPORTED="ENCODING_NOT_SUPPORTED",e.INVALID_IMAGE_DATA="INVALID_IMAGE_DATA",e.INVALID_QR_DATA="INVALID_QR_DATA",e.PLATFORM_NOT_SUPPORTED="PLATFORM_NOT_SUPPORTED",e))(d||{});class f extends Error{constructor(e,t,i){super(t),this.code=e,this.originalError=i,this.name="BluetoothPrintError",Error.captureStackTrace&&Error.captureStackTrace(this,f)}toString(){let e=`${this.name} [${this.code}]: ${this.message}`;return this.originalError&&(e+="\nCaused by: "+this.originalError.message),e}}var g=function(){return function(e){this.name=e}}(),p=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(t,i)};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),v=function(e){function t(t){var i,r,n=e.call(this)||this;return n.name="ServiceNotFoundError",n.normalizedIdentifier="<UNKNOWN_IDENTIFIER>","string"==typeof t?n.normalizedIdentifier=t:t instanceof g?n.normalizedIdentifier="Token<"+(t.name||"UNSET_NAME")+">":t&&(t.name||(null===(i=t.prototype)||void 0===i?void 0:i.name))&&(n.normalizedIdentifier="MaybeConstructable<"+t.name+">"||"MaybeConstructable<"+(null===(r=t.prototype)||void 0===r?void 0:r.name)+">"),n}return p(t,e),Object.defineProperty(t.prototype,"message",{get:function(){return'Service with "'+this.normalizedIdentifier+'" identifier was not found in the container. Register it before usage via explicitly calling the "Container.set" function or using the "@Service()" decorator.'},enumerable:!1,configurable:!0}),t}(Error),E=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(t,i)};return function(t,i){function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),I=function(e){function t(t){var i,r,n=e.call(this)||this;return n.name="CannotInstantiateValueError",n.normalizedIdentifier="<UNKNOWN_IDENTIFIER>","string"==typeof t?n.normalizedIdentifier=t:t instanceof g?n.normalizedIdentifier="Token<"+(t.name||"UNSET_NAME")+">":t&&(t.name||(null===(i=t.prototype)||void 0===i?void 0:i.name))&&(n.normalizedIdentifier="MaybeConstructable<"+t.name+">"||"MaybeConstructable<"+(null===(r=t.prototype)||void 0===r?void 0:r.name)+">"),n}return E(t,e),Object.defineProperty(t.prototype,"message",{get:function(){return'Cannot instantiate the requested value for the "'+this.normalizedIdentifier+"\" identifier. The related metadata doesn't contain a factory or a type to instantiate."},enumerable:!1,configurable:!0}),t}(Error),C=Symbol(),y=function(){return y=Object.assign||function(e){for(var t,i=1,r=arguments.length;r>i;i++)for(var n in t=arguments[i])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e},y.apply(this,arguments)},w=function(){function e(e){this.services=[],this.id=e}return e.prototype.has=function(e){return!!this.findService(e)},e.prototype.get=function(e){var t=D.of(void 0),i=t.findService(e),r=this.findService(e);if(i&&!0===i.global)return this.getServiceValue(i);if(r)return this.getServiceValue(r);if(i&&this!==t){var n=y({},i);n.value=C,this.set(n);var s=this.getServiceValue(n);return this.set(y(y({},n),{value:s})),s}if(i)return this.getServiceValue(i);throw new v(e)},e.prototype.getMany=function(e){var t=this;return this.findAllServices(e).map(function(e){return t.getServiceValue(e)})},e.prototype.set=function(e,t){var i=this;if(e instanceof Array)return e.forEach(function(e){return i.set(e)}),this;if("string"==typeof e||e instanceof g)return this.set({id:e,type:null,value:t,factory:void 0,global:!1,multiple:!1,eager:!1,transient:!1});if("function"==typeof e)return this.set({id:e,type:e,value:t,factory:void 0,global:!1,multiple:!1,eager:!1,transient:!1});var r=y({id:new g("UNREACHABLE"),type:null,factory:void 0,value:C,global:!1,multiple:!1,eager:!1,transient:!1},e),n=this.findService(r.id);return n&&!0!==n.multiple?Object.assign(n,r):this.services.push(r),r.eager&&this.get(r.id),this},e.prototype.remove=function(e){var t=this;return Array.isArray(e)?e.forEach(function(e){return t.remove(e)}):this.services=this.services.filter(function(i){return i.id!==e||(t.destroyServiceInstance(i),!1)}),this},e.prototype.reset=function(e){var t=this;switch(void 0===e&&(e={strategy:"resetValue"}),e.strategy){case"resetValue":this.services.forEach(function(e){return t.destroyServiceInstance(e)});break;case"resetServices":this.services.forEach(function(e){return t.destroyServiceInstance(e)}),this.services=[];break;default:throw Error("Received invalid reset strategy.")}return this},e.prototype.findAllServices=function(e){return this.services.filter(function(t){return t.id===e})},e.prototype.findService=function(e){return this.services.find(function(t){return t.id===e})},e.prototype.getServiceValue=function(e){var t,i=C;if(e.value!==C)return e.value;if(!e.factory&&!e.type)throw new I(e.id);if(e.factory)if(e.factory instanceof Array){var r=void 0;try{r=this.get(e.factory[0])}catch(c){if(!(c instanceof v))throw c;r=new e.factory[0]}i=r[e.factory[1]](this,e.id)}else i=e.factory(this,e.id);if(!e.factory&&e.type){var n=e.type,s=(null===(t=Reflect)||void 0===t?void 0:t.getMetadata("design:paramtypes",n))||[],o=this.initializeParams(n,s);o.push(this),i=new(n.bind.apply(n,function(){for(var e=0,t=0,i=arguments.length;i>t;t++)e+=arguments[t].length;var r=Array(e),n=0;for(t=0;i>t;t++)for(var s=arguments[t],o=0,c=s.length;c>o;o++,n++)r[n]=s[o];return r}([void 0],o)))}if(e.transient||i===C||(e.value=i),i===C)throw new I(e.id);return e.type&&this.applyPropertyHandlers(e.type,i),i},e.prototype.initializeParams=function(e,t){var i=this;return t.map(function(t,r){var n=D.handlers.find(function(t){return(t.object===e||t.object===Object.getPrototypeOf(e))&&t.index===r});return n?n.value(i):t&&t.name&&!i.isPrimitiveParamType(t.name)?i.get(t):void 0})},e.prototype.isPrimitiveParamType=function(e){return["string","boolean","number","object"].includes(e.toLowerCase())},e.prototype.applyPropertyHandlers=function(e,t){var i=this;D.handlers.forEach(function(r){"number"!=typeof r.index&&(r.object.constructor===e||e.prototype instanceof r.object.constructor)&&r.propertyName&&(t[r.propertyName]=r.value(i))})},e.prototype.destroyServiceInstance=function(e,t){if(void 0===t&&(t=!1),t||e.type||e.factory){if("function"==typeof(null==e?void 0:e.value).destroy)try{e.value.destroy()}catch(i){}e.value=C}},e}(),D=function(){function e(){}return e.of=function(e){if(void 0===e&&(e="default"),"default"===e)return this.globalInstance;var t=this.instances.find(function(t){return t.id===e});return t||(t=new w(e),this.instances.push(t)),t},e.has=function(e){return this.globalInstance.has(e)},e.get=function(e){return this.globalInstance.get(e)},e.getMany=function(e){return this.globalInstance.getMany(e)},e.set=function(e,t){return this.globalInstance.set(e,t),this},e.remove=function(e){return this.globalInstance.remove(e),this},e.reset=function(e){if(void 0===e&&(e="default"),"default"==e)this.globalInstance.reset(),this.instances.forEach(function(e){return e.reset()});else{var t=this.instances.find(function(t){return t.id===e});t&&(t.reset(),this.instances.splice(this.instances.indexOf(t),1))}return this},e.registerHandler=function(e){return this.handlers.push(e),this},e.import=function(e){return this},e.handlers=[],e.globalInstance=new w("default"),e.instances=[],e}();function N(e){return function(t){var i={id:t,type:t,factory:void 0,multiple:!1,global:!1,eager:!1,transient:!1,value:C};(e instanceof g||"string"==typeof e)&&(i.id=e),D.set(i)}}class m{constructor(){this.serviceCache=new Map,this.logger=u.scope("BaseAdapter")}onStateChange(e){this.stateCallback=e}updateState(e){this.stateCallback&&this.stateCallback(e)}validateDeviceId(e){if(!e||"string"!=typeof e)throw new f(d.DEVICE_NOT_FOUND,"Invalid device ID provided")}validateBuffer(e){if(!(e&&e instanceof ArrayBuffer))throw new f(d.PRINT_JOB_FAILED,"Invalid buffer data provided")}validateOptions(e){var t,i,r;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!=(r=null==e?void 0:e.retries)?r:3))}}getServiceInfo(e){const t=this.serviceCache.get(e);if(!t)throw new f(d.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)}}class O extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=Taro.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),Taro.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield Taro.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield Taro.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,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),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=Taro.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield Taro.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield Taro.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class b extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=my.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),my.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield my.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield my.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,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),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=my.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield my.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield my.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class T extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=swan.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),swan.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield swan.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield swan.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,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),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=swan.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield swan.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield swan.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}class S extends m{connect(e){return o(this,null,function*(){if(this.validateDeviceId(e),this.isDeviceConnected(e))return this.logger.warn("Device already connected:",e),void this.updateState(c.CONNECTED);this.updateState(c.CONNECTING),this.logger.debug("Connecting to device:",e);try{let t;const i=tt.createBLEConnection({deviceId:e}),r=new Promise((e,i)=>{t=setTimeout(()=>{i(Error("Connection timeout after 10 seconds"))},1e4)});yield Promise.race([i,r]),t&&clearTimeout(t),this.logger.info("BLE connection established"),yield this.discoverServices(e),this.updateState(c.CONNECTED),this.logger.info("Device connected successfully"),tt.onBLEConnectionStateChange(t=>{t.deviceId!==e||t.connected||(this.logger.warn("Device disconnected unexpectedly"),this.updateState(c.DISCONNECTED),this.cleanupDevice(e))})}catch(t){this.updateState(c.DISCONNECTED),this.logger.error("Connection failed:",t);const i=t.message||"";if(i.includes("timeout"))throw new f(d.CONNECTION_TIMEOUT,`Connection to device ${e} timed out`,t);if(i.includes("not found"))throw new f(d.DEVICE_NOT_FOUND,`Device ${e} not found`,t);throw new f(d.CONNECTION_FAILED,"Failed to connect to device "+e,t)}})}disconnect(e){return o(this,null,function*(){this.validateDeviceId(e),this.updateState(c.DISCONNECTING),this.logger.debug("Disconnecting from device:",e);try{yield tt.closeBLEConnection({deviceId:e}),this.cleanupDevice(e),this.updateState(c.DISCONNECTED),this.logger.info("Device disconnected successfully")}catch(t){this.logger.warn("Disconnect error (ignored):",t),this.cleanupDevice(e),this.updateState(c.DISCONNECTED)}})}write(e,t,i){return o(this,null,function*(){this.validateDeviceId(e),this.validateBuffer(t);const r=this.getServiceInfo(e),n=this.validateOptions(i);try{if(!(yield tt.getBLEConnectionState({deviceId:e})).connected)throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected")}catch(h){throw this.cleanupDevice(e),new f(d.DEVICE_DISCONNECTED,"Device disconnected",h)}const{chunkSize:s,delay:o,retries:c}=n,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),n=Math.floor(t/s)+1;let u=0;for(;c>=u;)try{const t=tt.writeBLECharacteristicValue({deviceId:e,serviceId:r.serviceId,characteristicId:r.characteristicId,value:i.buffer}),s=new Promise((e,t)=>{setTimeout(()=>{t(Error("Write timeout after 5 seconds"))},5e3)});yield Promise.race([t,s]),this.logger.debug(`Chunk ${n}/${l} written successfully`);break}catch(h){if(u++,u>c)throw this.logger.error(`Chunk ${n} failed after ${c} retries`),new f(d.WRITE_FAILED,`Failed to write chunk ${n}/${l}`,h);this.logger.warn(`Chunk ${n} write failed, retry ${u}/${c}`),yield new Promise(e=>setTimeout(e,2*o))}t+s<a.length&&(yield new Promise(e=>setTimeout(e,o)))}this.logger.info(`Successfully wrote ${a.length} bytes`)}else this.logger.warn("No data to write")})}discoverServices(e){return o(this,null,function*(){this.logger.debug("Discovering services for device:",e);try{const t=yield tt.getBLEDeviceServices({deviceId:e});for(const i of t.services){const t=(yield tt.getBLEDeviceCharacteristics({deviceId:e,serviceId:i.uuid})).characteristics.find(e=>e.properties.write||e.properties.writeWithoutResponse);if(t)return this.serviceCache.set(e,{serviceId:i.uuid,characteristicId:t.uuid}),void this.logger.info("Found writeable characteristic:",{service:i.uuid,characteristic:t.uuid})}throw new f(d.CHARACTERISTIC_NOT_FOUND,"No writeable characteristic found. Make sure the device is a supported printer.")}catch(t){if(t instanceof f)throw t;throw new f(d.SERVICE_DISCOVERY_FAILED,"Failed to discover device services",t)}})}}var _=(e=>(e.WECHAT="wechat",e.ALIPAY="alipay",e.BAIDU="baidu",e.BYTEDANCE="bytedance",e.WEB="web",e.UNKNOWN="unknown",e))(_||{});function P(e){return"object"==typeof e&&null!==e&&"request"in e}class A{static create(){const e="undefined"!=typeof wx&&P(wx)?"wechat":"undefined"!=typeof my&&P(my)?"alipay":"undefined"!=typeof swan&&P(swan)?"baidu":"undefined"!=typeof tt&&P(tt)?"bytedance":"undefined"!=typeof window&&"object"==typeof(t=window)&&null!==t&&"navigator"in t?"web":"unknown";var t;switch(e){case _.WECHAT:return new O;case _.ALIPAY:return new b;case _.BAIDU:return new T;case _.BYTEDANCE:return new S;default:throw new f(d.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported. Please use a supported mini-program platform.`)}}static createForPlatform(e){switch(e){case _.WECHAT:return new O;case _.ALIPAY:return new b;case _.BAIDU:return new T;case _.BYTEDANCE:return new S;default:throw new f(d.PLATFORM_NOT_SUPPORTED,`Platform ${e} is not supported.`)}}}let B=class{constructor(e){var t,i;this.deviceId=null,this.state=c.DISCONNECTED,this.logger=u.scope("ConnectionManager"),this.adapter=e||A.create(),null==(i=(t=this.adapter).onStateChange)||i.call(t,e=>{this.state=e,this.logger.debug("State changed:",e)})}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{this.deviceId=e,yield this.adapter.connect(e),this.state=c.CONNECTED,this.logger.info("Connected successfully")}catch(t){this.deviceId=null,this.state=c.DISCONNECTED;const e=t instanceof f?t:new f(d.CONNECTION_FAILED,"Connection failed",t);throw this.logger.error("Connection failed:",e),e}})}disconnect(){return o(this,null,function*(){if(!this.deviceId)return void this.logger.warn("Disconnect called but no device connected");const e=this.deviceId;this.logger.info("Disconnecting from device:",e);try{yield this.adapter.disconnect(e),this.deviceId=null,this.state=c.DISCONNECTED,this.logger.info("Disconnected successfully")}catch(t){const e=new f(d.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.logger.error("Disconnect failed:",e),e}})}isConnected(){return this.state===c.CONNECTED}getDeviceId(){return this.deviceId}getState(){return this.state}getAdapter(){return this.adapter}};B=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],B);let M=class{constructor(e,t){if(this.jobBuffer=null,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!1,this.adapterOptions={},this.logger=u.scope("PrintJobManager"),t)this.connectionManager=e,this.adapter=t;else if(e&&"function"==typeof e.connect)this.adapter=e,this.connectionManager={getDeviceId:()=>"test-device",isConnected:()=>!0,getState:()=>c.CONNECTED,connect:()=>Promise.resolve(),disconnect:()=>Promise.resolve(),getAdapter:()=>this.adapter};else{if(this.connectionManager=e,!this.connectionManager||"function"!=typeof this.connectionManager.getAdapter)throw Error("Printer adapter not provided and could not be retrieved from connection manager");this.adapter=this.connectionManager.getAdapter()}}start(e){return o(this,null,function*(){if(this._isInProgress)throw new f(d.PRINT_JOB_IN_PROGRESS,"A print job is already in progress. Wait for completion or cancel it.");this.logger.info(`Starting print job: ${e.length} bytes`),this.jobBuffer=e,this.jobOffset=0,this._isPaused=!1,this._isInProgress=!0;try{yield this.processJob(),this._isPaused?this.logger.info("Print job paused"):(this.logger.info("Print job completed successfully"),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0)}catch(t){throw this.logger.error("Print job failed:",t),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,t instanceof f?t:new f(d.PRINT_JOB_FAILED,"Print job failed",t)}})}pause(){this._isInProgress?(this._isPaused=!0,this.logger.info("Print job paused")):this.logger.warn("Pause called but no print job in progress")}resume(){return o(this,null,function*(){if(this._isInProgress&&this._isPaused){this._isPaused=!1,this.logger.info("Print job resumed");try{yield this.processJob(),this._isPaused||(this.logger.info("Print job completed successfully"),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0)}catch(e){throw this.logger.error("Print job failed after resume:",e),this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,e instanceof f?e:new f(d.PRINT_JOB_FAILED,"Print job failed",e)}}else this.logger.warn("Resume called but no paused print job")})}cancel(){this._isInProgress?(this._isPaused=!1,this._isInProgress=!1,this.jobBuffer=null,this.jobOffset=0,this.logger.info("Print job cancelled")):this.logger.warn("Cancel called but no print job in progress")}remaining(){return this.jobBuffer?this.jobBuffer.length-this.jobOffset:0}isPaused(){return this._isPaused}isInProgress(){return this._isInProgress}setOptions(e){this.adapterOptions=s(s({},this.adapterOptions),e),this.logger.debug("Adapter options updated:",this.adapterOptions)}processJob(){return o(this,null,function*(){if(!this.jobBuffer)return;if(!this.adapter||"function"!=typeof this.adapter.write)throw new f(d.INVALID_CONFIGURATION,"Printer adapter does not support write operation");const e=this.jobBuffer.length,t=this.jobBuffer;try{for(;this.jobOffset<t.length;){if(this._isPaused)return void this.logger.debug("Job paused at offset:",this.jobOffset);const i=Math.min(this.jobOffset+512,t.length),r=t.slice(this.jobOffset,i);yield this.adapter.write(this.getDeviceId(),r.buffer,this.adapterOptions),this.jobOffset=i,this.logger.debug(`Processed ${this.jobOffset}/${e} bytes`)}}catch(i){throw this.logger.error("Error processing job:",i),i}})}getDeviceId(){const e=this.connectionManager.getDeviceId();if(!e)throw new f(d.DEVICE_DISCONNECTED,"Device ID not available");return e}};M=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],M);const R=u.scope("Encoding"),L=class{static configure(e){this.config=s(s({},this.config),e)}static encode(e,t="GBK"){if(!e||"string"!=typeof e)return new Uint8Array(0);const i=t.toUpperCase().replace("-","");return"UTF8"===i||"UTF-8"===i||this.config.showWarnings&&!this.warningShown&&(R.warn(`Encoding ${t} not yet fully implemented, falling back to UTF-8. This may cause display issues with some printers.`),this.warningShown=!0),this.utf8Encoder.encode(e)}static isSupported(e){if(!e||"string"!=typeof e)return!1;const t=e.toUpperCase().replace("-","");return"UTF8"===t||"UTF-8"===t}};L.utf8Encoder=new TextEncoder,L.warningShown=!1,L.config={showWarnings:!0};let F=L;class ${static toBitmap(e,t,i){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return new Uint8Array(0);if(e.length!==t*i*4)throw Error(`Invalid image data length: expected ${t*i*4}, got ${e.length}`);const r=Math.ceil(t/8),n=new Uint8Array(r*i),s=new Float32Array(t*i);for(let o=0;o<e.length;o+=4){const t=o/4,i=e[o]||0,r=e[o+1]||0,n=e[o+2]||0;s[t]=.299*i+.587*r+.114*n}for(let o=0;i>o;o++)for(let e=0;t>e;e++){const c=s[o*t+e]||0,a=128>c?0:255;if(0===a){const t=o*r+Math.floor(e/8),i=7-e%8;n[t]=(n[t]||0)|1<<i}const l=c-a;this.distributeError(s,t,i,e,o,l)}return n}static distributeError(e,t,i,r,n,s){const o=(o,c,a)=>{const l=r+o,h=n+c;if(l>=0&&t>l&&h>=0&&i>h){const i=h*t+l;e[i]=Math.max(0,Math.min(255,(e[i]||0)+s*a))}};o(1,0,7/16),o(-1,1,3/16),o(0,1,5/16),o(1,1,1/16)}}class j{constructor(){this.logger=u.scope("EscPos")}init(){return[new Uint8Array([27,64])]}text(e,t="GBK"){return e&&"string"==typeof e?[F.encode(e,t)]:[]}feed(e=1){return[new Uint8Array([27,100,Math.max(1,Math.min(255,Math.floor(e)))])]}cut(){return[new Uint8Array([29,86,0])]}image(e,t,i){if(!(e&&e instanceof Uint8Array&&t>0&&i>0))return[];if(e.length!==t*i*4)return this.logger.warn(`Invalid image data length: expected ${t*i*4}, got ${e.length}`),[];const r=$.toBitmap(e,t,i),n=Math.ceil(t/8);return[new Uint8Array([29,118,48,0,n%256,Math.floor(n/256),i%256,Math.floor(i/256)]),r]}qr(e,t){var i,r,n,s;if(!e||"string"!=typeof e)return[];const o=null!=(i=null==t?void 0:t.model)?i:2,c=Math.max(1,Math.min(16,null!=(r=null==t?void 0:t.size)?r:6)),a=null!=(n=null==t?void 0:t.errorCorrection)?n:"M",l=[];l.push(new Uint8Array([29,40,107,4,0,49,65,1===o?49:50,0])),l.push(new Uint8Array([29,40,107,3,0,49,67,c]));const h=null!=(s={L:48,M:49,Q:50,H:51}[a])?s:49;l.push(new Uint8Array([29,40,107,3,0,49,69,h]));const u=F.encode(e,"GBK"),d=u.length+3,f=d%256,g=Math.floor(d/256);return l.push(new Uint8Array([29,40,107,f,g,49,80,48])),l.push(u),l.push(new Uint8Array([29,40,107,3,0,49,81,48])),l}}let U=class{constructor(e){this.buffer=[],this.logger=u.scope("CommandBuilder"),this.driver=e||new j,this.buffer.push(...this.driver.init())}text(e,t){return this.logger.debug("Adding text:",e.substring(0,50)),this.buffer.push(...this.driver.text(e,t)),this}feed(e=1){return this.logger.debug("Adding feed:",e),this.buffer.push(...this.driver.feed(e)),this}cut(){return this.logger.debug("Adding cut command"),this.buffer.push(...this.driver.cut()),this}image(e,t,i){return this.logger.debug(`Adding image: ${t}x${i}`),this.buffer.push(...this.driver.image(e,t,i)),this}qr(e,t){return this.logger.debug("Adding QR code:",e.substring(0,50)),this.buffer.push(...this.driver.qr(e,t)),this}clear(){return this.logger.debug("Clearing buffer"),this.buffer=[],this.buffer.push(...this.driver.init()),this}getBuffer(){const e=this.buffer.reduce((e,t)=>e+t.length,0),t=new Uint8Array(e);let i=0;for(const r of this.buffer)t.set(r,i),i+=r.length;return t}getTotalBytes(){return this.buffer.reduce((e,t)=>e+t.length,0)}};U=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],U);exports.BluetoothPrinter=class extends a{constructor(e,t,i){if(super(),this.logger=u.scope("BluetoothPrinter"),this.state=c.DISCONNECTED,e&&"function"==typeof e.connect){const i=e,r=t;this.connectionManager=new B(i),this.printJobManager=new M(this.connectionManager,i),this.commandBuilder=new U(r)}else this.connectionManager=e,this.printJobManager=t,this.commandBuilder=i,this.connectionManager||(this.connectionManager=new B,this.printJobManager=new M(this.connectionManager),this.commandBuilder=new U);this.updateState()}updateState(){let e;e=this.connectionManager&&"function"==typeof this.connectionManager.getState?this.connectionManager.getState():c.CONNECTED;let t=!1,i=!1;this.printJobManager&&(t="function"==typeof this.printJobManager.isInProgress&&this.printJobManager.isInProgress(),i="function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()),this.state=i?c.PAUSED:t?c.PRINTING:e,this.emit("state-change",this.state),this.logger.debug("State updated:",this.state)}connect(e){return o(this,null,function*(){this.logger.info("Connecting to device:",e);try{return yield this.connectionManager.connect(e),this.updateState(),this.emit("connected",e),this.logger.info("Connected successfully"),this}catch(t){const e=t instanceof f?t:new f(d.CONNECTION_FAILED,"Connection failed",t);throw this.emit("error",e),this.updateState(),e}})}disconnect(){return o(this,null,function*(){const e=this.connectionManager.getDeviceId();if(e){this.logger.info("Disconnecting from device:",e);try{yield this.connectionManager.disconnect(),this.printJobManager.cancel(),this.updateState(),this.emit("disconnected",e),this.logger.info("Disconnected successfully")}catch(t){const e=new f(d.DEVICE_DISCONNECTED,"Disconnect failed",t);throw this.emit("error",e),this.updateState(),e}}else this.logger.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,i){return this.commandBuilder.image(e,t,i),this}qr(e,t){return this.commandBuilder.qr(e,t),this}setOptions(e){return this.printJobManager.setOptions(e),this}pause(){this.printJobManager.pause(),this.updateState(),this.logger.info("Print job paused")}resume(){return o(this,null,function*(){this.logger.info("Resuming print job");try{yield this.printJobManager.resume(),this.updateState(),this.logger.info("Print job resumed")}catch(e){const t=new f(d.PRINT_JOB_FAILED,"Failed to resume print job",e);throw this.emit("error",t),this.updateState(),t}})}cancel(){this.printJobManager.cancel(),this.commandBuilder.clear(),this.updateState(),this.logger.info("Print job cancelled")}remaining(){return this.printJobManager.remaining()}print(){return o(this,null,function*(){if(!this.connectionManager.isConnected())throw new f(d.CONNECTION_FAILED,"Printer not connected. Call connect() first.");const e=this.commandBuilder.getBuffer();this.logger.info(`Starting print job: ${e.length} bytes`),this.commandBuilder.clear(),this.updateState();try{yield this.printJobManager.start(e),"function"==typeof this.printJobManager.isPaused&&this.printJobManager.isPaused()?this.logger.info("Print job paused"):(this.emit("print-complete"),this.logger.info("Print job completed successfully"))}catch(t){this.logger.error("Print job failed with error:",t);const e=t instanceof f?t:new f(d.PRINT_JOB_FAILED,"Print job failed",t);throw this.emit("error",e),e}finally{this.updateState()}})}},exports.BluetoothPrinter=((e,t)=>{for(var i,r=t,n=e.length-1;n>=0;n--)(i=e[n])&&(r=i(r)||r);return r})([N()],exports.BluetoothPrinter);const x={adapter:{chunkSize:20,delay:20,retries:3,timeout:1e4},driver:{encoding:"GBK",paperWidth:58},logging:{level:l.WARN}};exports.BluetoothPrintError=f,exports.DEFAULT_CONFIG=x,exports.Encoding=F,exports.ErrorCode=d,exports.EscPos=j,exports.EventEmitter=a,exports.ImageProcessing=$,exports.LogLevel=l,exports.Logger=u,exports.PrinterState=c,exports.TaroAdapter=O,exports.mergeConfig=function(e,t){return{adapter:s(s(s({},x.adapter),e.adapter),t.adapter),driver:s(s(s({},x.driver),e.driver),t.driver),logging:s(s(s({},x.logging),e.logging),t.logging)}};