taro-bluetooth-print 2.3.1 → 2.4.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +6 -1
  3. package/dist/index.cjs.js +1 -1
  4. package/dist/index.es.js +1 -1
  5. package/dist/index.umd.js +1 -1
  6. package/dist/types/config/PrinterConfigManager.d.ts +206 -0
  7. package/dist/types/config/index.d.ts +8 -0
  8. package/dist/types/device/MultiPrinterManager.d.ts +164 -0
  9. package/dist/types/device/index.d.ts +2 -0
  10. package/dist/types/index.d.ts +5 -1
  11. package/dist/types/services/BatchPrintManager.d.ts +205 -0
  12. package/dist/types/services/PrintHistory.d.ts +142 -0
  13. package/dist/types/services/PrintJobManager.d.ts +28 -4
  14. package/dist/types/services/PrinterStatus.d.ts +97 -0
  15. package/dist/types/services/index.d.ts +3 -0
  16. package/package.json +2 -2
  17. package/src/adapters/AlipayAdapter.ts +1 -0
  18. package/src/adapters/BaiduAdapter.ts +1 -0
  19. package/src/adapters/ByteDanceAdapter.ts +1 -0
  20. package/src/adapters/TaroAdapter.ts +1 -0
  21. package/src/adapters/WebBluetoothAdapter.ts +1 -1
  22. package/src/config/PrinterConfigManager.ts +523 -0
  23. package/src/config/index.ts +15 -0
  24. package/src/device/MultiPrinterManager.ts +470 -0
  25. package/src/device/index.ts +8 -0
  26. package/src/encoding/gbk-lite.ts +81 -76
  27. package/src/encoding/gbk-table.ts +14 -14
  28. package/src/index.ts +12 -1
  29. package/src/services/BatchPrintManager.ts +494 -0
  30. package/src/services/ConnectionManager.ts +4 -1
  31. package/src/services/PrintHistory.ts +338 -0
  32. package/src/services/PrintJobManager.ts +69 -9
  33. package/src/services/PrinterStatus.ts +261 -0
  34. package/src/services/index.ts +25 -0
  35. package/src/template/TemplateEngine.ts +4 -1
@@ -0,0 +1,142 @@
1
+ import { PrintJobStatus, PrintJobPriority } from '../queue/PrintQueue';
2
+ /**
3
+ * Print history entry
4
+ */
5
+ export interface PrintHistoryEntry {
6
+ /** Unique entry ID */
7
+ id: string;
8
+ /** Job ID from PrintJobManager */
9
+ jobId?: string;
10
+ /** Print data size in bytes */
11
+ dataSize: number;
12
+ /** Job status */
13
+ status: PrintJobStatus | 'unknown';
14
+ /** Priority */
15
+ priority: PrintJobPriority;
16
+ /** Creation timestamp */
17
+ createdAt: number;
18
+ /** Start timestamp */
19
+ startedAt?: number;
20
+ /** Completion timestamp */
21
+ completedAt?: number;
22
+ /** Duration in milliseconds */
23
+ duration?: number;
24
+ /** Error message if failed */
25
+ error?: string;
26
+ /** Device ID */
27
+ deviceId?: string;
28
+ /** Device name */
29
+ deviceName?: string;
30
+ /** Metadata */
31
+ metadata?: Record<string, unknown>;
32
+ }
33
+ /**
34
+ * History statistics
35
+ */
36
+ export interface PrintHistoryStats {
37
+ /** Total jobs */
38
+ total: number;
39
+ /** Completed jobs */
40
+ completed: number;
41
+ /** Failed jobs */
42
+ failed: number;
43
+ /** Cancelled jobs */
44
+ cancelled: number;
45
+ /** Average duration in ms */
46
+ avgDuration: number;
47
+ /** Total bytes printed */
48
+ totalBytes: number;
49
+ /** Success rate */
50
+ successRate: number;
51
+ }
52
+ /**
53
+ * Query options for history
54
+ */
55
+ export interface HistoryQueryOptions {
56
+ /** Start date filter */
57
+ startDate?: number;
58
+ /** End date filter */
59
+ endDate?: number;
60
+ /** Status filter */
61
+ status?: PrintJobStatus | PrintJobStatus[];
62
+ /** Device ID filter */
63
+ deviceId?: string;
64
+ /** Limit results */
65
+ limit?: number;
66
+ /** Offset for pagination */
67
+ offset?: number;
68
+ }
69
+ /**
70
+ * Print History Service
71
+ */
72
+ export declare class PrintHistory {
73
+ private readonly logger;
74
+ private readonly entries;
75
+ private counter;
76
+ private readonly maxEntries;
77
+ /**
78
+ * Creates a new PrintHistory instance
79
+ * @param maxEntries - Maximum number of entries to keep (default: 1000)
80
+ */
81
+ constructor(maxEntries?: number);
82
+ /**
83
+ * Add a new print job to history
84
+ */
85
+ addJob(params: {
86
+ jobId?: string;
87
+ data: Uint8Array;
88
+ status: PrintJobStatus | 'unknown';
89
+ priority?: PrintJobPriority;
90
+ deviceId?: string;
91
+ deviceName?: string;
92
+ metadata?: Record<string, unknown>;
93
+ }): string;
94
+ /**
95
+ * Update job status
96
+ */
97
+ updateJob(id: string, updates: Partial<{
98
+ status: PrintJobStatus | 'unknown';
99
+ startedAt: number;
100
+ completedAt: number;
101
+ error: string;
102
+ }>): void;
103
+ /**
104
+ * Get entry by ID
105
+ */
106
+ getEntry(id: string): PrintHistoryEntry | undefined;
107
+ /**
108
+ * Get recent jobs
109
+ */
110
+ getRecent(count?: number): PrintHistoryEntry[];
111
+ /**
112
+ * Query history with filters
113
+ */
114
+ query(options?: HistoryQueryOptions): PrintHistoryEntry[];
115
+ /**
116
+ * Get statistics
117
+ */
118
+ getStats(options?: {
119
+ days?: number;
120
+ }): PrintHistoryStats;
121
+ /**
122
+ * Clear all history
123
+ */
124
+ clear(): void;
125
+ /**
126
+ * Export history as JSON
127
+ */
128
+ export(): string;
129
+ /**
130
+ * Import history from JSON
131
+ */
132
+ import(json: string): number;
133
+ /**
134
+ * Generate unique ID
135
+ */
136
+ private generateId;
137
+ /**
138
+ * Enforce maximum entries limit
139
+ */
140
+ private enforceMaxEntries;
141
+ }
142
+ export declare const printHistory: PrintHistory;
@@ -4,8 +4,15 @@ import { IPrintJobManager, IConnectionManager } from './interfaces';
4
4
  * Print Job Manager implementation
5
5
  */
6
6
  export declare class PrintJobManager implements IPrintJobManager {
7
- /** 内存中的任务状态存储(可被子类或外部替换为持久化方案) */
8
- private static jobStateStore;
7
+ /** Instance-level job state storage (per-printer support) */
8
+ private instanceJobStateStore;
9
+ /** Static job state store for backward compatibility */
10
+ private static _jobStateStore;
11
+ /**
12
+ * Get the static job state store (for backward compatibility)
13
+ * @deprecated Use instance-level store instead for multi-printer support
14
+ */
15
+ private static get jobStateStore();
9
16
  private adapter;
10
17
  private connectionManager;
11
18
  private jobBuffer;
@@ -65,8 +72,8 @@ export declare class PrintJobManager implements IPrintJobManager {
65
72
  /**
66
73
  * Saves the current job state for resume later.
67
74
  *
68
- * 默认实现使用内存存储。如需持久化(如 localStorage),
69
- * 可通过 setSaveHandler/setLoadHandler 自定义。
75
+ * Uses instance-level storage by default. Falls back to static store
76
+ * for backward compatibility.
70
77
  */
71
78
  private saveJobState;
72
79
  /**
@@ -79,6 +86,23 @@ export declare class PrintJobManager implements IPrintJobManager {
79
86
  * Clears the current job state
80
87
  */
81
88
  private clearJobState;
89
+ /**
90
+ * Cleanup resources and clear all job state.
91
+ * Call this when the printer is no longer needed.
92
+ */
93
+ destroy(): void;
94
+ /**
95
+ * Clean up expired job states from static store.
96
+ * Call this periodically to prevent memory leaks.
97
+ *
98
+ * @param maxAge - Maximum age in ms (default: 1 hour)
99
+ */
100
+ static cleanupExpiredJobs(maxAge?: number): number;
101
+ /**
102
+ * Get count of pending job states in static store.
103
+ * Useful for debugging memory usage.
104
+ */
105
+ static getStaticStoreSize(): number;
82
106
  /**
83
107
  * Emits job state change event
84
108
  *
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Printer Status Service
3
+ *
4
+ * Queries printer status including paper, battery, and error states.
5
+ * Works with ESC/POS printers that support status commands.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const status = new PrinterStatus(printer);
10
+ * const paperStatus = await status.getPaperStatus();
11
+ * console.log('Paper:', paperStatus);
12
+ * ```
13
+ */
14
+ /**
15
+ * Paper status
16
+ */
17
+ export declare enum PaperStatus {
18
+ /** Paper is present and OK */
19
+ OK = "ok",
20
+ /** Paper is low */
21
+ LOW = "low",
22
+ /** Paper is out */
23
+ OUT = "out",
24
+ /** Paper status unknown */
25
+ UNKNOWN = "unknown"
26
+ }
27
+ /**
28
+ * Printer status
29
+ */
30
+ export interface PrinterStatusInfo {
31
+ /** Paper status */
32
+ paper: PaperStatus;
33
+ /** Cover open (if supported) */
34
+ coverOpen?: boolean;
35
+ /** Cutter error (if supported) */
36
+ cutterError?: boolean;
37
+ /** Motor error (if supported) */
38
+ motorError?: boolean;
39
+ /** Temperature issue (if supported) */
40
+ overTemp?: boolean;
41
+ /** Battery level (0-100, if supported) */
42
+ batteryLevel?: number;
43
+ /** Timestamp of status check */
44
+ timestamp: number;
45
+ /** Raw status bytes */
46
+ rawStatus?: Uint8Array;
47
+ }
48
+ /**
49
+ * Status query options
50
+ */
51
+ export interface StatusQueryOptions {
52
+ /** Timeout for status query in ms */
53
+ timeout?: number;
54
+ /** Include raw status bytes */
55
+ includeRaw?: boolean;
56
+ }
57
+ /**
58
+ * Printer Status Service
59
+ */
60
+ export declare class PrinterStatus {
61
+ private readonly logger;
62
+ /**
63
+ * Creates a new PrinterStatus instance
64
+ */
65
+ constructor();
66
+ /**
67
+ * Get printer status
68
+ *
69
+ * Sends ESC/POS status query command and parses the response.
70
+ *
71
+ * @param writeFunc - Function to write data to printer
72
+ * @param readFunc - Function to read response from printer
73
+ * @param options - Query options
74
+ * @returns Printer status info
75
+ */
76
+ getStatus(writeFunc: (data: ArrayBuffer) => Promise<void>, readFunc: () => Promise<ArrayBuffer>, options?: StatusQueryOptions): Promise<PrinterStatusInfo>;
77
+ /**
78
+ * Parse status bytes from printer
79
+ *
80
+ * Different printers return different status formats.
81
+ * This implementation handles common ESC/POS status responses.
82
+ */
83
+ private parseStatus;
84
+ /**
85
+ * Check if paper is available
86
+ */
87
+ checkPaper(writeFunc: (data: ArrayBuffer) => Promise<void>, readFunc: () => Promise<ArrayBuffer>): Promise<PaperStatus>;
88
+ /**
89
+ * Check if printer is ready
90
+ */
91
+ isReady(writeFunc: (data: ArrayBuffer) => Promise<void>, readFunc: () => Promise<ArrayBuffer>): Promise<boolean>;
92
+ /**
93
+ * Get human-readable status string
94
+ */
95
+ static toString(status: PrinterStatusInfo): string;
96
+ }
97
+ export declare const printerStatus: PrinterStatus;
@@ -5,4 +5,7 @@
5
5
  export { ConnectionManager, type ConnectionManagerConfig, type ConnectionManagerEvents, } from './ConnectionManager';
6
6
  export { CommandBuilder } from './CommandBuilder';
7
7
  export { PrintJobManager } from './PrintJobManager';
8
+ export { PrintHistory, printHistory, type PrintHistoryEntry, type PrintHistoryStats, type HistoryQueryOptions, } from './PrintHistory';
9
+ export { PrinterStatus, printerStatus, type PrinterStatusInfo, type StatusQueryOptions, type PaperStatus, } from './PrinterStatus';
10
+ export { BatchPrintManager, batchPrintManager, type BatchJob, type BatchConfig, type BatchStats, type BatchEvents, } from './BatchPrintManager';
8
11
  export * from './interfaces';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "taro-bluetooth-print",
3
- "version": "2.3.1",
4
- "description": "Taro 蓝牙打印库 v2.3 - 轻量级、高性能、跨平台支持微信、支付宝、百度、字节跳动小程序及H5 Web Bluetooth",
3
+ "version": "2.4.1",
4
+ "description": "Taro 蓝牙打印库 v2.4 - 轻量级、高性能、跨平台支持微信、支付宝、百度、字节跳动小程序及H5 Web Bluetooth",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -6,6 +6,7 @@
6
6
  import { MiniProgramAdapter, MiniProgramBLEApi } from './BaseAdapter';
7
7
 
8
8
  // Declare Alipay global for TypeScript
9
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
9
10
  interface AlipayGlobal extends MiniProgramBLEApi {}
10
11
 
11
12
  declare const my: AlipayGlobal;
@@ -6,6 +6,7 @@
6
6
  import { MiniProgramAdapter, MiniProgramBLEApi } from './BaseAdapter';
7
7
 
8
8
  // Declare Baidu global for TypeScript
9
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
9
10
  interface BaiduGlobal extends MiniProgramBLEApi {}
10
11
 
11
12
  declare const swan: BaiduGlobal;
@@ -6,6 +6,7 @@
6
6
  import { MiniProgramAdapter, MiniProgramBLEApi } from './BaseAdapter';
7
7
 
8
8
  // Declare ByteDance global for TypeScript
9
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
9
10
  interface ByteDanceGlobal extends MiniProgramBLEApi {}
10
11
 
11
12
  declare const tt: ByteDanceGlobal;
@@ -6,6 +6,7 @@
6
6
  import { MiniProgramAdapter, MiniProgramBLEApi } from './BaseAdapter';
7
7
 
8
8
  // Declare Taro global for TypeScript
9
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
9
10
  interface TaroGlobal extends MiniProgramBLEApi {}
10
11
 
11
12
  declare const Taro: TaroGlobal;
@@ -359,7 +359,7 @@ export class WebBluetoothAdapter extends BaseAdapter {
359
359
  })
360
360
  .catch(error => {
361
361
  clearTimeout(timeoutId);
362
- reject(error);
362
+ reject(error instanceof Error ? error : new Error(String(error)));
363
363
  });
364
364
  });
365
365
  }