@munchi_oy/react-native-epson-printer 1.0.3 → 1.0.5

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/README.md CHANGED
@@ -1,43 +1,105 @@
1
1
  # @munchi_oy/react-native-epson-printer
2
2
 
3
- Epson printer SDK bridge for React Native.
3
+ Epson printer SDK bridge for React Native (iOS + Android).
4
+
5
+ ## Installation (version-pinned recommended)
6
+
7
+ Use an explicit version instead of `latest` to keep production builds predictable.
8
+
9
+ ```bash
10
+ npm install @munchi_oy/react-native-epson-printer@1.0.3
11
+ # or
12
+ pnpm add @munchi_oy/react-native-epson-printer@1.0.3
13
+ # or
14
+ yarn add @munchi_oy/react-native-epson-printer@1.0.3
15
+ ```
16
+
17
+ Recommended policy:
18
+ - Pin to an exact version in production.
19
+ - Upgrade intentionally after validating printers on staging.
4
20
 
5
21
  ## Overview
6
22
 
7
23
  This package provides:
8
24
  - Epson discovery (`discoverPrinters`)
9
25
  - Epson connection lifecycle (`connect`, `disconnect`, connection events)
10
- - Epson print queueing and hardware-recovery retries
11
- - Receipt printing with generic `PrintJob` commands and embedded payload support
26
+ - Serialized print queue with retry + recovery behavior
27
+ - Receipt printing via generic `PrintJob` commands
28
+ - Embedded payload printing (`printEmbedded`)
29
+ - Cash drawer pulse (`openDrawer`)
12
30
 
13
31
  This package does not include Star or Sunmi drivers.
14
32
 
15
- ## Installation
33
+ ## Behavior Support (implemented)
16
34
 
17
- ```bash
18
- npm install @munchi_oy/react-native-epson-printer
19
- # or
20
- pnpm add @munchi_oy/react-native-epson-printer
35
+ | Behavior | Status | Details |
36
+ | :--- | :--- | :--- |
37
+ | Session-isolated instances | Implemented | Each `getPrinter(...)` instance owns a native `sessionId`; events are routed by session. |
38
+ | Target conflict protection | Implemented | Concurrent active usage of the same target returns `TARGET_IN_USE`. |
39
+ | Serialized job queue | Implemented | `connect`, `print`, and `disconnect` are queued to avoid race conditions per instance. |
40
+ | Hardware-error pause/resume | Implemented | Hardware failures pause queue; queue resumes when recovery is detected via status events and polling. |
41
+ | Retry for transient busy/timeout states | Implemented | Native operations retry for retryable states (`BUSY`, `IN_USE`, timeout-family errors). |
42
+ | Print receive timeout guard | Implemented | Native print call fails with `PRINT_TIMEOUT` if printer callback does not return within 30s. |
43
+ | iOS stale-session recovery | Implemented | One-shot session recovery + reconnect + retry for stale/busy/offline connection scenarios. |
44
+ | Post-print auto-disconnect | Implemented | JS driver schedules disconnect after 5s idle after print completion. |
45
+ | Android warm reconnect cache | Implemented | Native Android keeps a short-lived connection cache (up to 120s) for faster reconnect. |
46
+ | Discovery cleanup/filtering | Implemented | Duplicate targets are deduped and Epson sub-devices such as `[local_display]` are filtered out. |
47
+
48
+ ## Multi-instance (one tablet -> many printers)
49
+
50
+ Yes, this is supported.
51
+
52
+ - Create one printer instance per physical target.
53
+ - Run them in parallel if needed.
54
+ - Do not connect two active instances to the same target at the same time (`TARGET_IN_USE`).
55
+
56
+ ```ts
57
+ import { EpsonModel, getPrinter } from '@munchi_oy/react-native-epson-printer';
58
+
59
+ const kitchenPrinter = getPrinter({
60
+ target: 'BT:00:01:90:7B:5A:11',
61
+ model: EpsonModel.TM_M30III,
62
+ });
63
+
64
+ const receiptPrinter = getPrinter({
65
+ target: 'TCP:192.168.1.50',
66
+ model: EpsonModel.TM_M30III,
67
+ });
68
+
69
+ await Promise.all([
70
+ kitchenPrinter.connect(),
71
+ receiptPrinter.connect(),
72
+ ]);
73
+
74
+ await Promise.all([
75
+ kitchenPrinter.print({ commands: [{ type: 'text', text: 'Kitchen ticket\n' }, { type: 'cut' }] }),
76
+ receiptPrinter.print({ commands: [{ type: 'text', text: 'Customer receipt\n' }, { type: 'cut' }] }),
77
+ ]);
78
+
79
+ await Promise.all([
80
+ kitchenPrinter.disconnect(),
81
+ receiptPrinter.disconnect(),
82
+ ]);
21
83
  ```
22
84
 
23
85
  ## iOS Setup
24
86
 
25
- 1. Add the package.
26
- 2. Run CocoaPods install in your iOS project:
87
+ 1. Install the package.
88
+ 2. Run CocoaPods install:
27
89
 
28
90
  ```bash
29
91
  cd ios && pod install
30
92
  ```
31
93
 
32
- 3. Ensure Bluetooth/network permissions are configured in `Info.plist` for your transport mode.
94
+ 3. Configure `Info.plist` permissions based on your connection method (Bluetooth/TCP).
33
95
 
34
96
  ## Android Setup
35
97
 
36
- 1. Add the package and sync Gradle.
37
- 2. Ensure runtime permissions are requested in your app before discovery/connection:
98
+ 1. Install the package and sync Gradle.
99
+ 2. Request runtime permissions before discovery/connection:
38
100
  - Android 12+ (`API 31+`): `BLUETOOTH_SCAN`, `BLUETOOTH_CONNECT`
39
- - Android 11 and below: location permission for Bluetooth discovery (`ACCESS_FINE_LOCATION`)
40
- 3. Rebuild the Android app after installation.
101
+ - Android 11 and below: `ACCESS_FINE_LOCATION` (Bluetooth discovery)
102
+ 3. Rebuild the app.
41
103
 
42
104
  ## Quick Start
43
105
 
@@ -67,9 +129,9 @@ await printer.disconnect();
67
129
  | Field | Type | Required | Description |
68
130
  | :--- | :--- | :--- | :--- |
69
131
  | `model` | `EpsonModel` | Yes | Epson printer series passed to native init |
70
- | `target` | `string` | No | Default target (for `connect()` without args) |
71
- | `lang` | `Epos2Lang` | No | Language enum used by native printer object |
72
- | `logger` | `PrinterLogger` | No | SDK logger hook (`error`, optional `info`) |
132
+ | `target` | `string` | No | Default target used by `connect()` when no target is passed |
133
+ | `lang` | `Epos2Lang` | No | Language enum for native printer object |
134
+ | `logger` | `PrinterLogger` | No | Per-instance logger (`error`, optional `info`) |
73
135
 
74
136
  ## Discovery
75
137
 
@@ -78,31 +140,38 @@ Use discovery as a standalone API:
78
140
  ```ts
79
141
  import { discoverPrinters } from '@munchi_oy/react-native-epson-printer';
80
142
 
81
- const printers = await discoverPrinters({ timeout: 5000, connectionType: 'bluetooth' });
143
+ const printers = await discoverPrinters({
144
+ timeout: 5000,
145
+ connectionType: 'bluetooth',
146
+ });
82
147
  ```
83
148
 
84
- `discoverPrinters` filters out Epson sub-device targets like `[local_display]`.
149
+ Supported `connectionType` filters:
150
+ - `bluetooth` -> `BT:`
151
+ - `tcp` -> `TCP:`, `TCPS:`
152
+ - `usb` -> `USB:`
85
153
 
86
154
  ## Connection Lifecycle
87
155
 
88
156
  - `connect(target?, timeout?)`
89
157
  - `disconnect()`
90
158
  - `onConnectionChange(callback)`
159
+ - `onStatusChange(callback)`
91
160
 
92
- Examples:
161
+ Example:
93
162
 
94
163
  ```ts
95
164
  await printer.connect(); // uses config.target
96
165
  await printer.connect('TCP:192.168.1.50', 7000); // override target
97
166
 
98
- const unsubscribe = printer.onConnectionChange((status) => {
99
- console.log('status', status);
167
+ const off = printer.onConnectionChange((status) => {
168
+ console.log('connection', status);
100
169
  });
101
170
  ```
102
171
 
103
172
  ## Printing
104
173
 
105
- ### PrintJob
174
+ ### Generic `PrintJob`
106
175
 
107
176
  ```ts
108
177
  await printer.print({
@@ -115,7 +184,7 @@ await printer.print({
115
184
  });
116
185
  ```
117
186
 
118
- ### Embedded Payload
187
+ ### Embedded payload
119
188
 
120
189
  ```ts
121
190
  await printer.printEmbedded({
@@ -125,26 +194,15 @@ await printer.printEmbedded({
125
194
  });
126
195
  ```
127
196
 
128
- ### Cash Drawer
197
+ ### Cash drawer
129
198
 
130
199
  ```ts
131
200
  await printer.openDrawer();
132
201
  ```
133
202
 
134
- ## Multi-Instance And Session Behavior
135
-
136
- Each `getPrinter(...)` instance has its own native `sessionId`.
137
-
138
- This ensures:
139
- - native calls are isolated per JS instance
140
- - native events are routed by session
141
- - instance A does not consume instance B events
142
-
143
- If two instances connect to the same target at the same time, native returns `TARGET_IN_USE`.
144
-
145
203
  ## Logging
146
204
 
147
- You can inject logger per instance or set a global logger.
205
+ You can set a global logger:
148
206
 
149
207
  ```ts
150
208
  import { setGlobalLogger } from '@munchi_oy/react-native-epson-printer';
@@ -155,9 +213,28 @@ setGlobalLogger({
155
213
  });
156
214
  ```
157
215
 
158
- ## What We Support
216
+ ## React Helpers
217
+
218
+ The package exports:
219
+ - `PrinterProvider`
220
+ - `usePrinter()`
221
+ - `usePrinterStatus({ enabled?: boolean })`
222
+
223
+ `usePrinterStatus` handles connect/disconnect behavior based on `enabled`, subscribes to connection + hardware status events, and exposes error state.
159
224
 
160
- ### Vendor Support
225
+ ## Supported Epson Models
226
+
227
+ The following printer series are natively supported by the underlying Epson ePOS SDK and can be passed to the `model` configuration using the `EpsonModel` enum:
228
+
229
+ - **TM-M Series**: TM-m10, TM-m30, TM-m30II, TM-m30III, TM-m50, TM-m50II, TM-m55
230
+ - **TM-P Series**: TM-P20, TM-P20II, TM-P60, TM-P60II, TM-P80, TM-P80II
231
+ - **TM-T Series**: TM-T20, TM-T60, TM-T70, TM-T81, TM-T82, TM-T83, TM-T83III, TM-T88, TM-T88VII, TM-T90, TM-T90KP, TM-T100
232
+ - **TM-U Series**: TM-U220, TM-U220II, TM-U330
233
+ - **TM-L Series**: TM-L90, TM-L90LFC, TM-L100
234
+ - **TM-H Series**: TM-H6000
235
+ - **Others**: TS-100, SB-H50, SB-M30
236
+
237
+ ## Vendor and Platform Support
161
238
 
162
239
  | Vendor | Support |
163
240
  | :--- | :--- |
@@ -165,31 +242,17 @@ setGlobalLogger({
165
242
  | Star | No |
166
243
  | Sunmi | No |
167
244
 
168
- ### Platform Focus
169
-
170
245
  | Platform | Status |
171
246
  | :--- | :--- |
172
247
  | iOS | Supported |
173
248
  | Android | Supported |
174
249
 
175
- ### Connection Types
176
-
177
- - Bluetooth (`BT:`)
178
- - TCP (`TCP:`, `TCPS:`)
179
- - USB (`USB:`)
250
+ ## Known Limitations
180
251
 
181
- ## Known Issues
182
-
183
- - If printer hardware state is bad (cover open/paper out), jobs pause until recovery is detected.
184
- - Discovery quality depends on OS radio/network state and Epson SDK behavior.
185
- - Connecting to the same target from multiple active sessions returns `TARGET_IN_USE`.
186
-
187
- ## Limitations
188
-
189
- - Epson-only package scope.
190
- - `model` must be known at instance creation time.
191
- - No direct API to change model/lang after instance creation; create a new printer instance instead.
192
- - Bridge behavior depends on Epson ePOS2 SDK constraints.
252
+ - Epson-only scope.
253
+ - `model` must be known at `getPrinter(...)` creation time.
254
+ - Model/language are immutable per instance; create a new instance to change them.
255
+ - Underlying behavior is constrained by Epson ePOS2 SDK.
193
256
 
194
257
  ## Troubleshooting
195
258
 
@@ -198,26 +261,24 @@ setGlobalLogger({
198
261
  - Android: clean/sync Gradle and rebuild.
199
262
 
200
263
  2. `Printer target is required`
201
- - Pass `target` in config or in `connect(target)`.
264
+ - Pass `target` in config or `connect(target)`.
202
265
 
203
- 3. Frequent busy/connect retries
204
- - Ensure only one active session per target and stable transport.
266
+ 3. `TARGET_IN_USE`
267
+ - Another active session is using the same target. Disconnect old owner first.
205
268
 
206
- ## Migration Guide (Breaking Changes)
269
+ 4. Busy/timeouts during peak usage
270
+ - Keep one active owner per target and avoid overlapping connect/print flows from different instances.
207
271
 
208
- If you are upgrading from older versions:
272
+ ## Migration Notes (already shipped)
209
273
 
210
- 1. Epson-only
211
- - Removed `PrinterType`, Star/Sunmi drivers, and adapter-style vendor factory.
274
+ If upgrading from older adapter-based versions:
212
275
 
213
- 2. Config changes
214
- - `model` is now required in `getPrinter({ ... })`.
276
+ 1. Epson-only scope
277
+ - Removed Star/Sunmi and `PrinterType` factory behavior.
215
278
 
216
- 3. Connect signature changes
217
- - Before: `connect(target, timeout, model, lang)`
218
- - Now: `connect(target?, timeout?)`
219
- - Model/lang come from instance config.
279
+ 2. Config updates
280
+ - `model` is required in `getPrinter({ ... })`.
220
281
 
221
- 4. Paths and exports
222
- - Epson internals moved from `src/vendors/epson/*` to `src/epson/*`.
223
- - Public imports remain from `@munchi_oy/react-native-epson-printer`.
282
+ 3. Connect signature
283
+ - Before: `connect(target, timeout, model, lang)`
284
+ - Now: `connect(target?, timeout?)` (model/lang come from instance config).
package/dist/index.js CHANGED
@@ -8,4 +8,4 @@
8
8
  `,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
9
9
  `,bold:!0}):i==="R"?e.push({type:"text",text:g+`
10
10
  `,bold:!0}):e.push({type:"text",text:g+`
11
- `,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var x=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var A=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var L=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var U=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var Q={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Me=5e3,F=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new L(this.logger),this.queueController=new x(this.logger),this.recoveryController=new A({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new U({logger:this.logger,defaultStatus:Q,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new w({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return W.Platform.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return W.Platform.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await S(()=>m.connect(n,e,Me,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await S(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");let o=!1;try{await S(()=>m.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}catch(l){let g=E(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",N),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,N}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=se(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>m.print(i,o));break}catch(l){let g=ne(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",N),N}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=oe(e);return await this.print(r)}catch(r){let n=E(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return Q;let e=this.sessionManager.getSessionId();if(!e)return Q;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),E(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};var ue=require("react-native");var ae=ue.NativeModules.MunchiEpsonModule,we={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},be=t=>t.includes("[local_"),xe=(t,e)=>e?we[e].some(n=>t.startsWith(n)):!0,ce=async t=>{if(!ae)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await ae.discover({timeout:t.timeout})).map(ie).filter(r=>!r||be(r.target)?!1:xe(r.target,t.connectionType))}catch(e){let r=E(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Ae=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],le=t=>{for(let[e,r]of Ae)if(e.test(t))return r;return null};var de=t=>{let e=E(t),r=e.message.toUpperCase(),n=t instanceof p?t.isHardwareError:z(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Le=t=>de(t);var me=Pe(require("react")),R=require("react");var ge=(0,R.createContext)(void 0),Ue=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&B(e)},[e]);let o=(0,R.useMemo)(()=>{let g={...t,logger:e??t.logger};return K(g)},[t.lang,t.model,t.target,e]),l=(0,R.useMemo)(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return me.default.createElement(ge.Provider,{value:l},r)},k=()=>{let t=(0,R.useContext)(ge);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var f=require("react");function Fe(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=k(),[i,o]=(0,f.useState)("DISCONNECTED"),[l,g]=(0,f.useState)(null),[c,N]=(0,f.useState)(null),X=(0,f.useRef)("DISCONNECTED"),$=(0,f.useRef)(null),d=c!==null,I=(0,f.useCallback)(C=>{$.current=C,N(C)},[]),_=(0,f.useCallback)(C=>{if(C instanceof Error&&C.message){I(C.message);return}if(typeof C=="string"&&C.length>0){I(C);return}I("Unknown printer error")},[I]),a=(0,f.useCallback)(()=>{$.current!==null&&I(null)},[I]);return(0,f.useEffect)(()=>r.onConnectionChange(O=>{X.current=O,o(O),O==="CONNECTED"&&a()}),[a,r]),(0,f.useEffect)(()=>e?r.onStatusChange(O=>{g(O),a()}):void 0,[a,e,r]),(0,f.useEffect)(()=>{e&&i==="CONNECTED"&&r.getStatus().then(C=>{g(C),a()}).catch(_)},[_,a,i,e,r]),(0,f.useEffect)(()=>{let C=X.current;if(e){C==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(_);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(_)},[_,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var Te="1.0.3";function K(t){return new F({...t,logger:t.logger??Y()})}0&&(module.exports={Epos2CallbackCode,Epos2ConnectionEvent,Epos2ErrorStatus,Epos2Font,Epos2Lang,Epos2StatusEvent,EpsonModel,FontSize,MunchiPrinterError,PrinterError,PrinterErrorCode,PrinterProvider,PrinterTranslationCode,VERSION,discoverPrinters,getGlobalLogger,getPrinter,resolveEpsonError,resolveModelFromBluetoothName,resolvePrinterError,setGlobalLogger,usePrinter,usePrinterStatus});
11
+ `,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var x=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var A=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var L=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var U=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var Q={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Me=5e3,F=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new L(this.logger),this.queueController=new x(this.logger),this.recoveryController=new A({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new U({logger:this.logger,defaultStatus:Q,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new w({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return W.Platform.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return W.Platform.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await S(()=>m.connect(n,e,Me,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await S(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");let o=!1;try{await S(()=>m.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}catch(l){let g=E(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",N),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,N}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=se(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await S(()=>m.print(i,o));break}catch(l){let g=ne(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let N=E(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",N),N}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=oe(e);return await this.print(r)}catch(r){let n=E(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return Q;let e=this.sessionManager.getSessionId();if(!e)return Q;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),E(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};var ue=require("react-native");var ae=ue.NativeModules.MunchiEpsonModule,we={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},be=t=>t.includes("[local_"),xe=(t,e)=>e?we[e].some(n=>t.startsWith(n)):!0,ce=async t=>{if(!ae)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await ae.discover({timeout:t.timeout})).map(ie).filter(r=>!r||be(r.target)?!1:xe(r.target,t.connectionType))}catch(e){let r=E(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Ae=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],le=t=>{for(let[e,r]of Ae)if(e.test(t))return r;return null};var de=t=>{let e=E(t),r=e.message.toUpperCase(),n=t instanceof p?t.isHardwareError:z(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Le=t=>de(t);var me=Pe(require("react")),R=require("react");var ge=(0,R.createContext)(void 0),Ue=({config:t,logger:e,children:r})=>{let[n,i]=(0,R.useState)();(0,R.useEffect)(()=>{e&&B(e)},[e]);let o=(0,R.useMemo)(()=>{let g={...t,logger:e??t.logger};return K(g)},[t.lang,t.model,t.target,e]),l=(0,R.useMemo)(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return me.default.createElement(ge.Provider,{value:l},r)},k=()=>{let t=(0,R.useContext)(ge);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};var f=require("react");function Fe(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=k(),[i,o]=(0,f.useState)("DISCONNECTED"),[l,g]=(0,f.useState)(null),[c,N]=(0,f.useState)(null),X=(0,f.useRef)("DISCONNECTED"),$=(0,f.useRef)(null),d=c!==null,I=(0,f.useCallback)(C=>{$.current=C,N(C)},[]),_=(0,f.useCallback)(C=>{if(C instanceof Error&&C.message){I(C.message);return}if(typeof C=="string"&&C.length>0){I(C);return}I("Unknown printer error")},[I]),a=(0,f.useCallback)(()=>{$.current!==null&&I(null)},[I]);return(0,f.useEffect)(()=>r.onConnectionChange(O=>{X.current=O,o(O),O==="CONNECTED"&&a()}),[a,r]),(0,f.useEffect)(()=>e?r.onStatusChange(O=>{g(O),a()}):void 0,[a,e,r]),(0,f.useEffect)(()=>{e&&i==="CONNECTED"&&r.getStatus().then(C=>{g(C),a()}).catch(_)},[_,a,i,e,r]),(0,f.useEffect)(()=>{let C=X.current;if(e){C==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(_);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(_)},[_,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var Te="1.0.5";function K(t){return new F({...t,logger:t.logger??Y()})}0&&(module.exports={Epos2CallbackCode,Epos2ConnectionEvent,Epos2ErrorStatus,Epos2Font,Epos2Lang,Epos2StatusEvent,EpsonModel,FontSize,MunchiPrinterError,PrinterError,PrinterErrorCode,PrinterProvider,PrinterTranslationCode,VERSION,discoverPrinters,getGlobalLogger,getPrinter,resolveEpsonError,resolveModelFromBluetoothName,resolvePrinterError,setGlobalLogger,usePrinter,usePrinterStatus});
package/dist/index.mjs CHANGED
@@ -8,4 +8,4 @@ var q={},z=t=>{q.logger=t},G=()=>q.logger;import{Platform as j}from"react-native
8
8
  `,align:"center",bold:!0})}else i==="B"?e.push({type:"text",text:g+`
9
9
  `,bold:!0}):i==="R"?e.push({type:"text",text:g+`
10
10
  `,bold:!0}):e.push({type:"text",text:g+`
11
- `,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var v=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var D=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var M=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var w=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var F={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Ee=5e3,b=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new M(this.logger),this.queueController=new v(this.logger),this.recoveryController=new D({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new w({logger:this.logger,defaultStatus:F,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new y({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return j.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return j.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await N(()=>m.connect(n,e,Ee,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await N(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");let o=!1;try{await N(()=>m.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}catch(l){let g=C(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",p),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,p}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await N(()=>m.print(i,o));break}catch(l){let g=K(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",p),p}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=J(e);return await this.print(r)}catch(r){let n=C(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return F;let e=this.sessionManager.getSessionId();if(!e)return F;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),C(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};import{NativeModules as Re}from"react-native";var Z=Re.MunchiEpsonModule,pe={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Pe=t=>t.includes("[local_"),Ne=(t,e)=>e?pe[e].some(n=>t.startsWith(n)):!0,Ie=async t=>{if(!Z)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await Z.discover({timeout:t.timeout})).map(X).filter(r=>!r||Pe(r.target)?!1:Ne(r.target,t.connectionType))}catch(e){let r=C(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Se=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],_e=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var Oe=t=>{let e=C(t),r=e.message.toUpperCase(),n=t instanceof R?t.isHardwareError:A(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Ot=t=>Oe(t);import ye from"react";import{createContext as ve,useContext as De,useEffect as Me,useMemo as ee,useState as we}from"react";var te=ve(void 0),bt=({config:t,logger:e,children:r})=>{let[n,i]=we();Me(()=>{e&&z(e)},[e]);let o=ee(()=>{let g={...t,logger:e??t.logger};return ne(g)},[t.lang,t.model,t.target,e]),l=ee(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return ye.createElement(te.Provider,{value:l},r)},re=()=>{let t=De(te);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useCallback as B,useEffect as x,useRef as ie,useState as Y}from"react";function Ut(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=re(),[i,o]=Y("DISCONNECTED"),[l,g]=Y(null),[c,p]=Y(null),H=ie("DISCONNECTED"),V=ie(null),d=c!==null,P=B(f=>{V.current=f,p(f)},[]),I=B(f=>{if(f instanceof Error&&f.message){P(f.message);return}if(typeof f=="string"&&f.length>0){P(f);return}P("Unknown printer error")},[P]),a=B(()=>{V.current!==null&&P(null)},[P]);return x(()=>r.onConnectionChange(S=>{H.current=S,o(S),S==="CONNECTED"&&a()}),[a,r]),x(()=>e?r.onStatusChange(S=>{g(S),a()}):void 0,[a,e,r]),x(()=>{e&&i==="CONNECTED"&&r.getStatus().then(f=>{g(f),a()}).catch(I)},[I,a,i,e,r]),x(()=>{let f=H.current;if(e){f==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(I);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(I)},[I,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var be="1.0.3";function ne(t){return new b({...t,logger:t.logger??G()})}export{ce as Epos2CallbackCode,ae as Epos2ConnectionEvent,ue as Epos2ErrorStatus,le as Epos2Font,W as Epos2Lang,Q as Epos2StatusEvent,k as EpsonModel,U as FontSize,h as MunchiPrinterError,R as PrinterError,_ as PrinterErrorCode,bt as PrinterProvider,O as PrinterTranslationCode,be as VERSION,Ie as discoverPrinters,G as getGlobalLogger,ne as getPrinter,Ot as resolveEpsonError,_e as resolveModelFromBluetoothName,Oe as resolvePrinterError,z as setGlobalLogger,re as usePrinter,Ut as usePrinterStatus};
11
+ `,align:"left"})}return e.push({type:"feed",lines:3}),e.push({type:"cut"}),{commands:e}};var v=class{constructor(e){this.logger=e}queue=Promise.resolve();isQueuePaused=!1;resumeQueueResolver=null;isPaused(){return this.isQueuePaused}pause(){this.isQueuePaused=!0}resume(){this.isQueuePaused&&(this.isQueuePaused=!1,this.resumeQueueResolver&&(this.resumeQueueResolver(),this.resumeQueueResolver=null))}async waitUntilResumed(){if(this.isQueuePaused)return new Promise(e=>{let r=this.resumeQueueResolver;this.resumeQueueResolver=()=>{r&&r(),e()}})}enqueue(e){return new Promise((r,n)=>{let i=async()=>{this.isQueuePaused&&(this.logger?.info?.("[EpsonPrinter] Queue is PAUSED. Waiting for resume..."),await this.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Queue RESUMED."));try{let o=await e();r(o)}catch(o){n(o)}};this.queue=this.queue.then(i,i)})}enqueueBackground(e){this.queue=this.queue.then(e,e)}};var D=class{constructor(e){this.config=e}recoveryTimer=null;start(){this.recoveryTimer||(this.config.logger?.info?.("[EpsonPrinter] Starting recovery polling..."),this.recoveryTimer=setInterval(async()=>{try{let e=await this.config.getStatus();if(e.online&&!e.coverOpen&&e.errorStatus==="NONE")this.config.logger?.info?.("[EpsonPrinter] Poller detected healthy status. Requesting queue resume."),this.config.onRecovered();else{let n=`[EpsonPrinter] Polling... Status: Online=${e.online}, Cover=${e.coverOpen}, Err=${e.errorStatus}`;this.config.logger?.info?.(n)}}catch(e){this.config.logger?.error("[EpsonPrinter] Recovery poll failed",e)}},2e3))}stop(){this.recoveryTimer&&(this.config.logger?.info?.("[EpsonPrinter] Stopping recovery polling."),clearInterval(this.recoveryTimer),this.recoveryTimer=null)}};var M=class{constructor(e){this.logger=e}sessionId=null;sessionInitPromise=null;getSessionId(){return this.sessionId}async ensureSession(){if(!m)throw new Error("Native module not found");return this.sessionId?this.sessionId:this.sessionInitPromise?this.sessionInitPromise:(this.sessionInitPromise=m.initSession().then(e=>(this.sessionId=e,e)).finally(()=>{this.sessionInitPromise=null}),this.sessionInitPromise)}async disposeSession(){if(!m||!this.sessionId){this.sessionId=null;return}let e=this.sessionId;this.sessionId=null;try{await m.disposeSession(e)}catch(r){this.logger?.error("[EpsonPrinter] Dispose session failed",r)}}};var w=class{constructor(e){this.config=e}statusCallbacks=new Set;latestHardwareStatus=null;statusRefreshPromise=null;statusRefreshTimer=null;subscribe(e){return this.statusCallbacks.add(e),this.latestHardwareStatus?e(this.latestHardwareStatus):this.config.getConnectionStatus()!=="CONNECTED"?e(this.config.defaultStatus):this.refreshNow(),()=>{this.statusCallbacks.delete(e)}}handleStatusEvent(){this.scheduleRefresh()}handleConnected(){this.scheduleRefresh(0)}handleDisconnected(){this.clearRefreshTimer(),this.setHardwareStatus(this.config.defaultStatus)}clear(){this.clearRefreshTimer()}async refreshNow(){if(this.config.getConnectionStatus()!=="CONNECTED"){this.setHardwareStatus(this.config.defaultStatus);return}if(this.statusRefreshPromise){await this.statusRefreshPromise;return}this.statusRefreshPromise=(async()=>{try{let e=await this.config.getStatus();this.setHardwareStatus(e)}catch(e){this.config.logger?.error("[EpsonPrinter] Status refresh failed",e),this.latestHardwareStatus||this.setHardwareStatus(this.config.defaultStatus)}})().finally(()=>{this.statusRefreshPromise=null}),await this.statusRefreshPromise}emitHardwareStatus(e){for(let r of this.statusCallbacks)r(e)}setHardwareStatus(e){this.latestHardwareStatus=e,this.emitHardwareStatus(e)}clearRefreshTimer(){this.statusRefreshTimer&&(clearTimeout(this.statusRefreshTimer),this.statusRefreshTimer=null)}scheduleRefresh(e=150){this.config.getConnectionStatus()==="CONNECTED"&&(this.statusRefreshTimer||(this.statusRefreshTimer=setTimeout(()=>{this.statusRefreshTimer=null,this.refreshNow()},e)))}};var F={online:!1,coverOpen:!1,paperEmpty:!1,paper:"EMPTY",errorStatus:"NONE",drawerOpen:!1},Ee=5e3,b=class{disconnectTimer=null;connectionStatus="DISCONNECTED";isConnecting=!1;target=null;defaultTarget;model;lang;logger;sessionManager;queueController;recoveryController;statusController;eventRouter;constructor(e){this.logger=e.logger,this.defaultTarget=e.target??null,this.model=e.model,this.lang=e.lang??0,this.sessionManager=new M(this.logger),this.queueController=new v(this.logger),this.recoveryController=new D({logger:this.logger,getStatus:()=>this.getStatus(),onRecovered:()=>this.resumeQueue()}),this.statusController=new w({logger:this.logger,defaultStatus:F,getConnectionStatus:()=>this.connectionStatus,getStatus:()=>this.getStatus()}),this.eventRouter=new y({logger:this.logger,getSessionId:()=>this.sessionManager.getSessionId(),getConnectionStatus:()=>this.connectionStatus,onEvent:r=>{r.statusEventType!==null&&(this.statusController.handleStatusEvent(),r.isRecoveryEvent&&this.queueController.isPaused()&&(this.logger?.info?.("[EpsonPrinter] Printer recovered (Event). Resuming queue..."),this.resumeQueue())),r.connectionStatus!==null&&(r.connectionStatus==="CONNECTED"&&(this.connectionStatus="CONNECTED"),r.connectionStatus==="CONNECTED"&&this.statusController.handleConnected(),r.connectionStatus==="DISCONNECTED"&&(this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected()))}})}resumeQueue(){if(!this.queueController.isPaused())return;this.logger?.info?.("[EpsonPrinter] Resuming queue..."),this.recoveryController.stop(),this.queueController.resume()}isIosConnectionRecoveryCandidate(e){return j.OS!=="ios"?!1:e.code==="CONNECTION_FAILED"||e.code==="TIMEOUT"&&e.translationCode==="printer.error.connection_timeout"||e.translationCode==="printer.error.offline"}hasTargetInUseToken(e){if(!e||typeof e!="object")return!1;let r=String(e.code??"").toUpperCase(),n=String(e.message??"").toUpperCase();return r.includes("TARGET_IN_USE")||n.includes("TARGET_IN_USE")}isIosConnectBusyRecoveryCandidate(e){return j.OS!=="ios"||e.translationCode!=="printer.error.busy"?!1:!this.hasTargetInUseToken(e.originalError)}async recoverIosSessionForPrint(){if(!m)throw new Error("Native module not found");let e=this.target??this.defaultTarget;if(!e)throw new Error("Printer target is required");let r=this.sessionManager.getSessionId();if(r)try{await m.disconnect(r)}catch(i){this.logger?.error("[EpsonPrinter] iOS recovery disconnect failed (best-effort)",i)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let n=await this.sessionManager.ensureSession();return await N(()=>m.connect(n,e,Ee,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected(),n}async recoverIosSessionForConnect(e,r){if(!m)throw new Error("Native module not found");let n=this.sessionManager.getSessionId();if(n)try{await m.disconnect(n)}catch(o){this.logger?.error("[EpsonPrinter] iOS connect recovery disconnect failed (best-effort)",o)}await this.sessionManager.disposeSession(),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED");let i=await this.sessionManager.ensureSession();await N(()=>m.connect(i,e,r,this.model,this.lang)),this.target=e,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}async connect(e,r=5e3){let n=e??this.defaultTarget;if(!n){let i=new Error("Printer target is required");throw this.logger?.error("[EpsonPrinter] Connect failed: missing target",i),i}return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m){this.logger?.error("[EpsonPrinter] Native module not found");return}if(this.connectionStatus==="CONNECTED"&&this.target===n)return;let i=await this.sessionManager.ensureSession();this.isConnecting=!0,this.connectionStatus="CONNECTING",this.eventRouter.emitStatus("CONNECTING");let o=!1;try{await N(()=>m.connect(i,n,r,this.model,this.lang)),this.target=n,this.connectionStatus="CONNECTED",this.eventRouter.emitStatus("CONNECTED"),this.isConnecting=!1,this.eventRouter.ensureStatusListener(),this.eventRouter.ensureConnectionListener(),this.statusController.handleConnected()}catch(l){let g=C(l);if(!o&&this.isIosConnectBusyRecoveryCandidate(g)){o=!0,this.logger?.error("[EpsonPrinter] iOS busy connect suspected stale session. Recovering connection and retrying connect once...",g);try{await this.recoverIosSessionForConnect(n,r),this.logger?.info?.("[EpsonPrinter] iOS connect recovery succeeded."),this.isConnecting=!1;return}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS connect recovery failed",p),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,p}}throw this.logger?.error(`[EpsonPrinter] Connect failed for ${n}`,g),this.connectionStatus="DISCONNECTED",this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.isConnecting=!1,g}})}async print(e){if(!m)return;this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null);let r=0,n=!1;return this.queueController.enqueue(async()=>{let i=await this.sessionManager.ensureSession(),o=$(e);for(;;){r++,this.logger?.info?.(`[EpsonPrinter] Print attempt ${r}`);try{await N(()=>m.print(i,o));break}catch(l){let g=K(l);if(!n&&this.isIosConnectionRecoveryCandidate(g)){n=!0,this.logger?.error("[EpsonPrinter] iOS stale session suspected. Recovering connection and retrying print once...",g);try{i=await this.recoverIosSessionForPrint(),this.logger?.info?.("[EpsonPrinter] iOS session recovery succeeded. Retrying print...");continue}catch(c){let p=C(c);throw this.logger?.error("[EpsonPrinter] iOS session recovery failed",p),p}}if(g.isHardwareError){this.queueController.pause(),this.logger?.error(`[EpsonPrinter] Hardware error on attempt ${r}. Waiting for recovery before retry...`,g),this.recoveryController.start(),await this.queueController.waitUntilResumed(),this.logger?.info?.("[EpsonPrinter] Recovery detected. Sending cut to flush partial print before retry...");try{await m.print(i,[{cmd:"addCut"}])}catch{}this.logger?.info?.("[EpsonPrinter] Retrying print job...")}else throw this.logger?.error(`[EpsonPrinter] Print failed (non-recoverable) on attempt ${r}`,g),g}}}).finally(()=>{this.disconnectTimer&&clearTimeout(this.disconnectTimer),this.disconnectTimer=setTimeout(()=>{this.performDisconnect()},5e3)})}performDisconnect(){this.queueController.enqueueBackground(async()=>{if(!this.disconnectTimer)return;let e=this.sessionManager.getSessionId();if(m&&this.connectionStatus==="CONNECTED"&&e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),await this.sessionManager.disposeSession()}catch(r){this.logger?.error("[EpsonPrinter] Auto-Disconnect failed",r)}this.disconnectTimer=null})}async printEmbedded(e){try{let r=J(e);return await this.print(r)}catch(r){let n=C(r);throw String(r).includes("MunchiPrinterError")||this.logger?.error("[EpsonPrinter] Embedded print failed",n),n}}async disconnect(){return this.disconnectTimer&&(clearTimeout(this.disconnectTimer),this.disconnectTimer=null),this.queueController.enqueue(async()=>{if(!m)return;let e=this.sessionManager.getSessionId();if(e)try{await m.disconnect(e),this.connectionStatus="DISCONNECTED",this.target=null,this.statusController.handleDisconnected(),this.eventRouter.emitStatus("DISCONNECTED"),this.eventRouter.removeStatusListener(),this.recoveryController.stop()}catch(r){this.logger?.error("[EpsonPrinter] Disconnect failed",r)}finally{this.statusController.clear(),await this.sessionManager.disposeSession()}})}async getStatus(){if(!m)return F;let e=this.sessionManager.getSessionId();if(!e)return F;try{return await m.getStatus(e)}catch(r){throw this.logger?.error("[EpsonPrinter] GetStatus failed",r),C(r)}}async openDrawer(){let e={commands:[{type:"drawer"}]};return this.print(e)}onConnectionChange(e){return this.eventRouter.onConnectionChange(e)}onStatusChange(e){return this.statusController.subscribe(e)}};import{NativeModules as Re}from"react-native";var Z=Re.MunchiEpsonModule,pe={bluetooth:["BT:"],tcp:["TCP:","TCPS:"],usb:["USB:"]},Pe=t=>t.includes("[local_"),Ne=(t,e)=>e?pe[e].some(n=>t.startsWith(n)):!0,Ie=async t=>{if(!Z)return console.warn("[EpsonDiscovery] Native module not found"),[];try{return(await Z.discover({timeout:t.timeout})).map(X).filter(r=>!r||Pe(r.target)?!1:Ne(r.target,t.connectionType))}catch(e){let r=C(e);throw console.error("[EpsonDiscovery] Discovery failed",r),r}};var Se=[[/^TM-m10/i,0],[/^TM-m30III/i,29],[/^TM-m30II/i,21],[/^TM-m30/i,1],[/^TM-m50II/i,30],[/^TM-m50/i,23],[/^TM-m55/i,31],[/^TM-P20II/i,27],[/^TM-P20/i,2],[/^TM-P60II/i,4],[/^TM-P60/i,3],[/^TM-P80II/i,28],[/^TM-P80/i,5],[/^TM-T20/i,6],[/^TM-T60/i,7],[/^TM-T70/i,8],[/^TM-T81/i,9],[/^TM-T82/i,10],[/^TM-T83III/i,19],[/^TM-T83/i,11],[/^TM-T88VII/i,24],[/^TM-T88/i,12],[/^TM-T90KP/i,14],[/^TM-T90/i,13],[/^TM-T100/i,20],[/^TM-U220II/i,32],[/^TM-U220/i,15],[/^TM-U330/i,16],[/^TM-L90LFC/i,25],[/^TM-L90/i,17],[/^TM-L100/i,26],[/^TM-H6000/i,18]],_e=t=>{for(let[e,r]of Se)if(e.test(t))return r;return null};var Oe=t=>{let e=C(t),r=e.message.toUpperCase(),n=t instanceof R?t.isHardwareError:A(t),i=e.translationCode==="printer.error.busy"||r.includes("BUSY")||r.includes("IN_USE")||r.includes("PRINT_BUSY"),o=e.code==="TIMEOUT"||e.translationCode==="printer.error.connection_timeout"||r.includes("TIMEOUT"),l=e.code==="CONNECTION_FAILED"||e.translationCode==="printer.error.offline",g=e.code==="DISCOVERY_FAILED",c="UNKNOWN";return n?c="HARDWARE":i?c="BUSY":o?c="TIMEOUT":l?c="CONNECTION":g?c="DISCOVERY":e.code==="PRINT_FAILED"&&(c="PRINT"),{code:e.code,translationCode:e.translationCode,message:e.message,category:c,isHardwareError:n,retryable:i||o,shouldPauseQueue:n,raw:t}},Ot=t=>Oe(t);import ye from"react";import{createContext as ve,useContext as De,useEffect as Me,useMemo as ee,useState as we}from"react";var te=ve(void 0),bt=({config:t,logger:e,children:r})=>{let[n,i]=we();Me(()=>{e&&z(e)},[e]);let o=ee(()=>{let g={...t,logger:e??t.logger};return ne(g)},[t.lang,t.model,t.target,e]),l=ee(()=>({printer:o,config:t,isReady:!0,error:n}),[o,t,n]);return ye.createElement(te.Provider,{value:l},r)},re=()=>{let t=De(te);if(!t)throw new Error("usePrinter must be used within a PrinterProvider");return t};import{useCallback as B,useEffect as x,useRef as ie,useState as Y}from"react";function Ut(t={}){let{enabled:e=!0}=t,{printer:r,config:n}=re(),[i,o]=Y("DISCONNECTED"),[l,g]=Y(null),[c,p]=Y(null),H=ie("DISCONNECTED"),V=ie(null),d=c!==null,P=B(f=>{V.current=f,p(f)},[]),I=B(f=>{if(f instanceof Error&&f.message){P(f.message);return}if(typeof f=="string"&&f.length>0){P(f);return}P("Unknown printer error")},[P]),a=B(()=>{V.current!==null&&P(null)},[P]);return x(()=>r.onConnectionChange(S=>{H.current=S,o(S),S==="CONNECTED"&&a()}),[a,r]),x(()=>e?r.onStatusChange(S=>{g(S),a()}):void 0,[a,e,r]),x(()=>{e&&i==="CONNECTED"&&r.getStatus().then(f=>{g(f),a()}).catch(I)},[I,a,i,e,r]),x(()=>{let f=H.current;if(e){f==="DISCONNECTED"&&i==="DISCONNECTED"&&r.connect(n.target,5e3).then(a).catch(I);return}(i==="CONNECTED"||i==="CONNECTING")&&r.disconnect().then(a).catch(I)},[I,a,n.target,i,e,r]),{connectionStatus:i,hardwareStatus:l,isError:d,errorMessage:c}}var be="1.0.5";function ne(t){return new b({...t,logger:t.logger??G()})}export{ce as Epos2CallbackCode,ae as Epos2ConnectionEvent,ue as Epos2ErrorStatus,le as Epos2Font,W as Epos2Lang,Q as Epos2StatusEvent,k as EpsonModel,U as FontSize,h as MunchiPrinterError,R as PrinterError,_ as PrinterErrorCode,bt as PrinterProvider,O as PrinterTranslationCode,be as VERSION,Ie as discoverPrinters,G as getGlobalLogger,ne as getPrinter,Ot as resolveEpsonError,_e as resolveModelFromBluetoothName,Oe as resolvePrinterError,z as setGlobalLogger,re as usePrinter,Ut as usePrinterStatus};
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "1.0.3";
1
+ export declare const VERSION = "1.0.5";
2
2
  //# sourceMappingURL=version.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@munchi_oy/react-native-epson-printer",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Munchi Printer SDK Bridge",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",