feat: 新增 plugin/ 插件化形态(funjia.print-tag)+ 可选 SN 条码/二维码

把本工程的标签排版能力改造成 FunjiaUI 远端插件,放进 plugin/ 子目录,
与原独立 Web 版并存(两者功能一致,模板/版面/打印行为逐项对齐)。

- 入口从 createApp().mount() 改为 activate(ctx) + ctx.addRoute,注册 1 菜单 / 1 路由 / 2 命令
- 11 个模板的渲染收敛成 SpecTag,差异集中到 templates/registry.ts(字段/选项/默认值原样保留)
- 店铺名 / 电话从写死改为可配置,记忆在插件私有存储
- 内置二维码图片改为打包 data URL —— 远端插件没有自己的 public/
- 去掉 @headlessui/vue(换原生 select)与 Tailwind,样式类名统一 pt- 前缀避免污染宿主
- 可选接入宿主 api::sn-code:按 SN 生成真 Code 128 条码与可扫二维码;
  关闭时(默认)完全保持原静态二维码行为。领码优先贴到已排版的格子,不够才新建
- 新增 commands: print-tag:issue-sn / print-tag:render-svg(后者纯本地出图,供其它插件复用)
- code128.ts 实现真 Code 128 Set B(含校验位);二维码走 qrcode-generator(真 QR)
- 自带本地预览器(preview/mock-api.ts 补了 /api/sn-codes mock)与 deploy / verify 脚本
- verify.mjs 修掉一处误报:源码边界判据改为「解析后是否逃出工程根」,
  而不是「说明符是否以 .. 开头」(后者会把 src/components/X.vue → ../codes 误判为越界)

已发布到插件仓库:funjia.print-tag@1.0.0
This commit is contained in:
2026-10-03 23:48:32 +08:00
parent 1896d1032b
commit ef41d98838
43 changed files with 8835 additions and 0 deletions
+498
View File
@@ -0,0 +1,498 @@
/**
* 预览器的最小后端(Vite 中间件)。
*
* ## 为什么预览器需要它
*
* 插件里最常见的功能就是「拉列表、存表单」。如果预览环境一律把 http 拦掉,
* 插件作者就只能看到一堆「被拦截」的日志 —— 页面渲染对不对能验,**功能对不对验不了**。
* 这个中间件让 `ctx.http.get("/api/device/list")` 在预览里真的能拿到数据。
*
* ## 它与宿主 mock 的关系
*
* 宿主自己也有一套 mock(`src/mock/`),跑在**浏览器内**、拦的是前端请求。
* 预览器是独立工程,拿不到那套代码(也不该依赖宿主源码),所以这里**重写一份**
* —— 但只重写「数据与路由」这层,契约里的关键定义与客户端共用,见下。
*
* 代价是两份实现可能漂移。因此约定:
*
* - **接口契约以宿主为准**,这里是它的**子集**(只实现最常用的几个);
* - 响应形状、`code` 取值、401 的语义**必须一致** —— 不一致就等于骗了插件作者;
* - 契约里那几个**线上跑的东西**(存储键、令牌形状、包络、请求头解析)
* 不在这份文件里重写,而是与客户端共用 `preview/api-contract.ts`;
* - 真后端就绪后,用 `PREVIEW_API_TARGET` 把 `/api` 代理过去,
* 这份 mock 自动让位(见 `vite.preview.config.ts`)。
*
* ## 401 与宿主对齐的地方
*
* 1. 未授权同时给 **HTTP 401** 和 **`code: 401`**(宿主 http 层认后者,
* 但真后端可能只给状态码,两边都给最稳);
* 2. `Authorization` 必须是 `Bearer <token>`,**严格校验前缀** ——
* 这样「请求层忘了加前缀」会在预览阶段暴露;
* 3. 登录接口用 `code: 1` 表达密码错误(业务失败),**不用 401**
* (401 的含义是「未授权」,会被上层当成「令牌失效」去清会话)。
*/
import type { IncomingMessage, ServerResponse } from "node:http";
import {
TOKEN_PREFIX,
TOKEN_TTL_MS,
UNAUTHORIZED_CODE,
parseAuthHeader,
type ApiResult,
type AuthUser,
} from "./api-contract";
/* ------------------------------------------------------------------ 类型 */
/** 用户表里的一行 = 对外的用户 + 密码(密码**绝不**出现在响应里) */
interface MockUser extends AuthUser {
password: string;
}
type Row = Record<string, any>;
/* ------------------------------------------------------------------ 数据 */
/** 与宿主 `src/mock/auth.ts` 的演示账号保持一致 */
const USERS: MockUser[] = [
{
id: 1,
account: "funjia",
password: "funjia123",
name: "管理员",
role: "超级管理员",
dept: "信息中心",
},
{
id: 2,
account: "viewer",
password: "viewer123",
name: "巡检员",
role: "普通用户",
dept: "运维组",
},
];
/**
* 种子数据:宿主 `src/mock/db.ts` 的一小部分。
*
* 刻意**不搬全**。预览要的是「有数据可看」,不是「数据与宿主逐行一致」;
* 搬全了一份 10 行的设备表反而会让这里变成第二个需要同步维护的地方。
*/
const SEED: Record<string, Row[]> = {
device: [
{ id: 1, code: "PC-2024-0001", name: "联想 ThinkCentre M720", category: "主机", brand: "联想", status: "在租", price: 1200, owner: "市政务服务中心信息科" },
{ id: 2, code: "MN-2024-0031", name: "AOC 24B1XH", category: "显示器", brand: "AOC", status: "在租", price: 300, owner: "市政务服务中心信息科" },
{ id: 3, code: "PC-2024-0007", name: "戴尔 OptiPlex 3080", category: "主机", brand: "戴尔", status: "闲置", price: 1100, owner: "" },
{ id: 4, code: "AIO-2024-0002", name: "惠普 ProOne 400 G6", category: "一体机", brand: "惠普", status: "维修中", price: 1600, owner: "第三实验中学" },
],
notice: [
{ id: 1, title: "租赁设备季度巡检安排", level: "重要", publisher: "运维组", content: "本季度巡检覆盖全部在租设备。" },
{ id: 2, title: "系统升级通知", level: "普通", publisher: "系统管理员", content: "本周六 22:00 升级,期间暂停服务约 30 分钟。" },
],
};
/* -------------------------------------------------------------- 响应助手 */
const ok = (data: any, total?: number): ApiResult => ({
code: 0,
msg: "ok",
data,
...(total === undefined ? {} : { total }),
});
const fail = (msg: string, code = 1): ApiResult => ({ code, msg, data: null });
const unauthorized = (reason: string): ApiResult => ({
code: UNAUTHORIZED_CODE,
msg: reason || "未登录或登录已过期",
data: null,
});
/* ------------------------------------------------------------------ 令牌 */
const toPublic = (user: MockUser): AuthUser => {
const { password: _password, ...rest } = user;
return rest;
};
function signToken(userId: number, ttl: number = TOKEN_TTL_MS): string {
const exp = Date.now() + ttl;
const nonce = Math.random().toString(36).slice(2, 10);
return `${TOKEN_PREFIX}.${userId}.${exp}.${nonce}`;
}
function verifyToken(token: string): { ok: true; user: AuthUser } | { ok: false; reason: string } {
const parts = String(token || "").split(".");
if (parts.length !== 4 || parts[0] !== TOKEN_PREFIX) {
return { ok: false, reason: "令牌格式不正确" };
}
const userId = Number(parts[1]);
const exp = Number(parts[2]);
if (!Number.isFinite(userId) || !Number.isFinite(exp)) {
return { ok: false, reason: "令牌格式不正确" };
}
if (Date.now() > exp) return { ok: false, reason: "登录状态已过期,请重新登录" };
const user = USERS.find((item) => item.id === userId);
if (!user) return { ok: false, reason: "令牌对应的用户不存在" };
return { ok: true, user: toPublic(user) };
}
/* ------------------------------------------------------------------ 请求 */
function readBody(req: IncomingMessage): Promise<any> {
return new Promise((resolve) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
// 1MB 上限:预览后端不该被一个大 body 拖死
if (raw.length > 1024 * 1024) raw = raw.slice(0, 1024 * 1024);
});
req.on("end", () => {
try {
resolve(raw ? JSON.parse(raw) : {});
} catch {
resolve({});
}
});
req.on("error", () => resolve({}));
});
}
/* ------------------------------------------------------------------ SN 码 */
/**
* SN 码的预览后端(对应宿主后端的 `api::sn-code` 模块)。
*
* ## 为什么模板里要额外带这一段
*
* 模板自带的通用 CRUD 只覆盖 `/api/<name>/list|detail|add|update|delete`,
* 而「标签打印」插件的核心增量能力是**可选接入 SN 码接口** —— 少了这一段,
* `npm run dev` 里一打开「② SN 码」开关就是 404,本地根本验不了,
* 只能构建 → 发布 → 装进宿主 → 点一遍,一圈几分钟。
*
* ## 与真后端的关系
*
* 参数口径(`targetType` / `count` / `refId` / `refLabel` / `remark`、返回
* `{ items }`、校验返回 `{ valid, reason, exists, record }`)**照着真后端抄**,
* 但**数据是进程内的**、格式里的校验位算法也是这里自己定的 ——
* 所以:**别看号段,只验链路**。真要对接,关掉开关或设 `PREVIEW_API_TARGET`。
*/
/** 业务类型 → 号段前缀。真后端同结构,前缀值以真后端 `/meta` 为准 */
const SN_PREFIX: Record<string, string> = {
DEVICE: "ZP",
PART: "PJ",
LEASE: "ZL",
MAINTENANCE: "SH",
CUSTOMER: "KH",
OTHER: "SN",
};
/** 校验位:body 各字符按 31 进制滚动求和后取模 36,映射到 0-9A-Z */
function snChecksum(body: string): string {
let sum = 0;
for (let i = 0; i < body.length; i += 1) {
sum = (sum * 31 + body.charCodeAt(i)) % 36;
}
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[sum];
}
function makeSn(targetType: string, seq: number): string {
const pad = (n: number) => String(n).padStart(2, "0");
const now = new Date();
const prefix = SN_PREFIX[targetType] || "SN";
const body = `${prefix}-${String(now.getFullYear()).slice(2)}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${String(seq).padStart(4, "0")}`;
return `${body}-${snChecksum(body)}`;
}
function issueSn(ledger: Row[], body: any, count: number): Row[] {
const targetType = String(body?.targetType || "DEVICE");
const batch = `B${Date.now().toString(36).toUpperCase()}`;
const out: Row[] = [];
for (let i = 0; i < count; i += 1) {
const sn = makeSn(targetType, ledger.length + 1);
const row: Row = {
sn,
targetType,
batch,
status: "ISSUED",
issuedAt: new Date().toISOString(),
...(body?.refId ? { refId: body.refId } : {}),
...(body?.refLabel ? { refLabel: body.refLabel } : {}),
...(body?.remark ? { remark: body.remark } : {}),
};
ledger.push(row);
out.push(row);
}
return out;
}
/** 命中 `/api/sn-codes*` 时返回结果;不命中返回 null,交回通用流程 */
function handleSnCode(
method: string,
path: string,
query: Record<string, string>,
body: any,
store: Record<string, Row[]>
): ApiResult | null {
if (path !== "/api/sn-codes" && !path.startsWith("/api/sn-codes/")) return null;
if (!store.__sn) store.__sn = [];
const ledger = store.__sn;
if (method === "GET" && path === "/api/sn-codes/meta") {
return ok({
targetTypes: Object.keys(SN_PREFIX),
defaultPrefix: SN_PREFIX,
typicalLength: 15,
maxLength: 16,
});
}
if (method === "POST" && path === "/api/sn-codes/generate") {
return ok(issueSn(ledger, body, 1)[0]);
}
if (method === "POST" && path === "/api/sn-codes/batch") {
const count = Math.min(Math.max(1, Number(body?.count) || 1), 200);
const items = issueSn(ledger, body, count);
return ok({ items, batch: items[0]?.batch });
}
if (method === "POST" && path === "/api/sn-codes/verify") {
const text = String(body?.sn || "").trim();
if (!text) return ok({ valid: false, reason: "EMPTY" });
const matched = text.match(/^([A-Z]{2})-(\d{6})-(\d{4})-([0-9A-Z])$/);
if (!matched) return ok({ valid: false, reason: "FORMAT" });
if (snChecksum(`${matched[1]}-${matched[2]}-${matched[3]}`) !== matched[4]) {
return ok({ valid: false, reason: "CHECKSUM" });
}
const record = ledger.find((row) => row.sn === text) || null;
return ok({ valid: true, exists: !!record, record });
}
if (method === "GET" && path === "/api/sn-codes") {
const pageSize = Number(query.pageSize) || 50;
let rows = ledger.slice();
for (const key of ["targetType", "status", "batch"] as const) {
if (query[key]) rows = rows.filter((row) => String(row[key]) === query[key]);
}
if (query.sn) rows = rows.filter((row) => String(row.sn).includes(query.sn));
// 看最新发放的在前,和真后端一致
rows = rows.slice().reverse();
return ok(rows.slice(0, pageSize), rows.length);
}
const voided = path.match(/^\/api\/sn-codes\/([^/]+)\/void$/);
if (method === "POST" && voided) {
const target = ledger.find((row) => row.sn === decodeURIComponent(voided[1]));
if (!target) return fail("SN 不存在");
target.status = "VOID";
target.voidedAt = new Date().toISOString();
return ok(target);
}
return null;
}
/* ------------------------------------------------------------------ 路由 */
/**
* 路由分发。
*
* `store` 由调用方传进来(而不是读模块级的变量):数据必须**每个预览进程一份**,
* 且要能被 `createPreviewApi()` 的闭包持有 —— 写成模块级单例的话,
* 多次创建中间件会共用一份脏数据。
*/
function handle(
method: string,
path: string,
query: Record<string, string>,
body: any,
store: Record<string, Row[]>,
authorization?: string
): ApiResult {
/* ---- 免登录 ---- */
if (method === "POST" && path === "/api/auth/login") {
const user = USERS.find(
(item) => item.account === String(body.account || "").trim() && item.password === body.password
);
if (!user) return fail("账号或密码不正确");
return ok({
token: signToken(user.id),
expiresIn: Math.floor(TOKEN_TTL_MS / 1000),
user: toPublic(user),
});
}
// 登出幂等且免登录:令牌已过期时也必须能登出,否则用户卡在跳不出去的状态
if (method === "POST" && path === "/api/auth/logout") return ok(true);
if (method === "GET" && path === "/api/auth/demo-accounts") {
return ok(USERS.map((u) => ({ account: u.account, password: u.password, role: u.role })));
}
/* ---- 鉴权闸门:以下一律要求合法令牌 ---- */
const parsed = parseAuthHeader(authorization);
if (parsed.reason) return unauthorized(parsed.reason);
const auth = verifyToken(parsed.token);
if (!auth.ok) return unauthorized(auth.reason);
if (method === "GET" && path === "/api/auth/me") return ok(auth.user);
/* ---- SN 码:插件专属接口,优先于通用 CRUD 匹配 ---- */
const snResult = handleSnCode(method, path, query, body, store);
if (snResult) return snResult;
/* ---- 通用 CRUD ---- */
const crud = path.match(/^\/api\/([\w-]+)\/(list|detail|add|update|delete)$/);
if (crud) {
const [, name, action] = crud;
// 集合不存在就就地创建:宿主也是这个行为(`collection()` 动态建表),
// 于是插件自带的数据表不需要先在种子里登记
if (!store[name]) store[name] = [];
const storeRows = store[name];
if (action === "list") {
const page = Number(query.page) || 1;
const pageSize = Number(query.pageSize) || 10;
const keyword = (query.keyword || "").trim().toLowerCase();
/**
* 保留字不参与等值过滤。
*
* `userId` / `pluginId` 尤其要注意:宿主会给插件请求自动附加这两个归属参数
* (见宿主 mock 的同名路由),把它们当业务字段去等值过滤会**永远筛出空集**,
* 而症状是「列表页一个插件都查不到数据」—— 很难往参数名上想。
*/
const RESERVED = ["page", "pageSize", "keyword", "userId", "pluginId"];
let matched = storeRows.slice();
for (const [key, value] of Object.entries(query)) {
if (RESERVED.includes(key)) continue;
if (value === undefined || value === null || value === "") continue;
matched = matched.filter((row) => String(row[key]) === String(value));
}
if (keyword) {
// 关键字按**第一行的字段名**搜(与宿主 `db.query` 的默认 keywordFields 一致),
// 而不是按每一行自己的字段 —— 否则字段不齐的行会搜出不一样的结果
const fields = Object.keys(matched[0] || {});
matched = matched.filter((row) =>
fields.some((field) => String((row as Row)[field] ?? "").toLowerCase().includes(keyword))
);
}
const start = (page - 1) * pageSize;
// 列表的 `data` 是**数组本身**,条数是同级的 `total` —— 与宿主一致。
// (写成 `data: { rows, total }` 是最常见的抄错,插件那边会永远拿不到行)
return ok(matched.slice(start, start + pageSize), matched.length);
}
if (action === "detail") {
return ok(storeRows.find((row) => String(row.id) === String(query.id)) || null);
}
if (action === "add") {
const nextId = storeRows.reduce((max, row) => Math.max(max, Number(row.id) || 0), 0) + 1;
const row: Row = { ...body, id: nextId, createdAt: new Date().toISOString() };
storeRows.push(row);
return ok(row);
}
if (action === "update") {
const index = storeRows.findIndex((row) => String(row.id) === String(body.id));
if (index < 0) return fail("记录不存在");
storeRows[index] = { ...storeRows[index], ...body };
return ok(storeRows[index]);
}
if (action === "delete") {
const raw = body.ids !== undefined ? body.ids : body.id;
const ids = (Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]).map(String);
if (!ids.length) return fail("没有指定要删除的记录");
const before = storeRows.length;
// 整体替换而不是原地 splice:保持「store 里的数组对象」这一层的稳定性,
// detail/update 拿到的是同一份引用,语义简单
store[name] = storeRows.filter((row) => !ids.includes(String(row.id)));
return ok(before - store[name].length);
}
}
// 明确报「没有这个接口」而不是静默 404 —— 插件作者一眼就知道是路径写错了,
// 而不是后端挂了
return fail(`预览后端没有这个接口:${method} ${path}(实现见 preview/mock-api.ts)`, 404);
}
/* ------------------------------------------------------------------ 出口 */
/**
* 创建中间件。数据存在闭包里,**进程重启即重置**(预览不需要持久化)。
*/
export function createPreviewApi() {
// 深拷贝:种子数据不该被请求改到,否则第二次装载就看到脏数据了
const store: Record<string, Row[]> = JSON.parse(JSON.stringify(SEED));
/**
* 已经提醒过的空集合名。
*
* 通用 CRUD 会**动态创建**没见过的集合(宿主同行为),于是表名打错
* (`/api/devices/list` 而种子是 `device`)的表现是「接口成功、列表是空的」——
* 看起来像「没数据」,不像「表名错了」。
*
* 响应**不动**(那是契约,宿主也是这么答的),只在预览服务端的终端里提醒一句:
* 那里正是开发者跑 `npm run dev` 时盯着的窗口。用 Set 去重,只提醒一次。
*/
const warned = new Set<string>();
const seedKeys = new Set(Object.keys(SEED));
function warnIfUnknownCollection(path: string) {
const match = path.match(/^\/api\/([\w-]+)\/(list|detail)$/);
if (!match) return;
const [, name] = match;
if (seedKeys.has(name) || warned.has(name)) return;
warned.add(name);
console.warn(
`\n \x1b[33m[preview]\x1b[0m 集合 \`${name}\` 不在预览种子里,已自动建成空表(宿主也是这样)。` +
`\n 如果你以为它有数据,先检查表名拼写;种子里现有:${[...seedKeys].join(" / ")}\n`
);
}
return async function previewApiMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: (err?: any) => void
): Promise<void> {
const rawUrl = req.url || "/";
const path = rawUrl.split("?")[0];
if (!path.startsWith("/api/")) return next();
const query: Record<string, string> = {};
for (const [key, value] of new URL(rawUrl, "http://127.0.0.1").searchParams) {
query[key] = value;
}
const method = (req.method || "GET").toUpperCase();
const body = method === "GET" ? {} : await readBody(req);
if (method === "GET") warnIfUnknownCollection(path);
let result: ApiResult;
try {
result = handle(method, path, query, body, store, req.headers.authorization);
} catch (error) {
result = fail(`预览后端内部错误:${(error as Error)?.message ?? error}`, 500);
}
// 未授权同时给 HTTP 状态码与业务码:真后端可能只给其一,
// 两边都给能让预览的行为最接近「两种后端都试过」
res.statusCode = result.code === UNAUTHORIZED_CODE ? UNAUTHORIZED_CODE : 200;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.setHeader("Cache-Control", "no-store");
res.end(JSON.stringify(result));
};
}