print-shim
v1.0.1
Published
TypeScript SDK for adapting local WebSocket print components across ecommerce platforms.
Downloads
27
Maintainers
Readme
print-shim 🖨️
print-shim 是一个旨在抹平国内电商平台(拼多多、抖店、小红书等)官方打印组件协议差异的轻量级 TypeScript SDK。它通过统一的 API 封装,让你只需编写一套代码,即可调用不同平台的本地打印服务。
✨ 特性
- 协议对齐:统一处理不同平台的 WebSocket 指令、RequestID 匹配及返回格式。
- Promise 化 API:告别繁琐的异步回调,支持 async/await。
- 连接管理:内置心跳检测、自动重连机制,保障打印稳定性。
- 轻量可靠:基于 Vite 构建,天然支持 Tree-shaking,体积极小。
- 开箱即用:预设各平台默认端口与协议映射。
📦 安装
npm install print-shim
# 或者
pnpm add print-shim🚀 快速上手
import { Platform, PrintShim } from "print-shim"
// 1. 初始化
const printShim = new PrintShim(Platform.XHS, {
useWss: false,
})
// 2. 建立连接
await printShim.connect()
// 3. 获取打印机列表
const { printers } = await printShim.getPrinters()
console.log("可用打印机:", printers)
// 4. 发送打印任务
try {
const result = await printShim.print({
taskID: "demo-task-001",
printer: "HPRT N41",
documents: [
{
templateURL: "https://example.com/template",
data: {},
},
],
})
console.log("打印成功:", result)
} catch (error) {
console.error("打印失败:", error)
}🏗️ 架构设计
print-shim 采用适配器模式,将平台协议差异下沉到 adapter,Core 只保留通用的 WebSocket 请求生命周期管理:
- Core:负责 WebSocket 连接、发送 payload、pending request 管理、timeout,以及收到消息后的分发流程。
- Adapter:负责平台协议差异,包括请求构造、响应匹配、最终响应判断、失败判断、结果归一化,以及平台响应类型维护。
- Shim Layer:提供面向业务开发者的标准化方法。
🛠️ API 详情
new PrintShim(platform, options?)
| 参数 | 类型 | 说明 |
| ----------------- | --------------------------------------------- | ------------------------------------- |
| platform | Platform.PDD \| Platform.DY \| Platform.XHS | 目标打印平台 |
| options.useWss | 可选 boolean | 是否走平台预设 wss 地址 |
| options.url | 可选 string | 自定义组件地址(优先级高于 useWss) |
| options.timeoutMs | 可选 number | 请求默认超时时间(毫秒) |
| options.logger | 可选 Logger | 自定义日志实现 |
| options.websocket | 可选 Partial<WebSocketClientOptions> | 自定义 WS 重连/心跳等连接参数 |
实例方法:
connect(): Promise<void>close(code?: number, reason?: string): voidsend<TResponse>(action: string, payload?: AnyJson, options?: SendOptions): Promise<TResponse>getPrinters(): Promise<GetPrintersResponse>print(payload: PrintPayload): Promise<PlatformPrintResponseMap[P]>preview(payload: PrintPayload): Promise<PlatformPreviewResponseMap[P]>onMessage(listener): () => void
