/* PLAN 349-0f 헬퍼 — 노선 초안 두 번 끌기(길이 바뀜 + 가운데 꺾임점) 뒤 새 노선 횡단 낡음 · 「다시 계산 중」. * 진짜 TS(`design_pipeline_page` · 단계 파일 · `B05_Profile_UI_Profile_Preview`)를 트랜스파일해 Node 로 돌림. * 서버 창구만 가짜(틀 = `helper_346_2_pipeline_cross_page.cjs` 그대로). 입력 argv[2] JSON · argv[3] 격자 이진. * 결과 = 표준출력 JSON. 짝 = `test_349_0f_draft_stale.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, }; STUBS["B06_Section_Cross_Refresh"] = { holdScreenAlignment: () => () => undefined, refreshCrossDesigns: async () => [], }; STUBS["B06_Section_UI_Section_Common"] = { staleChainages: (key) => (key ? key.split("|").map((entry) => Number(entry.split(":")[0])) : []), }; 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 storeMod = load("A00_Common", "design", "design_store.ts"); const previewMod = load("B05_Profile", "B05_Profile_UI_Profile_Preview.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, })), }; } /** 새 노선 상세의 낡은 측점 — 설계 계획고 ≠ 지금 계획선(`staleKey` 와 같은 잣대 1 mm). */ function staleOf(P, pipe) { const shown = pageMod.pipelineDetail(P); const profile = pipe.output("profile"); if (!shown || !profile) return null; return shown.cross_sections .filter( (s) => s.design && Math.abs(s.design.design_elevation_m - alignment.planElevationAt(profile, s.chainage_m)) > 1e-3, ) .map((s) => s.chainage_m); } async function run() { const P = "proj-3490f"; window.localStorage.setItem("frd_current_project_id", P); const savedBase = await savedBaseOf(); const seedRuns = runs().length; const link = { pipelineSource: () => ({ base: savedBase, edits: alignment.emptyEdits(), detail: job.detail, routeId: 7, }), adoptPipeline: () => undefined, redraw: () => undefined, }; const bridge = pageMod.routeDraftBridge(P, link, { stationIntervalM: job.interval }); pageMod.pipelineEarthwork(P, { conversion: job.conversion }); const pipe = pageMod.pagePipeline(P); let applied = 0; const preview = previewMod.createCrossPreview({ projectId: P, detail: () => null, routeId: () => 7, edits: () => alignment.emptyEdits(), alignment: () => null, debounceMs: () => 0, onApplied: () => (applied += 1), }); await settle(seedRuns + 1); // ① 2번째 꺾임점을 서쪽으로 20 m — 노선 길이 바뀜(job.drags[0]) const [a, b] = job.drags; const first = job.nodes.map((node, i) => i === a.index ? [node[0] + a.dx, node[1] + a.dy] : node, ); bridge.edited(draftOf(first)); const pendingDuring = preview.scheduleIfStale("1:2", true); const runOne = await settle(runs().length + 1); await tick(job.haulDelayMs + 20); const one = { outcome: runOne.outcome, length: pipe.output("route").lengthM, stale: staleOf(P, pipe), pendingAfter: preview.scheduleIfStale("1:2", true), }; // ② 가운데 꺾임점을 북동으로 10 m(job.drags[1]) const second = first.map((node, i) => (i === b.index ? [node[0] + b.dx, node[1] + b.dy] : node)); bridge.edited(draftOf(second)); const runTwo = await settle(runs().length + 1); await tick(job.haulDelayMs + 20); const two = { outcome: runTwo.outcome, length: pipe.output("route").lengthM, stale: staleOf(P, pipe), reused: runTwo.stages.cross !== undefined, pendingAfter: preview.scheduleIfStale("1:2", true), pendingSaved: preview.scheduleIfStale("", true), }; // ③ 그 차례 cross 가 끝내 안 와도(단계 실패) 3 s 뒤 풂 · 다시 그림 const store = storeMod.useDesignStore(P, null); const before = applied; store.set("generation", pipe.generation + 100); const stuck = preview.scheduleIfStale("1:2", true); await tick(3100); const released = { stuck, after: preview.scheduleIfStale("1:2", true), redrew: applied - before, }; preview.dispose(); pageMod.disposePagePipeline(P); page.clearDrafts(P); return { pendingDuring, one, two, released, savedLength: savedBase.chainage.at(-1) }; } 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); });