Files
Aislo/resources/tester/helper_346_2_pipeline_cross_page.cjs
T
eomsangdonandClaude Opus 5.5 bdd6255763 fix(계산묶음): 349-0r cross 입력에 암 경계 기본값 — 초안 새 측점도 서버 config 값(화면이 문맥에서 기억)
- design_pipeline_cross pipelineCrossSource 입력에 rockBoundaryDefaultM: readRockBoundaryDefault(projectId)
- 그 모듈을 가짜로 갈음하는 도움 파일 10개 가짜에 readRockBoundaryDefault: () => -0.5
- 검증_sub2b 같은 끌기(진짜 cross 입력 길): 미리보기 1,184.7 대 정본 1,184.0
- 시험: 바뀐 도움 파일 시험 10 + 349-0n · 0p = 77 통과 · typecheck 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QfHKQs7J3hQELKMWQMUJEy
2026-10-16 17:06:58 +09:00

332 lines
12 KiB
JavaScript

/* PLAN 346-1 · 346-2 붙임 단위검증 헬퍼 — 페이지 묶음에 cross · masshaul · haul · drainage · corridor 를
* 붙인 것. 진짜 TS(`design_pipeline_page` · `_cross` · 단계 파일 전부)를 그 자리에서 트랜스파일해 Node 로
* 돌림. 서버 창구(노선 · 구조물 · 관 목록 · 지형 격자 · 표준단면 · 흙 배분 fetch)만 가짜.
* 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_346_2_pipeline_cross_page.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,
})),
};
}
async function run() {
const P = "proj-3462";
window.localStorage.setItem("frd_current_project_id", P); // 지금 프로젝트(노선 0 칸 자리)
const savedBase = await savedBaseOf();
const seedRuns = runs().length;
const adopted = [];
let redraws = 0;
let corridor = 0;
const drainage = [];
const link = {
pipelineSource: () => ({
base: savedBase,
edits: alignment.emptyEdits(),
detail: job.detail,
routeId: 7,
}),
adoptPipeline: (base, edits, draft) => adopted.push({ draft, saved: base === savedBase }),
redraw: () => (redraws += 1),
side: {
pipelineStage: (ctx) => {
drainage.push(ctx.inputs.route !== null);
return null;
},
},
};
const bridge = pageMod.routeDraftBridge(P, link, {
stationIntervalM: job.interval,
onCorridorStale: () => (corridor += 1),
});
pageMod.pipelineEarthwork(P, { conversion: job.conversion });
const pipe = pageMod.pagePipeline(P);
const commits = [];
pipe.subscribe((e) => e.kind === "stage" && commits.push(`${e.stage}@${e.generation}`));
// ① 열 때 한 번 — 저장 노선 · 발자국 · 뒤 단계는 초안 없으니 3D 낡음 · 흙 배분 안 함
const openRun = await settle(seedRuns + 1);
await tick(job.haulDelayMs + 20);
const open = {
outcome: openRun.outcome,
stages: openRun.stages,
footprint: pipe.output("footprint")?.records.length ?? 0,
crossCount: Object.keys(pipe.output("cross")?.byKey ?? {}).length,
stations: pipe.output("ground").stations.length,
carried: Object.keys(pipe.input("cross")?.byKey ?? {}).length,
corridor,
haulCalls: haul.calls,
detail: pageMod.pipelineDetail(P),
pipeKeys: pipe
.output("ground")
.stations.filter((s) => s.kind === "pipe")
.map((s) => [s.key, s.chainageM]),
};
// ② 늦은 응답 버림 — 끝점 옮김(흙 배분 기다리는 중) → 바로 첫 점 옮김
bridge.edited(draftOf(shift(n - 1, 6, -4)));
const runA = await settle(runs().length + 1);
await tick(2);
bridge.edited(draftOf(shift(0, -5, 3)));
const runB = await settle(runs().length + 1);
await tick(job.haulDelayMs + 30);
const genA = runA.generation;
const genB = runB.generation;
const ground = pipe.output("ground");
const profile = pipe.output("profile");
const shown = pageMod.pipelineDetail(P);
const mass = pipe.output("masshaul");
const moved = {
run: {
outcome: runB.outcome,
stages: runB.stages,
totalMs: runB.totalMs,
sources: runB.sources,
},
line: pipe.output("route").line,
curves: pipe.output("route").curves,
stations: ground.stations.map((s) => ({
key: s.key,
kind: s.kind,
chainage: s.chainageM,
uphill: detailMod.uphillSide(s),
elevation: alignment.planElevationAt(profile, s.chainageM),
planRadius: s.planRadiusM,
outer: s.curveOuterSide,
widening: s.curveWideningM,
cut: pipe.output("cross").byKey[s.key]?.cutAreaM2 ?? null,
fill: pipe.output("cross").byKey[s.key]?.fillAreaM2 ?? null,
})),
finalCumulative: mass?.haulInput?.final_cumulative_m3 ?? null,
footprint: pipe.output("footprint")?.records.length ?? 0,
detail: shown && {
sections: shown.cross_sections.length,
designs: shown.cross_sections.filter((s) => s.design).length,
longitudinal: shown.longitudinal.samples.length,
stationIds: shown.longitudinal.stations.length,
profileMatches: shown.longitudinal.profile_alignment === profile,
},
alignmentDraft: editMod.readAlignmentDraft(pageMod.DRAFT_ROUTE_ID),
adoptedLast: adopted[adopted.length - 1],
redraws,
corridor,
drainage,
};
const late = {
genA,
genB,
haulCommits: commits.filter((c) => c.startsWith("haul@")),
haul: { ...haul },
};
// ③ 계획고 고침(초안 동안) — 노선 0 칸에 남음
const edits = {
station_offsets: { [alignment.chainageKey(savedBase.stations[3].chainage_m)]: 0.4 },
curve_radii: {},
};
const draftEdits = editMod.createProfileEditStore(
pageMod.DRAFT_ROUTE_ID,
alignment.emptyEdits(),
() => undefined,
);
draftEdits.replace(edits);
pageMod.pipelineGrade(P, edits);
const gradeRun = await settle(runs().length + 1);
const gradeDraft = {
pending: editMod.pendingAlignment(pageMod.DRAFT_ROUTE_ID),
sources: gradeRun.sources,
stages: Object.keys(gradeRun.stages),
};
// ④ 열 때로(초안 버림) — 노선 0 칸 · 새 노선 상세 비움
bridge.edited(null);
await settle(runs().length + 1);
await tick(20);
const reverted = {
detail: pageMod.pipelineDetail(P),
alignmentDraft: editMod.readAlignmentDraft(pageMod.DRAFT_ROUTE_ID),
pending: editMod.pendingAlignment(pageMod.DRAFT_ROUTE_ID),
adoptedLast: adopted[adopted.length - 1],
};
pageMod.disposePagePipeline(P);
page.clearDrafts(P);
return { open, moved, late, gradeDraft, reverted, n };
}
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);
});