/* 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 { makeLoader } = require("./helper_ts_stub_loader.cjs"); 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 { load, loadTs } = makeLoader({ root: ROOT, requireFor: (full) => (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); }, }); // 상세 가게 칸(472-5) — 실제는 상세 가게가 받을 때 채움 · 여기선 종단도가 내주는 저장 상세 그대로 const slots = () => load("B06_Section", "B06_Section_Section_Canon.ts"); /** 이 시험은 묶음 여럿(P · Q · B)이 같은 종단도 흉내를 씀 — 칸 = 지금 연 프로젝트. */ const here = () => window.localStorage.getItem("frd_current_project_id"); 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"); // B05 오른쪽 횡단 판(365-3) — 그림 조각만 가짜 · 값 고르기는 진짜 STUBS["b_svg_zoom_pan"] = { attachSvgZoomPan: () => undefined }; STUBS["B05_Profile_UI_RouteEdit_Cross_Draw"] = { CROSS_PLOT_PAD: {}, summarizeCross: () => "" }; STUBS["B05_Profile_UI_RouteEdit_Chrome"] = { sidePanelsOf: new WeakMap() }; // 판 양식(382-1) — 화면 밖 // B06 카드 그림(393-2) — 화면 밖 · 판 값 고르기는 진짜 STUBS["B05_Profile_UI_RouteEdit_Cross_Card"] = { routeCrossSource: () => null, routeCrossCard: () => null, }; const pane = load("B05_Profile", "B05_Profile_UI_RouteEdit_Cross.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: (slots().keepSavedDetail(here(), 7, job.detail), job.detail), routeId: 7, }), adoptPipeline: () => undefined, redraw: () => undefined, }); const options = { stationIntervalM: job.interval, holdDraft: (routeId, saved) => { slots().keepHeldDetail(here(), routeId, saved); // 초안 전 상세 칸(472-5 · 가게 hold 와 같음) 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, }; // ⑦ B05 오른쪽 횡단 판 = 묶음 그 측점(카드와 같은 계획고 · 면적) const card = pageMod.pipelineDetail(P).cross_sections; const panes = card.map((section) => { const shown = pane.pipelineCrossAt(pipe, section.chainage_m + 0.4, job.interval, undefined); return [ r3(shown?.chainage_m) === r3(section.chainage_m), r3(shown?.design?.design_elevation_m) === r3(section.design?.design_elevation_m), r3(shown?.design?.cut_area_m2) === r3(section.design?.cut_area_m2), shown?.samples.length === section.samples.length, ]; }); const paneCheck = { count: card.length, same: panes.filter((row) => row.every(Boolean)).length, elevation: r3( pane.pipelineCrossAt(pipe, target.chainageM, job.interval, undefined)?.design ?.design_elevation_m, ), }; // ⑥ 고리 — 같은 입력 = 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); // ⑨ 저장 노선 ▲▼ 한 번 = 횡단 한 벌(365-4) — 묶음 cross 가 다시 셈 창구를 부르고 그 상세 설계를 냄 const Q = "proj-365b"; window.localStorage.setItem("frd_current_project_id", Q); let refreshCalls = 0; let qBridge = pageMod.routeDraftBridge(Q, link(), { stationIntervalM: job.interval, savedCross: async (detail, _routeId, stations) => { if (!detailMod.detailCross(detail, stations)) return null; refreshCalls += 1; // 창구가 고친 설계 흉내 — 계획고 = 지금 종단(엔진이 「같은 자리」로 볼 값) · 면적 표시 999 const profile = pageMod.pagePipeline(Q).output("profile"); detail.cross_sections.forEach((section) => { section.design = { ...section.design, design_elevation_m: alignment.planElevationAt(profile, section.chainage_m), cut_area_m2: 999, fill_area_m2: 999, }; }); return detailMod.detailCross(detail, stations); }, }); pageMod.pipelineEarthwork(Q, { conversion: job.conversion }); let qPipe = pageMod.pagePipeline(Q); await settle(runs().length + 1); await tick(20); const openCalls = refreshCalls; const key = alignment.chainageKey(savedBase.stations[3].chainage_m); mark = runs().length; pageMod.pipelineGrade(Q, { station_offsets: { [key]: 0.3 }, curve_radii: {} }); const gradeRun = await settle(mark + 1); const firstKey = qPipe.output("ground").stations[0].key; const saved = { owns: pageMod.pipelineOwnsCross(Q), openCalls, gradeCalls: refreshCalls - openCalls, runs: runs().length - mark, sources: gradeRun.sources, fromDetail: qPipe.output("cross").byKey[firstKey]?.detail === job.detail.cross_sections[0].design, }; // ⑩ 다시 셈 창구로 연 뒤 끈 초안 = 새로고침(초안 둔 채 다시 열기) 초안 — 엔진이 창구 출력을 안 이어 씀 mark = runs().length; qBridge.edited(draftOf(shift(n - 2, 0, 2))); await settle(mark + 1); await tick(job.haulDelayMs + 30); const dragRows = shownRows(Q); pageMod.disposePagePipeline(Q); qBridge = pageMod.routeDraftBridge(Q, link(), { stationIntervalM: job.interval }); pageMod.pipelineEarthwork(Q, { conversion: job.conversion }); qPipe = pageMod.pagePipeline(Q); await settle(runs().length + 1); await tick(job.haulDelayMs + 30); const reopenRows = shownRows(Q); const sameAfterReload = { rows: dragRows?.length ?? 0, same: JSON.stringify(dragRows) === JSON.stringify(reopenRows), marked: (dragRows ?? []).filter((row) => row[2] === 999).length, }; // ⑧ 노선 한 걸음 + 계획고 맞춤 — 새 종단이 오면 계획고 맞춤 · 첫 차례는 cross 전에 밀림(무거운 셈 한 번) let graded = false; const stopShift = qPipe.subscribe((event) => { if (event.kind !== "stage" || event.stage !== "profile" || graded) return; if (event.generation !== qPipe.generation) return; graded = true; void Promise.resolve().then(() => pageMod.pipelineGrade(Q, { station_offsets: { [key]: 0.1 }, curve_radii: {} }), ); }, "노선 한 걸음 + 계획고 맞춤"); mark = runs().length; qBridge.edited(draftOf(shift(1, 0, 1))); await settle(mark + 2); await tick(job.haulDelayMs + 30); stopShift(); const shiftRuns = runs() .slice(mark) .map((r) => ({ outcome: r.outcome, cross: "cross" in r.stages, sources: r.sources })); pageMod.disposePagePipeline(Q); page.clearDrafts(Q); // ⑪ 초안 소단(365-5) — 소단 = 지금 구조물 구간(bermAt) · 쪽 깊이 = 세션 고침(측점 열쇠) → 묶음 cross const B = "proj-365c"; window.localStorage.setItem("frd_current_project_id", B); const span = { from: 30, to: 70 }; const bBridge = pageMod.routeDraftBridge(B, link(), { stationIntervalM: job.interval, bermAt: () => (c) => c >= span.from && c <= span.to ? { width_m: 1.5, interval_m: 5, slope_deg: 60, depth_m: 1 } : null, }); pageMod.pipelineEarthwork(B, { conversion: job.conversion }); const bPipe = pageMod.pagePipeline(B); await settle(runs().length + 1); bBridge.edited(draftOf(shift(n - 2, 0, 2))); await settle(runs().length + 1); await tick(20); const bermRows = () => bPipe.output("ground").stations.map((st) => { const d = bPipe.output("cross").byKey[st.key]?.detail ?? {}; return [ st.key, r3(st.chainageM), d.berm ? r3(d.berm.width_m) : null, d.berm_depth_left_m ?? null, ]; }); const bermBefore = bermRows(); const inside = bermBefore.find((row) => row[1] > span.from + 1 && row[1] < span.to - 1); page.writeState("bermdepth", { [inside[0]]: { left: 2.5 } }, B, 7); mark = runs().length; pageMod.pipelineCross(B); await settle(mark + 1); await tick(20); const bermAfter = bermRows(); const berm = { inSpan: bermBefore .filter((row) => row[1] >= span.from && row[1] <= span.to) .every((row) => row[2] === 1.5), outSpan: bermBefore .filter((row) => row[1] < span.from || row[1] > span.to) .every((row) => row[2] === null), depthBefore: inside[3], depthAfter: bermAfter.find((row) => row[0] === inside[0])[3], runs: runs().length - mark, }; const draftCtx = { inputs: { route: bPipe.input("route") }, out: { ground: bPipe.output("ground"), route: bPipe.output("route") }, }; pageMod.disposePagePipeline(B); page.clearDrafts(B); // ⑫ 들어온 화면 무관(365-5) — 설계 칸 = 세션 저장 상세 · 초안 자리로 미리 뜬 시설 측점 = 차례 짝 · 제원 지문 · // 옛 측구 결과(ditch_enabled)도 실음 · 초안 첫 계획선 꼭짓점 = 서버 저장 종단 const crossMod = load("A00_Common", "design", "design_pipeline_cross.ts"); const C = "proj-365d"; const sec = (chainage_m, kind, design, extra = {}) => ({ chainage_m, kind, design, ...extra }); page.writeState( "section-detail", { longitudinal: {}, cross_sections: [ sec(0, "bp", { ground_type: "soil" }), sec(20, "regular", { ground_type: "soil", ditch_choice: null, ditch_enabled: false }), sec(28, "irregular", { ground_type: "soil" }), sec(40, "ep", { ground_type: "soil" }), ], }, C, 7, ); const screen = { longitudinal: {}, cross_sections: [ sec(0, "bp", { ground_type: "soil" }), // 다시 셈이 옛 측구 결과를 선택으로 굳힌 화면 상세 — 설계 칸은 세션 저장 상세가 이김 sec(20, "regular", { ground_type: "soil", ditch_choice: false, ditch_enabled: true }), sec(27, "irregular", { ground_type: "soil" }, { culvert: { type: "pipe", diameter_m: 0.8 } }), sec(40, "ep", { ground_type: "soil" }), ], }; const st = (key, chainageM, kind) => ({ key, chainageM, kind }); const savedList = [ st("end:BP", 0, "end"), st("grid:1", 20, "grid"), st("pipe:p28", 28, "pipe"), st("end:EP", 40, "end"), ]; // 초안 자리 관 측점(27 m) = 등록 열쇠(주인 id)로 저장 관 측점과 짝(457 · 차례 짝 없음) const source = crossMod.pipelineCrossSource(C, screen, savedList, 7, () => savedList.map((s) => s.key), ); const bare = crossMod.pipelineCrossSource( C, { ...screen, cross_sections: screen.cross_sections.filter((x) => x.chainage_m !== 27) }, savedList, 7, ); // 보기가 심은 측점으로 흔들린 저장 기준(꼭짓점 +5 m) 대 서버 저장 종단 — 초안 첫 계획선은 저장 종단 쪽 const shaken = { ...savedBase, basePvi: savedBase.basePvi.map((node) => ({ ...node, elevation_m: node.elevation_m + 5 })), }; const planlineOf = (storedPvi) => grade.createPlanlineStage({ savedBase: () => shaken, savedLine: () => job.line, storedPvi })( draftCtx, ); const firstPvi = (base) => r3(base.basePvi[0].elevation_m); const viewFree = { grid20: source.input.byKey["grid:1"], pipeSpec: source.specs.get("pipe:p28") ?? null, pipeCarried: Boolean(source.input.byKey["pipe:p28"]), specsDiffer: source.input.specsKey !== bare.input.specsKey, firstStored: firstPvi(planlineOf(() => savedBase.basePvi)), firstShaken: firstPvi(planlineOf(undefined)), savedFirst: firstPvi(savedBase), }; page.clearDrafts(C); // ⑬ 보기가 늦게 심은 측점(386-3) — 종단도 기준이 바뀌어도(restart) 묶음은 안 돎 · 기준 = 입력이 심는 측점(옵션) const D = "proj-386"; window.localStorage.setItem("frd_current_project_id", D); let viewBase = savedBase; const planted = []; pageMod.routeDraftBridge( D, { ...link(), pipelineSource: () => ({ ...link().pipelineSource(), base: viewBase }) }, { stationIntervalM: job.interval, plantedBase: (source, inputs) => { planted.push(Array.isArray(inputs.pipes) ? inputs.pipes.length : null); return source.base; }, }, ); pageMod.pipelineEarthwork(D, { conversion: job.conversion }); // 기록 상한(RUN_LOG_SIZE) 뒤라 길이 대신 새 기록을 셈 const since = (old) => runs().filter((record) => !old.has(record)); let old = new Set(runs()); for (let i = 0; i < 400; i += 1) { const fresh = since(old); if (fresh.length && fresh.every((record) => record.outcome !== "running")) break; await tick(5); } await tick(20); const openRuns = since(old).length; old = new Set(runs()); viewBase = { ...savedBase, stations: [...savedBase.stations, { station_id: "irregular:late", chainage_m: 33 }], }; pageMod.restartPagePipeline(D); // 종단도 setIrregularStations 꼴 await tick(30); const late = { openRuns, lateRuns: since(old).length, planted: planted[0] ?? null }; old = new Set(runs()); late.same = await pageMod.reconcilePagePipeline(D); late.sameRuns = since(old).length; pageMod.disposePagePipeline(D); page.clearDrafts(D); return { late, kept, b05, b06, dropped, edit, loop, pane: paneCheck, saved, shiftRuns, sameAfterReload, berm, viewFree, }; } 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); });