|
| 1 | +import fs from "node:fs"; |
| 2 | +import { workerData, parentPort } from "node:worker_threads"; |
| 3 | +import path from "node:path"; |
| 4 | + |
| 5 | +const { input, output } = workerData; |
| 6 | + |
| 7 | +const START_TAG = "/*_START_DEV_*/"; |
| 8 | +const END_TAG = "/*_END_DEV_*/"; |
| 9 | + |
| 10 | +await fs.promises.mkdir(path.dirname(output), { recursive: true }); |
| 11 | + |
| 12 | +const rs = fs.createReadStream(input, { encoding: "utf8", highWaterMark: 20 }); |
| 13 | +const ws = fs.createWriteStream(output, { encoding: "utf8" }); |
| 14 | + |
| 15 | +let buffer = ""; // holds leftover across chunks |
| 16 | +let state = "KEEPING"; // or "DELETING" |
| 17 | + |
| 18 | +rs.on("data", (chunk) => { |
| 19 | + buffer += chunk; |
| 20 | + let idx; |
| 21 | + |
| 22 | + while (true) { |
| 23 | + if (state === "KEEPING") { |
| 24 | + idx = buffer.indexOf(START_TAG); |
| 25 | + if (idx === -1) { |
| 26 | + // No START tag – flush all except trailing possible START_TAG prefix |
| 27 | + const safeEnd = buffer.length - START_TAG.length + 1; |
| 28 | + if (safeEnd > 0) { |
| 29 | + ws.write(buffer.slice(0, safeEnd)); |
| 30 | + buffer = buffer.slice(safeEnd); |
| 31 | + } |
| 32 | + break; |
| 33 | + } else { |
| 34 | + // Found START tag |
| 35 | + ws.write(buffer.slice(0, idx)); |
| 36 | + buffer = buffer.slice(idx + START_TAG.length); |
| 37 | + state = "DELETING"; |
| 38 | + } |
| 39 | + } else { |
| 40 | + idx = buffer.indexOf(END_TAG); |
| 41 | + if (idx === -1) { |
| 42 | + // Not found yet – trim buffer to last possible END_TAG start |
| 43 | + buffer = buffer.slice(-END_TAG.length + 1); |
| 44 | + break; |
| 45 | + } else { |
| 46 | + buffer = buffer.slice(idx + END_TAG.length); |
| 47 | + state = "KEEPING"; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | +}); |
| 52 | + |
| 53 | +rs.on("end", () => { |
| 54 | + if (state === "KEEPING" && buffer.length > 0) { |
| 55 | + ws.write(buffer); |
| 56 | + } |
| 57 | + ws.end(() => parentPort.postMessage(`${input} → ${output}`)); |
| 58 | +}); |
| 59 | + |
| 60 | +rs.on("error", (err) => parentPort.postMessage(`Read error: ${err}`)); |
| 61 | +ws.on("error", (err) => parentPort.postMessage(`Write error: ${err}`)); |
0 commit comments