Files
Aislo/resources/tester/helper_365_page_pipeline.cjs
T
eomsangdonandClaude Opus 5.5 7efee22ab4 feat(365-2): 횡단 고침 → 묶음 cross 입력 · 입력 지문 고리(최대 3바퀴)
- 횡단 입력 = 부를 때마다 저장 상세 + 세션 고침(지반 유형 · 측구 · 2단 경사 · 암 경계 · 암 경사 · 측점 열쇠) + 표준 — 상세 객체마다 기억 걷음
- B06 고침(DesignSync 다시 셈 끝 · 암 경계) 뒤 pipelineCross — 노선 초안 동안 B06 고침이 카드(새 노선 상세)에 보임
- 고리 — 열 때 · 페이지 들어올 때 입력(세션 · 가게)을 묶음 입력(넘긴 값 · follow 뒤 값)과 견줌 · 다르면 한 바퀴 · 끝난 뒤 다시 · 3바퀴 넘으면 「계산 불안정」 한 줄
- 시험 test_365_page_pipeline(초안 동안 고침 카드 · 같은 입력 0바퀴 · 세션만 바뀜 1바퀴 · 불안정 3바퀴 알림 1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TteK8mfYZetk5P3bEZkyVZ
2026-10-17 12:08:22 +09:00

327 lines
12 KiB
JavaScript

/* PLAN 365 단위검증 헬퍼 — 묶음 주인 = 페이지(초안 둔 채 열기 · B06 바로 열기 · 새로고침). 진짜 TS
* (`design_pipeline_page` · 단계 파일 전부)를 그 자리에서 트랜스파일해 Node 로 돌림 · 서버 창구만 가짜
* (틀 = `helper_346_2_pipeline_cross_page.cjs`). 입력 argv[2] JSON · argv[3] 격자 이진 · 결과 = 표준출력 JSON.
* 짝 = `test_365_page_pipeline.py`. */
const fs = require("fs");
const path = require("path");
const ts = require(path.join(__dirname, "..", "..", "config", "node_modules", "typescript"));
const CATALOG = require("./helper_322_catalog_module.cjs");
const ROOT = path.join(__dirname, "..", "..");
const job = JSON.parse(fs.readFileSync(process.argv[2], "utf8"));
function memoryStorage() {
const map = new Map();
return {
getItem: (key) => (map.has(key) ? map.get(key) : null),
setItem: (key, value) => map.set(key, String(value)),
removeItem: (key) => map.delete(key),
key: (index) => [...map.keys()][index] ?? null,
get length() {
return map.size;
},
};
}
globalThis.window = {
sessionStorage: memoryStorage(),
localStorage: memoryStorage(),
setTimeout,
clearTimeout,
};
// 흙 배분 서버 — 늦게 답함 · 끊기면 버림
const haul = { calls: 0, aborted: 0, answered: 0 };
globalThis.fetch = (url, init) =>
new Promise((resolve, reject) => {
haul.calls += 1;
const timer = setTimeout(() => {
haul.answered += 1;
resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) });
}, job.haulDelayMs);
init.signal.addEventListener("abort", () => {
clearTimeout(timer);
haul.aborted += 1;
reject(new Error("aborted"));
});
});
const STUBS = {};
const cache = new Map();
function loadTs(full) {
if (cache.has(full)) return cache.get(full);
const js = ts.transpileModule(fs.readFileSync(full, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
const box = { exports: {} };
cache.set(full, box.exports);
const localRequire = (request) => {
if (CATALOG.isCatalogRequest(request)) return CATALOG;
const key = Object.keys(STUBS).find((name) => request.endsWith(name));
if (key) return STUBS[key];
if (request.startsWith("@config/")) return { API_BASE_URL: "http://fake" };
if (request.startsWith("@util/"))
return loadTs(path.join(ROOT, "common_util", `${request.slice(6)}.ts`));
if (request.startsWith(".")) return loadTs(path.join(path.dirname(full), `${request}.ts`));
return require(request);
};
new Function("exports", "module", "require", js)(box.exports, box, localRequire);
return box.exports;
}
const load = (...parts) => loadTs(path.join(ROOT, ...parts));
const sampler = load("common_util", "common_util_surface_sampler.ts");
const bytes = fs.readFileSync(process.argv[3]);
const grid = sampler.parseDtmGrid(
bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length),
);
const local = { grid, design: "las" };
STUBS["B05_Profile_Api_Replan"] = {
analysisTerrain: () => "las",
fetchRoutePlan: async () => ({
planned: job.line,
curves: [],
min_radius_m: job.minRadius,
station_snap: false,
}),
};
STUBS["B05_Profile_Api_Structures"] = {
fetchStructures: async () => ({ structures: [] }),
fetchStructureTypes: async () => job.types,
};
STUBS["B05_Profile_Api_TerrainGrid"] = {
loadDesignTerrainGrid: async () => local,
groundStageDeps: () => ({ grid: () => local, remote: async () => [] }),
};
STUBS["B04_PreProcess_Api_Fetch"] = {
fetchDetailPipePoints: async () => ({
pipe_points: job.pipes.map((pipe) => ({ ...pipe, lonlat: [0, 0] })),
}),
};
STUBS["B06_Section_UI_Standard_Panel"] = {
effectiveStandardCross: () => job.standard,
readRockBoundaryDefault: () => -0.5,
};
const pipeMod = load("A00_Common", "design", "logic", "design_pipeline.ts");
const pageMod = load("A00_Common", "design", "design_pipeline_page.ts");
const stationsMod = load("A00_Common", "design", "logic", "design_pipeline_stations.ts");
const routeGround = load("B05_Profile", "logic", "B05_Profile_Pipeline_RouteGround.ts");
const grade = load("B05_Profile", "logic", "B05_Profile_Pipeline_Grade.ts");
const gradeGround = load("B05_Profile", "logic", "B05_Profile_Grade_Ground.ts");
const detailMod = load("B05_Profile", "logic", "B05_Profile_Pipeline_Detail.ts");
const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.ts");
const editMod = load("B05_Profile", "B05_Profile_UI_Profile_Edit.ts");
const page = load("A00_Common", "b_page_state.ts");
const tick = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));
const runs = () => globalThis.__aisloPipeline?.runs ?? [];
async function settle(count) {
for (let i = 0; i < 400; i += 1) {
const last = runs()[runs().length - 1];
if (runs().length >= count && last && last.outcome !== "running") return last;
await tick(5);
}
throw new Error("묶음이 끝나지 않음");
}
const n = job.nodes.length;
const draftOf = (nodes) => ({
nodes,
curveOn: Array(n).fill(true),
curveRadius: Array(n).fill(null),
curveLock: Array(n).fill(null),
curveArc: Array(n).fill(null),
stationSnap: false,
});
const shift = (index, dx, dy) =>
job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node));
/** 저장 기준 — 저장 노선 지반 첫 계획선(관 측점 포함 · 서버 정책 그대로). */
async function savedBaseOf() {
const seed = pipeMod.createDesignPipeline({
stages: {
route: routeGround.createRouteStage({
minRadiusM: () => job.minRadius,
savedLine: () => ({ line: job.line, curves: [] }),
}),
stations: stationsMod.createStationsStage({
intervalM: job.interval,
types: () => job.types,
}),
ground: routeGround.createGroundStage({ grid: () => local, remote: async () => [] }),
},
});
await seed.start({ route: null, alignment: null, cross: null, pipes: job.pipes, structures: [] });
const ground = seed.output("ground");
seed.dispose();
const samples = ground.longitudinal.chainageM.map((c, i) => ({
chainage_m: c,
elevation_m: ground.longitudinal.z[i],
}));
const profile = gradeGround.groundProfile(samples);
return {
policy: job.policy,
onlyExplicitCurves: false,
basePvi: gradeGround.groundFollowingBasePvi({
samples,
stations: ground.stations.map((s) => s.chainageM),
policy: job.policy,
}),
chainage: profile.chainage,
ground: profile.ground,
stations: ground.stations.map((s) => ({
station_id: grade.stationIdOf(s.chainageM),
chainage_m: s.chainageM,
})),
};
}
const store = load("A00_Common", "design", "design_store.ts");
const r3 = (value) => (typeof value === "number" ? Math.round(value * 1000) / 1000 : null);
/** 묶음 새 노선 상세(카드가 그리는 것) — 측점 · 계획고 · 절 · 성토 면적. */
function shownRows(P) {
const shown = pageMod.pipelineDetail(P);
return (
shown &&
shown.cross_sections.map((s) => [
r3(s.chainage_m),
r3(s.design?.design_elevation_m),
r3(s.design?.cut_area_m2),
r3(s.design?.fill_area_m2),
])
);
}
async function run() {
const P = "proj-365";
window.localStorage.setItem("frd_current_project_id", P); // 지금 프로젝트(노선 0 칸 자리)
const savedBase = await savedBaseOf();
const shop = store.useDesignStore(P, null);
const holds = [];
let unstable = 0;
const link = () => ({
pipelineSource: () => ({
base: savedBase,
edits: alignment.emptyEdits(),
detail: job.detail,
routeId: 7,
}),
adoptPipeline: () => undefined,
redraw: () => undefined,
});
const options = {
stationIntervalM: job.interval,
holdDraft: (_routeId, saved) => {
holds.push(saved === job.detail ? "saved" : saved ? "other" : "null");
return async () => "saved";
},
onUnstable: () => (unstable += 1),
};
const open = (label) => {
const bridge = pageMod.routeDraftBridge(P, link(), options);
pageMod.pipelineEarthwork(P, { conversion: job.conversion });
return { bridge, label };
};
const stationList = () => (shop.get("stations") ?? []).map((s) => r3(s.chainageM));
// ① B05 길 — 저장 노선으로 열고 노선 꼭짓점 옮김(초안)
const first = open("b05");
await settle(runs().length + 1);
first.bridge.edited(draftOf(shift(1, 8, -6)));
await settle(runs().length + 1);
await tick(20);
const b05 = { rows: shownRows(P), stations: stationList(), holds: [...holds] };
// ② 떠남(새로고침 · 묶음 메모리 버림) — 세션(가게) 초안은 남음 · 가게 측점은 비워 다시 내는지 봄
pageMod.disposePagePipeline(P);
const kept = shop.get("routeDraft") !== null;
shop.set("stations", null);
holds.length = 0;
// ③ B06 바로 열기 — 페이지가 묶음을 세움(편집기 없음) · 초안 그대로 셈
const again = open("b06");
const reopenRun = await settle(runs().length + 1);
await tick(20);
const b06 = {
rows: shownRows(P),
stations: stationList(),
holds: [...holds],
outcome: reopenRun.outcome,
stages: Object.keys(reopenRun.stages),
};
// ⑤ 초안 동안 B06 고침 — 세션 칸(측점 열쇠) → pipelineCross → 카드(묶음 새 노선 상세)
const pipe = pageMod.pagePipeline(P);
const target = pipe.output("ground").stations.find((s) => s.kind === "grid" && s.chainageM > 30);
const cell = (ground) => ({ [target.key]: { ground_type: ground, section_mode: "left_cut" } });
const groundAt = () =>
pageMod
.pipelineDetail(P)
.cross_sections.find((s) => Math.abs(s.chainage_m - target.chainageM) < 1e-3)?.design
?.ground_type ?? null;
const before = groundAt();
page.writeState("crossdesign", cell("blasting_rock"), P, 7);
let mark = runs().length;
pageMod.pipelineCross(P);
await settle(mark + 1);
await tick(20);
const edit = {
key: target.key,
before,
after: groundAt(),
input: pipe.input("cross").byKey[target.key]?.groundType ?? null,
runs: runs().length - mark,
sources: runs()[runs().length - 1].sources,
};
// ⑥ 고리 — 같은 입력 = 0 바퀴 · 세션만 바뀜(알림 없음) = 1 바퀴 · 안 맞음 = 3 바퀴 뒤 알림
mark = runs().length;
const same = await pageMod.reconcilePagePipeline(P);
const sameRuns = runs().length - mark;
page.writeState("crossdesign", cell("ripping_rock"), P, 7);
mark = runs().length;
const once = await pageMod.reconcilePagePipeline(P);
const loop = {
same,
sameRuns,
once,
onceRuns: runs().length - mark,
onceGround: groundAt(),
};
let n = 0;
const realStandard = STUBS["B06_Section_UI_Standard_Panel"].effectiveStandardCross;
STUBS["B06_Section_UI_Standard_Panel"].effectiveStandardCross = () => ({
...job.standard,
n: (n += 1),
});
mark = runs().length;
loop.unstable = await pageMod.reconcilePagePipeline(P);
loop.unstableRuns = runs().length - mark;
loop.alerts = unstable;
STUBS["B06_Section_UI_Standard_Panel"].effectiveStandardCross = realStandard;
await pageMod.reconcilePagePipeline(P);
// ④ 초안 버림 — 열 때 맡긴 초안 전 상세로 되돌림(저장 정본)
again.bridge.edited(null);
const dropRun = await settle(runs().length + 1);
await tick(20);
const dropped = {
detail: pageMod.pipelineDetail(P),
restoreWhy: dropRun.restoreWhy ?? null,
routeDraft: shop.get("routeDraft"),
};
pageMod.disposePagePipeline(P);
page.clearDrafts(P);
return { kept, b05, b06, dropped, edit, loop };
}
run()
.then((out) => {
process.stdout.write(JSON.stringify(out));
process.exit(0);
})
.catch((error) => {
process.stderr.write(String(error && error.stack ? error.stack : error));
process.exit(1);
});