taro-bluetooth-print 2.2.1 → 2.3.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 (56) hide show
  1. package/CHANGELOG.md +57 -165
  2. package/README.md +142 -285
  3. package/dist/index.cjs.js +1 -1
  4. package/dist/index.es.js +1 -81644
  5. package/dist/index.umd.js +1 -1
  6. package/dist/types/adapters/AdapterFactory.d.ts +0 -1
  7. package/dist/types/adapters/AlipayAdapter.d.ts +0 -1
  8. package/dist/types/adapters/BaiduAdapter.d.ts +0 -1
  9. package/dist/types/adapters/BaseAdapter.d.ts +0 -1
  10. package/dist/types/adapters/ByteDanceAdapter.d.ts +0 -1
  11. package/dist/types/adapters/TaroAdapter.d.ts +0 -1
  12. package/dist/types/adapters/WebBluetoothAdapter.d.ts +0 -1
  13. package/dist/types/config/PrinterConfig.d.ts +0 -1
  14. package/dist/types/core/BluetoothPrinter.d.ts +1 -2
  15. package/dist/types/core/EventEmitter.d.ts +6 -26
  16. package/dist/types/core/index.d.ts +6 -0
  17. package/dist/types/drivers/CpclDriver.d.ts +304 -0
  18. package/dist/types/drivers/EscPos.d.ts +0 -1
  19. package/dist/types/drivers/GPrinterDriver.d.ts +63 -0
  20. package/dist/types/drivers/TsplDriver.d.ts +251 -0
  21. package/dist/types/drivers/ZplDriver.d.ts +325 -0
  22. package/dist/types/drivers/index.d.ts +9 -0
  23. package/dist/types/encoding/gbk-lite.d.ts +8 -0
  24. package/dist/types/encoding/gbk-table.d.ts +8 -30
  25. package/dist/types/index.d.ts +10 -5
  26. package/dist/types/plugins/PluginManager.d.ts +87 -0
  27. package/dist/types/plugins/builtin/LoggingPlugin.d.ts +14 -0
  28. package/dist/types/plugins/builtin/RetryPlugin.d.ts +18 -0
  29. package/dist/types/plugins/index.d.ts +7 -0
  30. package/dist/types/plugins/types.d.ts +97 -0
  31. package/dist/types/services/CommandBuilder.d.ts +0 -1
  32. package/dist/types/services/ConnectionManager.d.ts +1 -2
  33. package/dist/types/services/PrintJobManager.d.ts +0 -1
  34. package/dist/types/services/index.d.ts +8 -0
  35. package/dist/types/services/interfaces/index.d.ts +0 -1
  36. package/dist/types/template/TemplateEngine.d.ts +0 -1
  37. package/package.json +36 -20
  38. package/src/adapters/BaseAdapter.ts +6 -8
  39. package/src/core/BluetoothPrinter.ts +15 -15
  40. package/src/core/EventEmitter.ts +15 -15
  41. package/src/core/index.ts +7 -0
  42. package/src/drivers/CpclDriver.ts +549 -0
  43. package/src/drivers/GPrinterDriver.ts +115 -0
  44. package/src/drivers/TsplDriver.ts +405 -0
  45. package/src/drivers/ZplDriver.ts +543 -0
  46. package/src/drivers/index.ts +37 -0
  47. package/src/encoding/gbk-lite.ts +108 -0
  48. package/src/encoding/gbk-table.ts +80 -58
  49. package/src/index.ts +27 -23
  50. package/src/plugins/PluginManager.ts +195 -0
  51. package/src/plugins/builtin/LoggingPlugin.ts +99 -0
  52. package/src/plugins/builtin/RetryPlugin.ts +103 -0
  53. package/src/plugins/index.ts +10 -0
  54. package/src/plugins/types.ts +119 -0
  55. package/src/services/ConnectionManager.ts +22 -22
  56. package/src/services/index.ts +16 -0
@@ -0,0 +1,87 @@
1
+ import { Plugin, PluginHooks, PluginOptions } from './types';
2
+ import { BluetoothPrintError } from '../errors/BluetoothError';
3
+ import { PrinterState } from '../types';
4
+ /**
5
+ * Manages plugins for BluetoothPrinter
6
+ */
7
+ export declare class PluginManager {
8
+ private plugins;
9
+ private readonly logger;
10
+ /**
11
+ * Register a plugin
12
+ * @param plugin - Plugin to register
13
+ * @param options - Plugin options
14
+ * @throws {BluetoothPrintError} If plugin with same name already exists
15
+ */
16
+ register(plugin: Plugin, options?: PluginOptions): Promise<void>;
17
+ /**
18
+ * Unregister a plugin
19
+ * @param name - Plugin name to unregister
20
+ */
21
+ unregister(name: string): Promise<void>;
22
+ /**
23
+ * Get a registered plugin
24
+ * @param name - Plugin name
25
+ * @returns Plugin instance or undefined
26
+ */
27
+ get(name: string): Plugin | undefined;
28
+ /**
29
+ * Get all registered plugin names
30
+ * @returns Array of plugin names
31
+ */
32
+ getNames(): string[];
33
+ /**
34
+ * Check if a plugin is registered
35
+ * @param name - Plugin name
36
+ * @returns True if registered
37
+ */
38
+ has(name: string): boolean;
39
+ /**
40
+ * Execute a hook across all plugins
41
+ * @param hookName - Name of the hook to execute
42
+ * @param args - Arguments to pass to the hook
43
+ * @returns Result from hooks (last non-void result)
44
+ */
45
+ executeHook<K extends keyof PluginHooks>(hookName: K, ...args: Parameters<NonNullable<PluginHooks[K]>>): Promise<unknown>;
46
+ /**
47
+ * Execute beforeConnect hooks
48
+ */
49
+ beforeConnect(deviceId: string): Promise<string>;
50
+ /**
51
+ * Execute afterConnect hooks
52
+ */
53
+ afterConnect(deviceId: string): Promise<void>;
54
+ /**
55
+ * Execute beforeDisconnect hooks
56
+ */
57
+ beforeDisconnect(deviceId: string): Promise<void>;
58
+ /**
59
+ * Execute afterDisconnect hooks
60
+ */
61
+ afterDisconnect(deviceId: string): Promise<void>;
62
+ /**
63
+ * Execute beforePrint hooks
64
+ */
65
+ beforePrint(buffer: Uint8Array): Promise<Uint8Array>;
66
+ /**
67
+ * Execute afterPrint hooks
68
+ */
69
+ afterPrint(bytesSent: number): Promise<void>;
70
+ /**
71
+ * Execute onError hooks
72
+ * @returns True if error should be suppressed
73
+ */
74
+ onError(error: BluetoothPrintError): Promise<boolean>;
75
+ /**
76
+ * Execute onStateChange hooks
77
+ */
78
+ onStateChange(state: PrinterState, previousState: PrinterState): Promise<void>;
79
+ /**
80
+ * Execute onProgress hooks
81
+ */
82
+ onProgress(sent: number, total: number): Promise<void>;
83
+ /**
84
+ * Clear all plugins
85
+ */
86
+ clear(): Promise<void>;
87
+ }
@@ -0,0 +1,14 @@
1
+ import { PluginFactory, PluginOptions } from '../types';
2
+ import { LogLevel } from '../../utils/logger';
3
+ export interface LoggingPluginOptions extends PluginOptions {
4
+ /** Log level (default: DEBUG) */
5
+ level?: LogLevel;
6
+ /** Include timestamps (default: true) */
7
+ timestamps?: boolean;
8
+ /** Log progress updates (default: false, can be noisy) */
9
+ logProgress?: boolean;
10
+ }
11
+ /**
12
+ * Creates a logging plugin instance
13
+ */
14
+ export declare const createLoggingPlugin: PluginFactory;
@@ -0,0 +1,18 @@
1
+ import { PluginFactory, PluginOptions } from '../types';
2
+ import { ErrorCode } from '../../errors/BluetoothError';
3
+ export interface RetryPluginOptions extends PluginOptions {
4
+ /** Maximum retry attempts (default: 3) */
5
+ maxRetries?: number;
6
+ /** Initial delay in ms (default: 1000) */
7
+ initialDelay?: number;
8
+ /** Maximum delay in ms (default: 10000) */
9
+ maxDelay?: number;
10
+ /** Backoff multiplier (default: 2) */
11
+ backoffMultiplier?: number;
12
+ /** Error codes that should trigger retry */
13
+ retryableErrors?: ErrorCode[];
14
+ }
15
+ /**
16
+ * Creates a retry plugin instance
17
+ */
18
+ export declare const createRetryPlugin: PluginFactory;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Plugin System Exports
3
+ */
4
+ export { PluginManager } from './PluginManager';
5
+ export type { Plugin, PluginHooks, PluginOptions, PluginFactory } from './types';
6
+ export { createLoggingPlugin } from './builtin/LoggingPlugin';
7
+ export { createRetryPlugin } from './builtin/RetryPlugin';
@@ -0,0 +1,97 @@
1
+ import { BluetoothPrintError } from '../errors/BluetoothError';
2
+ import { PrinterState } from '../types';
3
+ /**
4
+ * Plugin lifecycle hooks
5
+ */
6
+ export interface PluginHooks {
7
+ /**
8
+ * Called before connecting to a device
9
+ * @param deviceId - Target device ID
10
+ * @returns Modified device ID or void
11
+ */
12
+ beforeConnect?: (deviceId: string) => string | void | Promise<string | void>;
13
+ /**
14
+ * Called after successful connection
15
+ * @param deviceId - Connected device ID
16
+ */
17
+ afterConnect?: (deviceId: string) => void | Promise<void>;
18
+ /**
19
+ * Called before disconnecting
20
+ * @param deviceId - Device ID to disconnect
21
+ */
22
+ beforeDisconnect?: (deviceId: string) => void | Promise<void>;
23
+ /**
24
+ * Called after disconnection
25
+ * @param deviceId - Disconnected device ID
26
+ */
27
+ afterDisconnect?: (deviceId: string) => void | Promise<void>;
28
+ /**
29
+ * Called before sending print data
30
+ * @param buffer - Data buffer to send
31
+ * @returns Modified buffer or void
32
+ */
33
+ beforePrint?: (buffer: Uint8Array) => Uint8Array | void | Promise<Uint8Array | void>;
34
+ /**
35
+ * Called after print job completes
36
+ * @param bytesSent - Total bytes sent
37
+ */
38
+ afterPrint?: (bytesSent: number) => void | Promise<void>;
39
+ /**
40
+ * Called when an error occurs
41
+ * @param error - The error that occurred
42
+ * @returns Whether to suppress the error (true = suppress)
43
+ */
44
+ onError?: (error: BluetoothPrintError) => boolean | void | Promise<boolean | void>;
45
+ /**
46
+ * Called when printer state changes
47
+ * @param state - New printer state
48
+ * @param previousState - Previous state
49
+ */
50
+ onStateChange?: (state: PrinterState, previousState: PrinterState) => void | Promise<void>;
51
+ /**
52
+ * Called during print progress
53
+ * @param sent - Bytes sent
54
+ * @param total - Total bytes
55
+ */
56
+ onProgress?: (sent: number, total: number) => void | Promise<void>;
57
+ }
58
+ /**
59
+ * Plugin configuration options
60
+ */
61
+ export interface PluginOptions {
62
+ [key: string]: unknown;
63
+ }
64
+ /**
65
+ * Plugin interface
66
+ */
67
+ export interface Plugin {
68
+ /**
69
+ * Unique plugin name
70
+ */
71
+ name: string;
72
+ /**
73
+ * Plugin version
74
+ */
75
+ version?: string;
76
+ /**
77
+ * Plugin description
78
+ */
79
+ description?: string;
80
+ /**
81
+ * Plugin hooks
82
+ */
83
+ hooks: PluginHooks;
84
+ /**
85
+ * Plugin initialization
86
+ * @param options - Plugin options
87
+ */
88
+ init?: (options?: PluginOptions) => void | Promise<void>;
89
+ /**
90
+ * Plugin cleanup
91
+ */
92
+ destroy?: () => void | Promise<void>;
93
+ }
94
+ /**
95
+ * Plugin factory function type
96
+ */
97
+ export type PluginFactory = (options?: PluginOptions) => Plugin;
@@ -2,7 +2,6 @@ import { IPrinterDriver, IQrOptions } from '../types';
2
2
  import { ICommandBuilder } from './interfaces';
3
3
  import { TextAlign, TextStyle } from '../formatter';
4
4
  import { BarcodeOptions } from '../barcode';
5
-
6
5
  /**
7
6
  * Command Builder implementation
8
7
  */
@@ -2,7 +2,6 @@ import { IPrinterAdapter, PrinterState } from '../types';
2
2
  import { IConnectionManager } from './interfaces';
3
3
  import { BluetoothPrintError } from '../errors/BluetoothError';
4
4
  import { EventEmitter } from '../core/EventEmitter';
5
-
6
5
  /**
7
6
  * Connection manager configuration
8
7
  */
@@ -55,7 +54,7 @@ export declare class ConnectionManager extends EventEmitter<ConnectionManagerEve
55
54
  private adapter;
56
55
  private deviceId;
57
56
  private state;
58
- private readonly logger;
57
+ private readonly connLogger;
59
58
  private readonly config;
60
59
  private heartbeatTimer;
61
60
  private reconnectAttempts;
@@ -1,6 +1,5 @@
1
1
  import { IAdapterOptions } from '../types';
2
2
  import { IPrintJobManager, IConnectionManager } from './interfaces';
3
-
4
3
  /**
5
4
  * Print Job Manager implementation
6
5
  */
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Services Module
3
+ * 服务模块 - 提供连接管理、命令构建、任务管理等功能
4
+ */
5
+ export { ConnectionManager, type ConnectionManagerConfig, type ConnectionManagerEvents, } from './ConnectionManager';
6
+ export { CommandBuilder } from './CommandBuilder';
7
+ export { PrintJobManager } from './PrintJobManager';
8
+ export * from './interfaces';
@@ -1,7 +1,6 @@
1
1
  import { IAdapterOptions, IQrOptions, PrinterState, IPrinterAdapter } from '../../types';
2
2
  import { TextAlign, TextStyle } from '../../formatter';
3
3
  import { BarcodeOptions } from '../../barcode';
4
-
5
4
  /**
6
5
  * Connection Manager Interface
7
6
  *
@@ -1,6 +1,5 @@
1
1
  import { TextAlign } from '../formatter';
2
2
  import { BarcodeFormat } from '../barcode';
3
-
4
3
  /**
5
4
  * Template type
6
5
  */
package/package.json CHANGED
@@ -1,18 +1,30 @@
1
1
  {
2
2
  "name": "taro-bluetooth-print",
3
- "version": "2.2.1",
4
- "description": "Taro 蓝牙打印库 v2.2 - 轻量级、高性能、跨平台支持微信、支付宝、百度、字节跳动小程序及H5 Web Bluetooth",
3
+ "version": "2.3.1",
4
+ "description": "Taro 蓝牙打印库 v2.3 - 轻量级、高性能、跨平台支持微信、支付宝、百度、字节跳动小程序及H5 Web Bluetooth",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
8
8
  "types": "dist/types/index.d.ts",
9
9
  "exports": {
10
10
  ".": {
11
+ "types": "./dist/types/index.d.ts",
11
12
  "import": "./dist/index.es.js",
12
13
  "require": "./dist/index.cjs.js",
13
- "types": "./dist/types/index.d.ts",
14
14
  "default": "./dist/index.umd.js"
15
15
  },
16
+ "./core": {
17
+ "types": "./dist/types/core/index.d.ts",
18
+ "import": "./dist/core/index.es.js"
19
+ },
20
+ "./drivers": {
21
+ "types": "./dist/types/drivers/index.d.ts",
22
+ "import": "./dist/drivers/index.es.js"
23
+ },
24
+ "./adapters": {
25
+ "types": "./dist/types/adapters/index.d.ts",
26
+ "import": "./dist/adapters/index.es.js"
27
+ },
16
28
  "./package.json": "./package.json"
17
29
  },
18
30
  "files": [
@@ -34,9 +46,9 @@
34
46
  "format:check": "prettier --check \"src/**/*.{ts,tsx,json,md}\"",
35
47
  "type-check": "tsc --noEmit",
36
48
  "prepublishOnly": "npm run build",
37
- "test": "jest",
38
- "test:watch": "jest --watch",
39
- "test:coverage": "jest --coverage"
49
+ "test": "vitest run",
50
+ "test:watch": "vitest",
51
+ "test:coverage": "vitest run --coverage"
40
52
  },
41
53
  "keywords": [
42
54
  "taro",
@@ -49,28 +61,32 @@
49
61
  ],
50
62
  "author": "Agions",
51
63
  "license": "MIT",
52
- "dependencies": {
53
- "@tarojs/taro": "^3.6.0"
64
+ "peerDependencies": {
65
+ "@tarojs/taro": "^3.6.22"
66
+ },
67
+ "peerDependenciesMeta": {
68
+ "@tarojs/taro": {
69
+ "optional": true
70
+ }
54
71
  },
55
72
  "devDependencies": {
56
- "@types/jest": "^29.5.11",
57
73
  "@types/node": "^20.14.8",
58
- "@typescript-eslint/eslint-plugin": "^6.19.0",
59
- "@typescript-eslint/parser": "^6.19.0",
74
+ "@types/web-bluetooth": "^0.0.21",
75
+ "@typescript-eslint/eslint-plugin": "^8.57.1",
76
+ "@typescript-eslint/parser": "^8.57.1",
77
+ "@vitest/coverage-v8": "^4.0.18",
60
78
  "eslint": "^8.56.0",
61
79
  "eslint-config-prettier": "^9.1.0",
62
80
  "eslint-plugin-prettier": "^5.1.3",
63
81
  "fast-check": "^4.5.3",
64
- "jest": "^29.7.0",
65
- "jest-environment-jsdom": "^29.7.0",
66
- "prettier": "^3.2.4",
67
- "rimraf": "^5.0.0",
68
- "terser": "^5.24.0",
69
- "ts-jest": "^29.1.1",
82
+ "prettier": "^3.8.1",
83
+ "rimraf": "^6.1.2",
84
+ "terser": "^5.46.0",
70
85
  "typescript": "^5.9.3",
71
- "vite": "^5.0.0",
72
- "vite-plugin-dts": "^3.9.1",
73
- "vitepress": "^1.0.0"
86
+ "vite": "^7.3.1",
87
+ "vite-plugin-dts": "^4.5.4",
88
+ "vitepress": "^1.6.4",
89
+ "vitest": "^4.0.18"
74
90
  },
75
91
  "sideEffects": false
76
92
  }
@@ -242,15 +242,13 @@ export abstract class MiniProgramAdapter extends BaseAdapter {
242
242
  this.logger.info('Device connected successfully');
243
243
 
244
244
  // Listen for connection state changes
245
- this.getApi().onBLEConnectionStateChange(
246
- (res: { deviceId: string; connected: boolean }) => {
247
- if (res.deviceId === deviceId && !res.connected) {
248
- this.logger.warn('Device disconnected unexpectedly');
249
- this.updateState(PrinterState.DISCONNECTED);
250
- this.cleanupDevice(deviceId);
251
- }
245
+ this.getApi().onBLEConnectionStateChange((res: { deviceId: string; connected: boolean }) => {
246
+ if (res.deviceId === deviceId && !res.connected) {
247
+ this.logger.warn('Device disconnected unexpectedly');
248
+ this.updateState(PrinterState.DISCONNECTED);
249
+ this.cleanupDevice(deviceId);
252
250
  }
253
- );
251
+ });
254
252
  } catch (error) {
255
253
  this.updateState(PrinterState.DISCONNECTED);
256
254
  this.logger.error('Connection failed:', error);
@@ -60,7 +60,7 @@ export interface PrinterEvents {
60
60
  * ```
61
61
  */
62
62
  export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
63
- private readonly logger = Logger.scope('BluetoothPrinter');
63
+ private readonly printerLogger = Logger.scope('BluetoothPrinter');
64
64
 
65
65
  /** Current printer state */
66
66
  public state: PrinterState = PrinterState.DISCONNECTED;
@@ -155,7 +155,7 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
155
155
  }
156
156
 
157
157
  this.emit('state-change', this.state);
158
- this.logger.debug('State updated:', this.state);
158
+ this.printerLogger.debug('State updated:', this.state);
159
159
  }
160
160
 
161
161
  /**
@@ -171,13 +171,13 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
171
171
  * ```
172
172
  */
173
173
  async connect(deviceId: string): Promise<this> {
174
- this.logger.info('Connecting to device:', deviceId);
174
+ this.printerLogger.info('Connecting to device:', deviceId);
175
175
 
176
176
  try {
177
177
  await this.connectionManager.connect(deviceId);
178
178
  this.updateState();
179
179
  this.emit('connected', deviceId);
180
- this.logger.info('Connected successfully');
180
+ this.printerLogger.info('Connected successfully');
181
181
 
182
182
  return this;
183
183
  } catch (error) {
@@ -208,18 +208,18 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
208
208
  async disconnect(): Promise<void> {
209
209
  const deviceId = this.connectionManager.getDeviceId();
210
210
  if (!deviceId) {
211
- this.logger.warn('Disconnect called but no device connected');
211
+ this.printerLogger.warn('Disconnect called but no device connected');
212
212
  return;
213
213
  }
214
214
 
215
- this.logger.info('Disconnecting from device:', deviceId);
215
+ this.printerLogger.info('Disconnecting from device:', deviceId);
216
216
 
217
217
  try {
218
218
  await this.connectionManager.disconnect();
219
219
  this.printJobManager.cancel();
220
220
  this.updateState();
221
221
  this.emit('disconnected', deviceId);
222
- this.logger.info('Disconnected successfully');
222
+ this.printerLogger.info('Disconnected successfully');
223
223
  } catch (error) {
224
224
  const printError = new BluetoothPrintError(
225
225
  ErrorCode.DEVICE_DISCONNECTED,
@@ -346,7 +346,7 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
346
346
  pause(): void {
347
347
  this.printJobManager.pause();
348
348
  this.updateState();
349
- this.logger.info('Print job paused');
349
+ this.printerLogger.info('Print job paused');
350
350
  }
351
351
 
352
352
  /**
@@ -360,12 +360,12 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
360
360
  * ```
361
361
  */
362
362
  async resume(): Promise<void> {
363
- this.logger.info('Resuming print job');
363
+ this.printerLogger.info('Resuming print job');
364
364
 
365
365
  try {
366
366
  await this.printJobManager.resume();
367
367
  this.updateState();
368
- this.logger.info('Print job resumed');
368
+ this.printerLogger.info('Print job resumed');
369
369
  } catch (error) {
370
370
  const printError = new BluetoothPrintError(
371
371
  ErrorCode.PRINT_JOB_FAILED,
@@ -390,7 +390,7 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
390
390
  this.printJobManager.cancel();
391
391
  this.commandBuilder.clear();
392
392
  this.updateState();
393
- this.logger.info('Print job cancelled');
393
+ this.printerLogger.info('Print job cancelled');
394
394
  }
395
395
 
396
396
  /**
@@ -439,7 +439,7 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
439
439
  }
440
440
 
441
441
  const buffer = this.commandBuilder.getBuffer();
442
- this.logger.info(`Starting print job: ${buffer.length} bytes`);
442
+ this.printerLogger.info(`Starting print job: ${buffer.length} bytes`);
443
443
 
444
444
  // Clear the command buffer after getting the buffer for printing
445
445
  this.commandBuilder.clear();
@@ -462,14 +462,14 @@ export class BluetoothPrinter extends EventEmitter<PrinterEvents> {
462
462
 
463
463
  if (isPaused) {
464
464
  // Print job was paused
465
- this.logger.info('Print job paused');
465
+ this.printerLogger.info('Print job paused');
466
466
  } else {
467
467
  // Print job completed successfully
468
468
  this.emit('print-complete');
469
- this.logger.info('Print job completed successfully');
469
+ this.printerLogger.info('Print job completed successfully');
470
470
  }
471
471
  } catch (error) {
472
- this.logger.error('Print job failed with error:', error);
472
+ this.printerLogger.error('Print job failed with error:', error);
473
473
  const printError =
474
474
  error instanceof BluetoothPrintError
475
475
  ? error
@@ -24,12 +24,12 @@
24
24
  * });
25
25
  * ```
26
26
  */
27
+ import { Logger } from '@/utils/logger';
28
+
27
29
  export class EventEmitter<T> {
28
- // 使用Map存储事件监听器,Set确保每个监听器唯一
29
30
  private listeners: Map<keyof T, Set<(data: T[keyof T]) => void>> = new Map();
30
-
31
- // Debug mode flag
32
31
  private debugMode = false;
32
+ protected readonly logger = Logger.scope('EventEmitter');
33
33
 
34
34
  /**
35
35
  * Subscribe to an event
@@ -45,7 +45,7 @@ export class EventEmitter<T> {
45
45
  this.listeners.get(event)!.add(handler as (data: T[keyof T]) => void);
46
46
 
47
47
  if (this.debugMode) {
48
- console.debug(`EventEmitter: Added listener for "${String(event)}"`, {
48
+ this.logger.debug(`EventEmitter: Added listener for "${String(event)}"`, {
49
49
  listenerCount: this.listenerCount(event),
50
50
  });
51
51
  }
@@ -90,7 +90,7 @@ export class EventEmitter<T> {
90
90
  this.listeners.set(event, newHandlers);
91
91
 
92
92
  if (this.debugMode) {
93
- console.debug(`EventEmitter: Prepend listener for "${String(event)}"`, {
93
+ this.logger.debug(`EventEmitter: Prepend listener for "${String(event)}"`, {
94
94
  listenerCount: this.listenerCount(event),
95
95
  });
96
96
  }
@@ -125,7 +125,7 @@ export class EventEmitter<T> {
125
125
  handlers.delete(handler as (data: T[keyof T]) => void);
126
126
 
127
127
  if (this.debugMode) {
128
- console.debug(`EventEmitter: Removed listener for "${String(event)}"`, {
128
+ this.logger.debug(`EventEmitter: Removed listener for "${String(event)}"`, {
129
129
  listenerCount: handlers.size,
130
130
  });
131
131
  }
@@ -135,7 +135,7 @@ export class EventEmitter<T> {
135
135
  this.listeners.delete(event);
136
136
 
137
137
  if (this.debugMode) {
138
- console.debug(`EventEmitter: Removed event "${String(event)}" (no more listeners)`);
138
+ this.logger.debug(`EventEmitter: Removed event "${String(event)}" (no more listeners)`);
139
139
  }
140
140
  }
141
141
  }
@@ -154,7 +154,7 @@ export class EventEmitter<T> {
154
154
  const data = args[0] as T[K];
155
155
 
156
156
  if (this.debugMode) {
157
- console.debug(`EventEmitter: Emitting "${String(event)}"`, {
157
+ this.logger.debug(`EventEmitter: Emitting "${String(event)}"`, {
158
158
  data,
159
159
  listenerCount: this.listenerCount(event),
160
160
  });
@@ -184,7 +184,7 @@ export class EventEmitter<T> {
184
184
  }
185
185
  } catch (error) {
186
186
  // 捕获并处理事件处理程序中的错误,避免影响其他监听器
187
- console.error(`Error in event handler for "${String(event)}":`, error);
187
+ this.logger.error(`Error in event handler for "${String(event)}":`, error);
188
188
  }
189
189
  }
190
190
  }
@@ -204,7 +204,7 @@ export class EventEmitter<T> {
204
204
  const data = args[0] as T[K];
205
205
 
206
206
  if (this.debugMode) {
207
- console.debug(`EventEmitter: Emitting async "${String(event)}"`, {
207
+ this.logger.debug(`EventEmitter: Emitting async "${String(event)}"`, {
208
208
  data,
209
209
  listenerCount: this.listenerCount(event),
210
210
  });
@@ -238,7 +238,7 @@ export class EventEmitter<T> {
238
238
  }
239
239
  } catch (error) {
240
240
  // 捕获并处理事件处理程序中的错误,避免影响其他监听器
241
- console.error(`Error in event handler for "${String(event)}":`, error);
241
+ this.logger.error(`Error in event handler for "${String(event)}":`, error);
242
242
  }
243
243
  })()
244
244
  );
@@ -247,7 +247,7 @@ export class EventEmitter<T> {
247
247
  await Promise.all(promises);
248
248
 
249
249
  if (this.debugMode) {
250
- console.debug(`EventEmitter: Finished emitting async "${String(event)}"`);
250
+ this.logger.debug(`EventEmitter: Finished emitting async "${String(event)}"`);
251
251
  }
252
252
  }
253
253
 
@@ -262,7 +262,7 @@ export class EventEmitter<T> {
262
262
  this.listeners.delete(event);
263
263
 
264
264
  if (this.debugMode) {
265
- console.debug(
265
+ this.logger.debug(
266
266
  `EventEmitter: Removed all ${listenerCount} listeners for "${String(event)}"`
267
267
  );
268
268
  }
@@ -272,7 +272,7 @@ export class EventEmitter<T> {
272
272
  this.listeners.clear();
273
273
 
274
274
  if (this.debugMode) {
275
- console.debug(`EventEmitter: Removed all ${eventCount} events and their listeners`);
275
+ this.logger.debug(`EventEmitter: Removed all ${eventCount} events and their listeners`);
276
276
  }
277
277
  }
278
278
  }
@@ -327,7 +327,7 @@ export class EventEmitter<T> {
327
327
  */
328
328
  setDebugMode(enabled: boolean): void {
329
329
  this.debugMode = enabled;
330
- console.debug(`EventEmitter: Debug mode ${enabled ? 'enabled' : 'disabled'}`);
330
+ this.logger.debug(`EventEmitter: Debug mode ${enabled ? 'enabled' : 'disabled'}`);
331
331
  }
332
332
 
333
333
  /**
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Core Module - 核心模块
3
+ */
4
+
5
+ export { BluetoothPrinter } from './BluetoothPrinter';
6
+ export type { PrinterEvents } from './BluetoothPrinter';
7
+ export { EventEmitter } from './EventEmitter';