import { expect, test } from "bun:test"; import ky from "ky"; import { DatalinkEntitySchema } from "./types.js"; import { buildSafeRecordEditPayload, compileRecordPredicate, parseSetClause, safeEditRecord } from "./services.js"; const entity = DatalinkEntitySchema.parse({ id: "entity", fields: [ { name: "E_entity_a", label: "金额", type: "number" }, { name: "E_entity_b", label: "金额", type: "number" }, ] }); test("筛选、赋值和 JSON 安全合并均拒绝歧义标签", () => { expect(() => compileRecordPredicate("金额 == 10", entity)).toThrow("歧义"); expect(() => parseSetClause("金额=10", entity)).toThrow("歧义"); expect(() => buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: entity.fields, patchForm: { 金额: 10 } })).toThrow("歧义"); }); test("明确物理键即使与另一个字段的标签冲突,也保持唯一目标", () => { const collision = DatalinkEntitySchema.parse({ id: "entity", fields: [ { name: "E_entity_a", label: "E_entity_b", type: "number" }, { name: "E_entity_b", label: "金额", type: "number" }, ] }); expect(parseSetClause("E_entity_b=10", collision)).toEqual({ E_entity_b: 10 }); expect(compileRecordPredicate("E_entity_b == 10", collision)({ E_entity_a: 1, E_entity_b: 10 })).toBe(true); const payload = buildSafeRecordEditPayload({ entityId: entity.id, recordId: "r", fields: collision.fields, patchForm: { E_entity_b: 10 } }); expect(payload.form.E_entity_b).toBe(10); expect(payload.form.E_entity_a).toBeUndefined(); }); test("模糊匹配不唯一时拒绝;物理短名、唯一标签和未知字段兼容保留", () => { const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [ { name: "E_entity_a", label: "原始金额", type: "number" }, { name: "E_entity_b", label: "折算金额", type: "number" }, ] }); expect(() => parseSetClause("金额=10", fields)).toThrow("歧义"); expect(parseSetClause("a=10,折算金额=20,active=true", fields)).toEqual({ E_entity_a: 10, E_entity_b: 20, active: true }); }); test("安全编辑遇到歧义字段在发出写请求前终止", async () => { const requests: string[] = []; const client = ky.create({ prefix: "https://tenant.invalid", fetch: async input => { requests.push(String(input)); return Response.json({}); } }); await expect(safeEditRecord(client, "corp", { entityId: entity.id, recordId: "r", detail: { id: "r" }, fields: entity.fields, patchForm: { 金额: 10 } })).rejects.toThrow("歧义"); expect(requests).toEqual([]); }); test("未声明的系统字段保留原语义,不会模糊匹配 inactive 等业务标签", () => { const fields = DatalinkEntitySchema.parse({ id: "entity", fields: [{ name: "E_entity_old", label: "inactive", type: "text" }] }); expect(compileRecordPredicate("active == true", fields)({ active: true, E_entity_old: false })).toBe(true); expect(parseSetClause("active=true", fields)).toEqual({ active: true }); });