/* PLAN 349-0d sub7 헬퍼 — 노선을 놓으면 follow 가 다시 매긴 관 · 구조물이 가게(design_store)에 바로 씀 · * 묶음 한 번 · 사진첩 한 걸음 안(놓은 뒤 setTimeout 0 전에 씀) · 되돌리기 · 초안 버림 = 초안 전 값 · 열기만 = 안 씀 · * 새 노선에서 먼 구조물 수. 진짜 TS 를 트랜스파일해 Node 로 · 서버 창구만 가짜(`helper_349_pipeline_once` 와 같은 틀). * 입력 argv[2] JSON · argv[3] 격자 이진. 결과 = 표준출력 JSON. 짝 = `test_349_0d_follow_store.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, }; // 흙 배분 서버 — 늦게 답함 · 끊기면 버림 globalThis.fetch = (url, init) => new Promise((resolve, reject) => { const timer = setTimeout( () => resolve({ ok: true, json: async () => ({ haul_plan: { blocks: [], url } }) }), 20, ); init.signal.addEventListener("abort", () => { clearTimeout(timer); 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: job.curves, min_radius_m: job.minRadius, station_snap: job.stationSnap, }), }; STUBS["B05_Profile_Api_Structures"] = { fetchStructures: async () => ({ structures: job.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 pageMod = load("A00_Common", "design", "design_pipeline_page.ts"); const storeMod = load("A00_Common", "design", "design_store.ts"); const alignment = load("B05_Profile", "logic", "B05_Profile_UI_Profile_Alignment.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 quiet() { let seen = -1; for (let i = 0; i < 400; i += 1) { await tick(15); const last = runs()[runs().length - 1]; const count = runs().length; if (count === seen && (!last || last.outcome !== "running")) return; seen = count; } 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: job.stationSnap, }); const shift = (index, dx, dy) => job.nodes.map((node, i) => (i === index ? [node[0] + dx, node[1] + dy] : node)); const chainagesOf = (stations) => (stations ?? []).map((s) => s.chainageM); const P = "proj-3490d"; const ids = (list) => (list ?? []).map((item) => [item.id ?? item.structure_id, item.chainage_m]); async function run() { window.localStorage.setItem("frd_current_project_id", P); const savedAlignment = job.detail.longitudinal.profile_alignment; const savedBase = alignment.toAlignmentBase(savedAlignment); const followed = []; const link = { pipelineSource: () => ({ base: savedBase, edits: savedAlignment.edits, detail: job.detail, routeId: 7, }), adoptPipeline: (base, edits, draft) => pageMod.pipelineGrade(P, draft ? edits : savedAlignment.edits), redraw: () => undefined, side: null, }; const store = storeMod.useDesignStore(P, null); const bridge = pageMod.routeDraftBridge(P, link, { stationIntervalM: job.interval, onFacilitiesFollowed: (far) => followed.push(far), }); pageMod.pipelineEarthwork(P, { conversion: job.conversion }); await quiet(); const pipe = pageMod.pagePipeline(P); const open = { storePipes: store.get("pipes"), storeStructures: store.get("structures"), followed: [...followed], }; // 사진첩 흉내 — 놓기 전 세션 사진 const snapshot = {}; for (let i = 0; i < window.sessionStorage.length; i += 1) { const key = window.sessionStorage.key(i); snapshot[key] = window.sessionStorage.getItem(key); } // 꼭짓점 한 번 끌어 놓기 — 사진첩은 놓은 뒤 setTimeout 0 에 한 걸음 찍음 let mark = runs().length; bridge.edited(draftOf(shift(1, 9, -6))); await tick(0); const atRecord = { pipes: ids(store.get("pipes")), structures: ids(store.get("structures")) }; await quiet(); const drag = { runs: runs() .slice(mark) .map((r) => r.sources), atRecord, pipes: ids(store.get("pipes")), structures: ids(store.get("structures")), inputPipes: ids(pipe.input("pipes")), followed: [...followed], blocked: pipe.blockedWrites, }; // 되돌리기 — 사진첩이 세션을 되쓴 뒤 노선 편집기가 초안 없음으로 알림 for (const key of Object.keys(snapshot)) window.sessionStorage.setItem(key, snapshot[key]); for (let i = window.sessionStorage.length - 1; i >= 0; i -= 1) { const key = window.sessionStorage.key(i); if (!(key in snapshot)) window.sessionStorage.removeItem(key); } mark = runs().length; bridge.edited(null); await quiet(); const undo = { runs: runs() .slice(mark) .map((r) => r.sources), storePipes: store.get("pipes"), storeStructures: store.get("structures"), inputPipes: ids(pipe.input("pipes")), followed: [...followed], }; // 다시 끌고 사진첩 없이 초안만 버림(편집기 [버림] 등) — 가게 = 초안 전 값 bridge.edited(draftOf(shift(1, 9, -6))); await quiet(); const second = ids(store.get("pipes")); bridge.edited(null); await quiet(); const drop = { second, storePipes: store.get("pipes"), inputPipes: ids(pipe.input("pipes")), blocked: pipe.blockedWrites, }; pageMod.disposePagePipeline(P); return { open, drag, undo, drop, saved: ids(job.pipes), savedStructures: ids(job.structures) }; } 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); });