import test from "node:test"; import assert from "node:assert/strict"; import {createHash} from "node:crypto"; import {existsSync, readFileSync} from "node:fs"; import {fileURLToPath} from "node:url"; import { BACK_MIRROR_AXIS, buildBoardIndex, connectorPinGroups, displayBounds, displayPoint, extractPathResistors, findCandidates, generateAdcSnippet, identityMatch, isValidRtlPortName, itemVisibleOnSide, mirrorBoardX, parseBoardQuery, resolveExactNetName, sameNetMembers, sameNetPins, searchBoard, } from "../../tools/board-viewer/web/board-logic.mjs"; function resolveGeneratedAsset(name) { // Live repo: tools/board-viewer/generated; compact package: evidence/board-viewer. const candidates = [ new URL(`../../tools/board-viewer/generated/${name}`, import.meta.url), new URL(`../../evidence/board-viewer/${name}`, import.meta.url), new URL(`../evidence/board-viewer/${name}`, import.meta.url), ]; for (const url of candidates) { const path = fileURLToPath(url); if (existsSync(path)) { return url; } } return candidates[0]; } function pin(overrides = {}) { return { id: "fixture-pin", number: "1", pad_role: "contact", net: "UART_A_TX", summary: "UART transmit", path: ["CON10.1", "UART_A_TX", "FPGA A1"], mechanical: false, electrical: true, direction: "output", external_level: "3.3V LVCMOS", function_category: "uart_tx", reserved: false, fixed_load_conflict: false, board_pull: null, adc_pulltype: null, programming: { status: "verified_fpga", conclusion: "FPGA 输出 UART_A_TX", network_explanation: "连接器网络 UART_A_TX 直达 FPGA", hdl_guidance: "RTL 端口方向应为 output", connection_guidance: ["连接到对端设备的接收端(RX)。"], constraints: ["LOCATION = A1", "IOSTANDARD = LVCMOS33"], risks: ["仍需检查当前工程约束冲突。"], evidence_tier: "cross_verified", sources: ["fixture"], }, evidence_tier: "cross_verified", fpga: { ball: "A1", board_signal: "UART_A_TX", io_standard: "LVCMOS33", capabilities: ["gpio", "uart_tx"], evidence_tier: "cross_verified", sources: ["fixture"], }, recommendation: {eligible: true, reasons: []}, ...overrides, }; } function resistor(overrides = {}) { return { reference: "R12", category: "R", component_value: "22R", value_ohms: 22, value_tokens: ["22r", "22", "22ohm"], summary: "电阻 22R · NET_A↔NET_B", position: {x: 1, y: 1}, view_position: {x: 1, y: 1}, rotation: 0, bounds: {x: 0, y: 0, width: 1, height: 1}, view_bounds: {x: 0, y: 0, width: 1, height: 1}, side: "front", pads: [ { number: "1", net: "NET_A", position: {x: 0, y: 0}, view_position: {x: 0, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, { number: "2", net: "NET_B", position: {x: 1, y: 0}, view_position: {x: 1, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, ], ...overrides, }; } function boardData() { return { resistors: [ resistor(), resistor({ reference: "R1225", component_value: "10k", value_ohms: 10000, value_tokens: ["10k", "10000", "10000r"], pads: [ { number: "1", net: "OTHER", position: {x: 2, y: 0}, view_position: {x: 2, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, { number: "2", net: "OTHER2", position: {x: 3, y: 0}, view_position: {x: 3, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, ], }), resistor({ reference: "R7", component_value: "4.7k", value_ohms: 4700, value_tokens: ["4.7k", "4k7", "4700", "4700r"], pads: [ { number: "1", net: "PUL1", position: {x: 4, y: 0}, view_position: {x: 4, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, { number: "2", net: "GND", position: {x: 5, y: 0}, view_position: {x: 5, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, ], }), resistor({ reference: "R674", component_value: "", value_ohms: null, value_tokens: [], pads: [ { number: "1", net: "BANK0_GPIO15", position: {x: 6, y: 0}, view_position: {x: 6, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, { number: "2", net: "PUL1", position: {x: 7, y: 0}, view_position: {x: 7, y: 0}, pad_role: "electrical", size: {width: 0.5, height: 0.5, drill_width: 0, drill_height: 0}, }, ], }), ], touchpoints: [ { reference: "CON78", category: "CON", summary: "UART2 RS-232 connector through U23", pins: [ pin({ number: "1", net: "RS232_TX2", path: ["CON78.1 RS232_TX2", "U23", "UART2_TX", "FPGA M10"], external_level: "RS232", reserved: true, fpga: { ball: "M10", board_signal: "UART2_TX", io_standard: "LVCMOS33", capabilities: ["gpio", "uart_tx", "rs232_via_transceiver"], evidence_tier: "cross_verified", sources: ["fixture"], }, recommendation: {eligible: false, reasons: ["reserved"]}, programming: { status: "verified_fpga", conclusion: "FPGA 输出 UART2_TX 经 U23 转为 RS-232", network_explanation: "连接器侧网络 RS232_TX2 对应逻辑侧 UART2_TX", hdl_guidance: "RTL 端口方向应为 output", connection_guidance: ["连接到对端设备的接收端(RX)。", "不能直接接 3.3V TTL/CMOS 串口。"], constraints: ["LOCATION = M10", "IOSTANDARD = LVCMOS33"], risks: ["当前功能已保留。"], evidence_tier: "cross_verified", sources: ["fixture"], }, }), ], }, { reference: "CON10", category: "CON", summary: "Verified UART fixture", pins: [pin()], }, { reference: "J2", category: "J", summary: "PWM fixture", pins: [ pin({ number: "7", net: "FAN_PWM_TEST", summary: "Fan PWM", function_category: "pwm", board_pull: "10k external pull-up to 3.3V", fpga: { ball: "B2", board_signal: "FAN_PWM_TEST", io_standard: "LVCMOS33", capabilities: ["gpio", "gpio_output", "pwm"], evidence_tier: "cross_verified", sources: ["fixture"], }, }), pin({ number: "8", net: "FAN_PWM_PULLTYPE", function_category: "pwm", adc_pulltype: "PULLUP", fpga: { ball: "B3", board_signal: "FAN_PWM_PULLTYPE", io_standard: "LVCMOS33", capabilities: ["gpio", "gpio_output", "pwm"], evidence_tier: "cross_verified", sources: ["fixture"], }, }), ], }, { reference: "TP3", category: "TP", summary: "Unverified test point", pins: [ pin({ net: "MYSTERY", external_level: "unknown", evidence_tier: "unknown", fpga: null, recommendation: {eligible: false, reasons: ["pin_evidence_not_verified"]}, }), ], }, ], }; } test("search covers reference, pin, net, function, capability, and FPGA ball", () => { const data = boardData(); assert.equal(searchBoard(data, "CON78")[0].reference, "CON78"); assert.equal(searchBoard(data, "CON78.1")[0].pinNumber, "1"); assert.equal(searchBoard(data, "rs232_tx2")[0].reference, "CON78"); assert.equal(searchBoard(data, "uart_tx")[0].reference, "CON10"); assert.equal(searchBoard(data, "rs232_via_transceiver")[0].reference, "CON78"); assert.equal(searchBoard(data, "m10")[0].pinNumber, "1"); assert.ok(searchBoard(data, "对端设备的接收端").some((result) => result.reference === "CON78")); assert.equal(searchBoard(data, "不能直接接 3.3v ttl")[0].reference, "CON78"); assert.deepEqual(searchBoard(data, "does-not-exist"), []); }); test("back view mirrors X about the vertical/Y axis for KiCad --mirror SVGs", () => { assert.equal(BACK_MIRROR_AXIS, "y"); assert.equal(mirrorBoardX(233.275, 430), 196.725); assert.deepEqual(displayPoint({x: 10, y: 5}, 100, "front"), {x: 10, y: 5}); assert.deepEqual(displayPoint({x: 10, y: 5}, 100, "back"), {x: 90, y: 5}); assert.deepEqual( displayBounds({x: 10, y: 5, width: 4, height: 2}, 100, "back"), {x: 86, y: 5, width: 4, height: 2}, ); assert.equal(itemVisibleOnSide({side: "back"}, "back"), true); assert.equal(itemVisibleOnSide({side: "back"}, "front"), false); assert.equal(itemVisibleOnSide({side: "front"}, "front"), true); }); test("pass D/E: exact resistor queries never false-positive on FPGA balls or R1225", () => { const data = boardData(); data.touchpoints[0].pins[0].fpga.ball = "R7"; data.touchpoints[0].pins[0].path = ["CON78.1", "R63 22R", "FPGA R7"]; const r7 = searchBoard(data, "R7"); assert.equal(r7[0].type, "resistor"); assert.equal(r7[0].reference, "R7"); assert.ok(!r7.some((item) => item.type === "pin" && item.matchedField === "fpga_ball")); const r12 = searchBoard(data, "R12"); assert.equal(r12[0].type, "resistor"); assert.equal(r12[0].reference, "R12"); assert.ok(!r12.some((item) => item.reference === "R1225")); assert.equal(searchBoard(data, "R674")[0].type, "resistor"); assert.equal(searchBoard(data, "r674.2")[0].type, "resistor_pad"); assert.equal(searchBoard(data, "r674.2")[0].pinNumber, "2"); assert.equal(identityMatch("R1225", "R12"), 0); assert.equal(identityMatch("R12", "R12"), 3); }); test("pass C/F: value and net search cover resistors; sameNetMembers includes resistor pads", () => { const data = boardData(); assert.equal(parseBoardQuery("4k7").kind, "value"); assert.equal(parseBoardQuery("R674").kind, "resistor_ref"); assert.equal(parseBoardQuery("ball:R7").kind, "ball"); assert.ok(searchBoard(data, "4k7").some((item) => item.reference === "R7")); assert.ok(searchBoard(data, "22R").some((item) => item.reference === "R12")); assert.ok(searchBoard(data, "PUL1").some((item) => item.reference === "R7" || item.reference === "R674")); assert.ok(searchBoard(data, "net:PUL1").some((item) => item.reference === "R674")); const members = sameNetMembers(data, "PUL1"); assert.ok(members.some((item) => item.kind === "resistor_pad" && item.reference === "R7")); assert.ok(members.some((item) => item.kind === "resistor_pad" && item.reference === "R674")); // Compatibility: sameNetPins stays touchpoint-only. assert.ok(sameNetPins(data, "PUL1").every((item) => item.kind === "touchpoint")); assert.ok(buildBoardIndex(data).resistorByReference.has("R674")); }); test("pass D: ball:R7 and U3.R7 disambiguate FPGA balls from resistor R7", () => { const data = boardData(); data.touchpoints[0].pins[0].fpga.ball = "R7"; data.touchpoints[0].pins[0].path = ["CON78.1", "BANK0", "U3.R7"]; assert.equal(searchBoard(data, "R7")[0].type, "resistor"); const ball = searchBoard(data, "ball:R7"); assert.ok(ball.some((item) => item.type === "pin" && item.pin?.fpga?.ball === "R7")); assert.ok(searchBoard(data, "U3.R7").some((item) => item.reference === "CON78")); }); test("pass G path jump extracts annotation resistors and fails closed on missing index", () => { const data = boardData(); const found = extractPathResistors(data, ["CON78.1", "R7 4.7k", "U3.R4", "FPGA M10"], ["R12 series"]); assert.deepEqual(found.map((item) => item.reference), ["R7", "R12"]); assert.throws( () => extractPathResistors(data, ["R99999 missing"]), /R99999 missing from resistor index/, ); }); test("search covers verified MCU device, package pin, signal, and capability", () => { const data = boardData(); const mcuPin = data.touchpoints.find((item) => item.reference === "TP3").pins[0]; mcuPin.summary = "GD32 firmware test point"; mcuPin.path = []; mcuPin.programming = { status: "verified_mcu", conclusion: "Verified MCU test point", network_explanation: "Verified MCU path", hdl_guidance: "Use from firmware", connection_guidance: [], constraints: [], risks: [], evidence_tier: "cross_verified", sources: ["fixture"], }; mcuPin.mcu = { device: "U27", family: "GD32F303CGT6", pin: "10", signal: "PA0", capabilities: ["gpio", "adc_input"], evidence_tier: "cross_verified", sources: ["fixture"], }; assert.equal(searchBoard(data, "u27.10")[0].reference, "TP3"); assert.equal(searchBoard(data, "gd32f303")[0].reference, "TP3"); assert.equal(searchBoard(data, "pa0")[0].reference, "TP3"); assert.equal(searchBoard(data, "adc_input")[0].reference, "TP3"); assert.ok(!findCandidates(data, "gpio").some((item) => item.reference === "TP3")); }); test("same-net lookup returns every matching pad and ignores empty nets", () => { const data = boardData(); data.touchpoints[1].pins.push(pin({number: "2", net: "RS232_TX2"})); assert.deepEqual( sameNetPins(data, "RS232_TX2").map((item) => `${item.reference}.${item.pinNumber}`), ["CON10.2", "CON78.1"], ); assert.deepEqual(sameNetPins(data, ""), []); }); test("candidate filtering is fail-closed and sorted by natural reference and pin", () => { const candidates = findCandidates(boardData(), "uart_tx"); assert.deepEqual(candidates.map((item) => `${item.reference}.${item.pin.number}`), ["CON10.1"]); assert.match(candidates[0].reason, /已验证 FPGA 路径/); assert.match(candidates[0].warning, /当前工程约束冲突/); }); test("candidate filters recognize canonical board capability aliases", () => { const aliases = [ ["pwm", "pwm_output"], ["gpio_output", "digital_output"], ["gpio_input", "digital_input"], ["tach", "tach_input"], ["fan_tach", "tach_input"], ["presence", "presence_input"], ]; for (const [filter, capability] of aliases) { const data = { touchpoints: [{ reference: "CON1", category: "CON", summary: "Alias fixture", pins: [pin({ fpga: { ball: "A1", board_signal: "ALIAS_SIGNAL", io_standard: "LVCMOS33", capabilities: ["gpio", capability], evidence_tier: "cross_verified", sources: ["fixture"], }, })], }], }; assert.equal(findCandidates(data, filter).length, 1, `${filter} -> ${capability}`); } }); test("generic GPIO candidates exclude dedicated tach, PWM, presence, and protocol pins", () => { const data = { touchpoints: [{ reference: "CON1", category: "CON", summary: "Mixed GPIO fixture", pins: [ pin({number: "1", function_category: "gpio", summary: "Direct bidirectional GPIO"}), pin({number: "2", function_category: "fan_tach", summary: "Fan tach input"}), pin({number: "3", function_category: "pwm", summary: "Open-collector PWM"}), pin({number: "4", function_category: "presence", summary: "Presence input"}), ], }], }; assert.deepEqual( findCandidates(data, "gpio").map((item) => `${item.reference}.${item.pin.number}`), ["CON1.1"], ); }); test("candidate reason exposes the pin purpose and non-default polarity", () => { const data = { touchpoints: [{ reference: "CON31", category: "CON", summary: "Fan connector", pins: [pin({ function_category: "pwm", summary: "风扇 PWM 开集电极下拉输出", active_level: "connector low", polarity: "FPGA high -> connector low", fpga: { ball: "E10", board_signal: "FAN_GPIO6", io_standard: "LVCMOS33", capabilities: ["gpio", "pwm_output", "fan_pwm"], evidence_tier: "cross_verified", sources: ["fixture"], }, })], }], }; const [candidate] = findCandidates(data, "pwm"); assert.match(candidate.reason, /风扇 PWM 开集电极下拉输出/); assert.match(candidate.reason, /FPGA high -> connector low/); }); test("product candidate filters keep dedicated functions out of generic GPIO", () => { const boardDataPath = resolveGeneratedAsset("board-data.json"); const buildInfoPath = resolveGeneratedAsset("build-info.json"); const expectationPath = new URL("./fixtures/candidate_count_expectation.json", import.meta.url); const boardDataBytes = readFileSync(boardDataPath); const buildInfoBytes = readFileSync(buildInfoPath); const data = JSON.parse(boardDataBytes); const expectation = JSON.parse(readFileSync(expectationPath, "utf8")); const boardDataSha = createHash("sha256").update(boardDataBytes).digest("hex"); const buildInfoSha = createHash("sha256").update(buildInfoBytes).digest("hex"); assert.equal(expectation.schema, "prod2u-board-viewer-candidate-count-expectation-v1"); assert.equal(boardDataSha, expectation.bound_to.board_data_sha256); assert.equal(buildInfoSha, expectation.bound_to.build_info_sha256); assert.equal(boardDataSha, expectation.bound_to.board_data_asset_sha256); for (const [capability, expectedCount] of Object.entries(expectation.candidate_counts)) { const candidates = findCandidates(data, capability); assert.equal(candidates.length, expectedCount, `${capability} count`); if (Array.isArray(expectation.candidate_keys?.[capability])) { assert.deepEqual( candidates.map((item) => `${item.reference}.${item.pin.number}`), expectation.candidate_keys[capability], `${capability} keys`, ); } } assert.ok(findCandidates(data, "gpio").every((item) => item.pin.function_category === "gpio")); }); test("unknown, inferred, power, ground, mechanical, reserved, and fixed-load pins are never candidates", () => { const blockers = [ {evidence_tier: "unknown"}, {evidence_tier: "name_inferred"}, {function_category: "power", net: "+3V3"}, {function_category: "ground", net: "GND"}, {mechanical: true, electrical: false}, {pad_role: "shield"}, {pad_role: "unknown"}, {reserved: true}, {fixed_load_conflict: true}, ]; for (const [index, override] of blockers.entries()) { const data = {touchpoints: [{reference: `J${index + 1}`, category: "J", summary: "", pins: [pin(override)]}]}; assert.deepEqual(findCandidates(data, "uart_tx"), []); } }); test("connector groups follow reviewed board-front order and separate auxiliary pads", () => { const touchpoint = { reference: "CON78", connector: { review_status: "cross_verified", contact_order: ["1", "2", "3", "4"], contact_grid: [["1"], ["2"], ["3"], ["4"]], }, pins: [ pin({id: "shield-5", number: "5", pad_role: "shield"}), pin({id: "contact-4", number: "4"}), pin({id: "contact-2", number: "2"}), pin({id: "mechanical-1", number: "", pad_role: "mechanical", mechanical: true, electrical: false}), pin({id: "contact-1", number: "1"}), pin({id: "contact-3", number: "3"}), ], }; const groups = connectorPinGroups(touchpoint); assert.deepEqual(groups.contactRows.map((row) => row.map((item) => item.number)), [["1"], ["2"], ["3"], ["4"]]); assert.deepEqual(groups.contacts.map((item) => item.number), ["1", "2", "3", "4"]); assert.deepEqual(groups.auxiliary.map((item) => item.id), ["shield-5", "mechanical-1"]); }); test("unknown connector layout never invents contact ordering", () => { const touchpoint = { reference: "CON1", connector: {review_status: "unknown", contact_order: [], contact_grid: []}, pins: [pin({id: "unknown-1", pad_role: "unknown"})], }; assert.deepEqual(connectorPinGroups(touchpoint), { contactRows: [], contacts: [], auxiliary: [touchpoint.pins[0]], }); }); test("RTL port names reject syntax that could escape an ADC assignment", () => { for (const name of ["uart_tx", "fan_pwm_out[3]", "_debug$signal"]) { assert.equal(isValidRtlPortName(name), true, name); } for (const name of ["", "3bad", "a b", "a;set", "name[foo]", "{signal}", "a\nnext"]) { assert.equal(isValidRtlPortName(name), false, name); } }); test("ADC generation requires current verified eligible data and omits implicit PULLTYPE", () => { const data = boardData(); const pwm = data.touchpoints[2].pins[0]; const snippet = generateAdcSnippet(pwm, "fan_pwm_out[3]", {adcCopyEnabled: true}); assert.equal( snippet, "set_pin_assignment { fan_pwm_out[3] } { LOCATION = B2; IOSTANDARD = LVCMOS33; }", ); assert.doesNotMatch(snippet, /PULLTYPE/); assert.throws(() => generateAdcSnippet(pwm, "a;bad", {adcCopyEnabled: true}), /合法的 RTL 端口名/); assert.throws(() => generateAdcSnippet(pwm, "fan_pwm_out", {adcCopyEnabled: false}), /源数据已过期/); assert.throws( () => generateAdcSnippet(data.touchpoints[0].pins[0], "uart2_tx", {adcCopyEnabled: true}), /不具备 ADC 生成资格/, ); }); test("ADC generation includes PULLTYPE only when curated annotation explicitly supplies it", () => { const pinWithPulltype = boardData().touchpoints[2].pins[1]; assert.equal( generateAdcSnippet(pinWithPulltype, "fan_pwm_aux", {adcCopyEnabled: true}), "set_pin_assignment { fan_pwm_aux } { LOCATION = B3; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }", ); }); test("pass C/D: 0805 is not a resistance query; 0R/120R grammar; bare PUL1 exact net", () => { const data = boardData(); // Inject path text noise that must NOT match bare exact-net PUL1. data.touchpoints[0].pins[0].path = ["mentions PUL1 in prose only", "FPGA M10"]; data.touchpoints[0].pins[0].net = "RS232_TX2"; assert.notEqual(parseBoardQuery("0805").kind, "value"); assert.equal(parseBoardQuery("0R").kind, "value"); assert.equal(parseBoardQuery("120R").kind, "value"); assert.equal(resolveExactNetName(data, "PUL1"), "PUL1"); const bare = searchBoard(data, "PUL1"); const prefixed = searchBoard(data, "net:PUL1"); assert.deepEqual( bare.map((item) => `${item.type}:${item.reference}.${item.pinNumber}`).sort(), prefixed.map((item) => `${item.type}:${item.reference}.${item.pinNumber}`).sort(), ); assert.ok(bare.every((item) => item.matchedField === "net")); assert.ok(!bare.some((item) => item.reference === "CON78")); // Fixture 4k7 grammar still works on synthetic R7. assert.ok(searchBoard(data, "4k7").some((item) => item.reference === "R7")); });