重构: 修复致命缺陷、清理死代码并打通类型检查与构建

本次优化在不改变业务行为的前提下,修复了多处会导致数据丢失或
功能失效的缺陷,并把此前从未跑过的类型检查与生产构建接通。

== 修复的严重缺陷 ==

服务端:
- dynamic/notice 路由在目标表缺失时用 `db.data = { dynamic: [] }`
  整体替换数据库对象后落盘,会把 employee/Notice/qa 等全部业务表清空。
  改为只创建缺失的那一张表。
- 列表接口在空表时访问 undefined.length 直接 500,统一补默认空数组。
- /api/employee/list 与 /login 明文返回 pwd 字段,且把含密码的
  请求体写进日志。改为统一剔除敏感字段、移除参数日志。
- upd 允许请求体覆盖主键 id / createTime;改为服务端维护。
- upload 未限制扩展名与大小,且用原始扩展名拼路径。

前端:
- src/common/axios.ts 的拦截器注册在全局默认 axios 实例上,而业务
  走 funjia-axios,导致拦截器全程失效;同时 funjia-axios 内部
  `axios.prototype.error = () => {}` + `axios.prototype(msg)` 会抛
  TypeError,使所有接口错误(含 401)被静默吞掉。现在本文件是唯一
  的拦截器注册点。
- 修改密码功能形同虚设: PwdForm.onUpdate 只做 setTimeout 后 emit
  成功,从不调接口;PwdDialog 又用已被拦截器解包掉的 status 判断
  成败,无论结果都提示失败。
- Notice/Plugin 新增时 userId 静默丢失 (UmByClassEnhance 的
  otherParams 只进 getList,不传 onAdd/onEdit),改用会话级
  setCurrentUserId/getCurrentUserId。
- 修复 Login 模板绑定了从未定义的 loading、跳转到路由表里不存在
  的路径;DynamicTable 里每次路由切换都触发的 debugger。
- 修复 Record/RecordUser 引用不存在的 marsLib/*、@/components/UmTable;
  CodeMirror 使用 ref 却未 import; ImageCell 调用不存在的
  getObjectTypeName。

== 结构优化 ==

- 新增 src/common/response.ts 与 BaseViewModel,收敛 7 个 viewModel
  中重复 20+ 次的响应码判断与 CRUD 样板。
- 新增 server/routers/helpers.mjs,统一服务端取表/过滤/分页/脱敏。
- 新增 server/smoke-test.mjs,16 个用例覆盖上述修复(含整库清空回归)。
- 删除 0 引用的死文件: ImageList.vue、autoresponsive.vue、
  animation.js、PwdDialog/PwdForm.vue。

== 工程配置 ==

- 修复阻塞安装与构建的三处错误:
  funjiaui 指向不存在的仓库 FunjiaUI_Vue(#v1.1.3),实为
  FunJiaUI_Vue_Package(#v1.3.1); pinia 锁 ~2.0.36 (vue 固定 3.2.33,
  2.1+ 要求 vue ^3.3.0); App.vue 引用不存在的 funjiaui/dist/style.css,
  实为包根目录 style.css。
- 新增 build/typecheck/build:only 脚本; 此前项目没有类型检查步骤。
- 移除 8 个未使用依赖,补齐 terser 与缺失的类型包。
- vite.config.ts 代理目标改由 .env 配置,移除硬编码内网地址;
  增加 manualChunks 拆包。
- 服务端数据库改为不进版本库,提供 *.example.json 初始化模板。

== 验证 ==

- npx vue-tsc --noEmit          : 0 错误
- npm run build                 : 成功 (1759 模块)
- cd server && npm run smoke    : 16/16 通过

优化前的代码保留在 legacy 分支。
This commit is contained in:
2026-09-24 15:39:59 +08:00
parent f7e6014b0b
commit a640389095
69 changed files with 6095 additions and 102028 deletions
+336
View File
@@ -0,0 +1,336 @@
/**
* 服务端路由烟雾测试(不依赖 funjia-server / cuid / lodash)。
*
* 用 vm 在内存中加载路由源码,把外部依赖替换成桩,再配一个内存版 db,
* 直接调用真实 handler 做断言。重点回归「整库被清空」这个致命缺陷。
*
* node smoke-test.mjs
*
* 退出码 0 = 全部通过,1 = 有用例失败。
*/
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import vm from "node:vm";
const here = dirname(fileURLToPath(import.meta.url));
// ── 沙箱内可用的桩 ────────────────────────────────────────────────────
const sandbox = {
console,
Math,
Date,
JSON,
Object,
Array,
String,
Number,
Boolean,
Promise,
Error,
TypeError,
setTimeout,
__cuid: () => "id-" + Math.random().toString(36).slice(2, 10),
__lodashMerge: (target, source) => Object.assign(target, source),
__db: null,
};
sandbox.globalThis = sandbox;
vm.createContext(sandbox);
/** 把路由源码的 import 改写成沙箱内的全局引用 */
const rewrite = (src) => {
let out = src;
// default 导入的第三方包
out = out.replace(
/import\s+cuid\s+from\s+["'][^"']*cuid["'];?/g,
"const cuid = globalThis.__cuid;"
);
out = out.replace(
/import\s+_\s+from\s+["'][^"']*lodash["'];?/g,
"const _ = { merge: (t, s) => globalThis.__lodashMerge(t, s) };"
);
// funjia-server 的具名导入(支持 `X as Y` 别名)
out = out.replace(
/import\s*\{([^}]*)\}\s*from\s*["']funjia-server[^"']*["'];?/g,
(m, names) =>
names
.split(",")
.map((n) => n.trim())
.filter(Boolean)
.map((n) => {
const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim());
return `const ${alias || orig} = globalThis.__${orig};`;
})
.join("\n")
);
// 相对导入 helpers.mjs(支持 `getTable as getTableRaw` 别名)
out = out.replace(
/import\s*\{([^}]*)\}\s*from\s*["'][^"']*helpers\.mjs["'];?/g,
(m, names) =>
names
.split(",")
.map((n) => n.trim())
.filter(Boolean)
.map((n) => {
const [orig, alias] = n.split(/\s+as\s+/).map((s) => s.trim());
return `const ${alias || orig} = globalThis.__helpers.${orig};`;
})
.join("\n")
);
// export default Foo → 挂到 __mod
out = out.replace(/export\s+default\s+([A-Za-z_$][\w$]*)\s*;?/g, "globalThis.__mod = $1;");
return out;
};
const loadModule = (relPath) => {
sandbox.__mod = undefined;
const src = rewrite(readFileSync(join(here, relPath), "utf8"));
// 每个模块包一层 IIFE,避免不同文件的顶层 const 在共享沙箱里冲突
vm.runInContext(`(function () {\n${src}\n})();`, sandbox, { filename: relPath });
return sandbox.__mod;
};
// ── 先加载 helpers.mjs ────────────────────────────────────────────────
{
let src = readFileSync(join(here, "routers/helpers.mjs"), "utf8");
src = src.replace(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=/g, "const $1 =");
src += "\nglobalThis.__helpers = { getTable, pickFilters, matchRow, paginate, listResponse, omitSensitive };";
vm.runInContext(src, sandbox, { filename: "routers/helpers.mjs" });
}
// ── getDb 桩:读 sandbox.__db ─────────────────────────────────────────
sandbox.__getDb = async () => sandbox.__db;
// ── 载入被测路由 ──────────────────────────────────────────────────────
const getEmployee = loadModule("routers/anki/employee.mjs");
const getNotice = loadModule("routers/anki/notice.mjs");
const getDynamic = loadModule("routers/dynamic.mjs");
// ── 假 router:收集路由表 ─────────────────────────────────────────────
const routes = [];
const router = {};
for (const m of ["get", "post", "put", "delete"]) {
router[m] = (path, handler) => routes.push({ method: m, path, handler });
}
getEmployee(router);
getNotice(router);
getDynamic(router);
const find = (method, path) => {
const r = routes.find((x) => x.method === method && x.path === path);
if (!r) throw new Error(`路由未注册: ${method.toUpperCase()} ${path}`);
return r.handler;
};
// ── 测试工具 ──────────────────────────────────────────────────────────
const makeDb = (seed) => ({
data: JSON.parse(JSON.stringify(seed)),
write: async () => {},
});
const makeCtx = ({ params = {}, query = {}, body = {} } = {}) => ({
type: "",
body: undefined,
params,
request: { query, body },
});
let passed = 0;
let failed = 0;
const test = async (name, fn) => {
try {
await fn();
passed++;
console.log(` PASS ${name}`);
} catch (err) {
failed++;
console.log(` FAIL ${name}`);
console.log(` ${err.message}`);
}
};
/**
* 断言是「空数组」。
* 不能直接用 assert.deepEqual(x, []):沙箱里创建的数组与主 realm 的 `[]`
* 原型不同,Node 会判定为「结构相同但非同一引用」。这里只校验实质语义。
*/
const assertEmptyArray = (value, label = "值") => {
assert.ok(Array.isArray(value), `${label} 不是数组: ${JSON.stringify(value)}`);
assert.equal(value.length, 0, `${label} 应为空数组,实际长度 ${value.length}`);
};
const seed = {
employee: [
{ id: "e1", userName: "admin", pwd: "123456", realName: "管理员" },
{ id: "e2", userName: "staff", pwd: "654321", realName: "员工甲" },
],
Notice: [{ id: "n1", title: "公告一", sort: 1 }],
leaseRecords: [{ id: "l1", name: "租赁单" }],
};
// ══ 用例 ══════════════════════════════════════════════════════════════
console.log("\n=== 服务端路由烟雾测试 ===\n");
console.log("[员工路由]");
await test("list 不泄漏 pwd 明文", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: {} });
await find("post", "/api/employee/list")(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.total, 2);
for (const row of ctx.body.data) {
assert.ok(!("pwd" in row), `pwd 泄漏: ${JSON.stringify(row)}`);
}
});
await test("list 在空表时不抛 500", async () => {
sandbox.__db = makeDb({});
const ctx = makeCtx({ body: {} });
await find("post", "/api/employee/list")(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.total, 0);
assertEmptyArray(ctx.body.data, "列表数据");
});
await test("login 成功返回用户但不含 pwd", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { userName: "admin", pwd: "123456" } });
await find("post", "/api/employee/login")(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.userName, "admin");
assert.ok(!("pwd" in ctx.body.data));
});
await test("login 失败不区分账号/密码错误(防枚举)", async () => {
sandbox.__db = makeDb(seed);
const a = makeCtx({ body: { userName: "nobody", pwd: "x" } });
const b = makeCtx({ body: { userName: "admin", pwd: "wrong" } });
await find("post", "/api/employee/login")(a);
await find("post", "/api/employee/login")(b);
assert.equal(a.body.code, 1);
assert.equal(b.body.code, 1);
assert.equal(a.body.msg, b.body.msg);
});
await test("add 拒绝重复用户名", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { userName: "admin", pwd: "x" } });
await find("post", "/api/employee/add")(ctx);
assert.equal(ctx.body.code, 1);
assert.equal(sandbox.__db.data.employee.length, 2);
});
await test("add 忽略请求体传入的 id / createTime", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { userName: "newbie", id: "HACKED", createTime: "1970-01-01" } });
await find("post", "/api/employee/add")(ctx);
const added = sandbox.__db.data.employee.find((x) => x.userName === "newbie");
assert.ok(added, "新员工未写入");
assert.notEqual(added.id, "HACKED");
assert.notEqual(added.createTime, "1970-01-01");
});
await test("upd 不能覆盖主键 id,且能改动业务字段", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { id: "e1", realName: "改名了", pwd: "newpwd" } });
await find("post", "/api/employee/upd")(ctx);
const row = sandbox.__db.data.employee.find((x) => x.id === "e1");
assert.ok(row, "e1 丢失");
assert.equal(row.id, "e1");
assert.equal(row.realName, "改名了");
});
await test("upd 目标不存在时返回业务错误而非 500", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { id: "not-exist", realName: "x" } });
await find("post", "/api/employee/upd")(ctx);
assert.equal(ctx.body.code, 1);
});
await test("delete 只删指定记录并返回条数", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { ids: ["e1", "ghost"] } });
await find("post", "/api/employee/delete")(ctx);
assert.equal(ctx.body.code, 0);
assert.equal(ctx.body.data.deleted, 1);
assert.equal(sandbox.__db.data.employee.length, 1);
});
await test("delete 空 ids 被拒绝", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ body: { ids: [] } });
await find("post", "/api/employee/delete")(ctx);
assert.equal(ctx.body.code, 1);
});
console.log("\n[通知路由]");
await test("Notice list 不因空表崩溃", async () => {
sandbox.__db = makeDb({});
const ctx = makeCtx({ body: {} });
await find("post", "/api/Notice/list")(ctx);
assert.equal(ctx.body.code, 0);
assertEmptyArray(ctx.body.data, "列表数据");
});
console.log("\n[★ 致命缺陷回归:整库清空]");
await test("dynamic.upd 目标表缺失时不清空整库", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ params: { tableName: "brandNewTable" }, body: { id: "x", name: "y" } });
await find("post", "/api/dynamic/upd/:tableName")(ctx);
assert.ok(Array.isArray(sandbox.__db.data.employee), "employee 表被清空了!");
assert.equal(sandbox.__db.data.employee.length, 2);
assert.ok(Array.isArray(sandbox.__db.data.Notice), "Notice 表被清空了!");
assert.equal(sandbox.__db.data.Notice.length, 1);
assert.ok(Array.isArray(sandbox.__db.data.leaseRecords), "leaseRecords 表被清空了!");
assertEmptyArray(sandbox.__db.data.brandNewTable, "缺失的新表");
});
await test("dynamic.delete 目标表缺失时不清空整库", async () => {
sandbox.__db = makeDb(seed);
const ctx = makeCtx({ params: { tableName: "anotherNewTable" }, body: { ids: ["a"] } });
await find("post", "/api/dynamic/delete/:tableName")(ctx);
assert.equal(sandbox.__db.data.employee.length, 2, "employee 表被清空了!");
assert.equal(sandbox.__db.data.Notice.length, 1, "Notice 表被清空了!");
});
await test("dynamic.list 空表返回空数组而非 500", async () => {
sandbox.__db = makeDb({});
const ctx = makeCtx({ params: { tableName: "whatever" }, body: {} });
await find("post", "/api/dynamic/list/:tableName")(ctx);
assert.equal(ctx.body.code, 0);
assertEmptyArray(ctx.body.data, "列表数据");
assert.equal(ctx.body.total, 0);
});
await test("dynamic.add 忽略请求体 id / createTime", async () => {
sandbox.__db = makeDb({ whatever: [] });
const ctx = makeCtx({ params: { tableName: "whatever" }, body: { id: "HACK", createTime: "0" } });
await find("post", "/api/dynamic/add/:tableName")(ctx);
const row = sandbox.__db.data.whatever[0];
assert.ok(row, "未写入");
assert.notEqual(row.id, "HACK");
assert.notEqual(row.createTime, "0");
});
await test("dynamic 分页参数生效", async () => {
sandbox.__db = makeDb({ big: Array.from({ length: 25 }, (_, i) => ({ id: `b${i}`, n: i })) });
const ctx = makeCtx({ params: { tableName: "big" }, body: { page: 2, pageSize: 10 } });
await find("post", "/api/dynamic/list/:tableName")(ctx);
assert.equal(ctx.body.total, 25);
assert.equal(ctx.body.data.length, 10);
assert.equal(ctx.body.data[0].id, "b10");
});
// ── 汇总 ──────────────────────────────────────────────────────────────
console.log(`\n=== 结果: ${passed} 通过 / ${failed} 失败 ===\n`);
process.exit(failed === 0 ? 0 : 1);