@intlayer/engine 9.1.3 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/assets/initConfig/templates/cjs.txt +4 -1
  2. package/dist/assets/initConfig/templates/json.txt +4 -1
  3. package/dist/assets/initConfig/templates/mjs.txt +4 -1
  4. package/dist/assets/initConfig/templates/ts.txt +4 -1
  5. package/dist/cjs/docReview/alignBlocks.cjs +57 -8
  6. package/dist/cjs/docReview/alignBlocks.cjs.map +1 -1
  7. package/dist/cjs/docReview/rebuildDocument.cjs +37 -9
  8. package/dist/cjs/docReview/rebuildDocument.cjs.map +1 -1
  9. package/dist/cjs/docReview/segmentDocument.cjs +19 -2
  10. package/dist/cjs/docReview/segmentDocument.cjs.map +1 -1
  11. package/dist/cjs/prepareIntlayer.cjs +7 -3
  12. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  13. package/dist/cjs/utils/runOnce.cjs +129 -50
  14. package/dist/cjs/utils/runOnce.cjs.map +1 -1
  15. package/dist/cjs/writeFileIfChanged.cjs +14 -7
  16. package/dist/cjs/writeFileIfChanged.cjs.map +1 -1
  17. package/dist/esm/docReview/alignBlocks.mjs +57 -8
  18. package/dist/esm/docReview/alignBlocks.mjs.map +1 -1
  19. package/dist/esm/docReview/rebuildDocument.mjs +37 -9
  20. package/dist/esm/docReview/rebuildDocument.mjs.map +1 -1
  21. package/dist/esm/docReview/segmentDocument.mjs +19 -2
  22. package/dist/esm/docReview/segmentDocument.mjs.map +1 -1
  23. package/dist/esm/prepareIntlayer.mjs +7 -3
  24. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  25. package/dist/esm/utils/runOnce.mjs +129 -50
  26. package/dist/esm/utils/runOnce.mjs.map +1 -1
  27. package/dist/esm/writeFileIfChanged.mjs +15 -8
  28. package/dist/esm/writeFileIfChanged.mjs.map +1 -1
  29. package/dist/types/docReview/alignBlocks.d.ts +4 -2
  30. package/dist/types/docReview/alignBlocks.d.ts.map +1 -1
  31. package/dist/types/docReview/rebuildDocument.d.ts.map +1 -1
  32. package/dist/types/docReview/segmentDocument.d.ts.map +1 -1
  33. package/dist/types/docReview/types.d.ts +9 -0
  34. package/dist/types/docReview/types.d.ts.map +1 -1
  35. package/dist/types/utils/index.d.ts +2 -2
  36. package/dist/types/utils/runOnce.d.ts +30 -6
  37. package/dist/types/utils/runOnce.d.ts.map +1 -1
  38. package/package.json +9 -9
@@ -2,92 +2,171 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
3
  let node_fs_promises = require("node:fs/promises");
4
4
  let node_path = require("node:path");
5
+ let node_fs = require("node:fs");
5
6
  let _intlayer_core_package_json = require("@intlayer/core/package.json");
6
7
  _intlayer_core_package_json = require_runtime.__toESM(_intlayer_core_package_json);
7
8
 
8
9
  //#region src/utils/runOnce.ts
9
- const DEFAULT_RUN_ONCE_OPTIONS = { cacheTimeoutMs: 60 * 1e3 };
10
- const writeSentinelFile = async (sentinelFilePath, currentTimestamp) => {
11
- const data = {
12
- version: _intlayer_core_package_json.default.version,
13
- timestamp: currentTimestamp
14
- };
10
+ const DEFAULT_RUN_ONCE_OPTIONS = {
11
+ cacheTimeoutMs: 60 * 1e3,
12
+ lockWaitTimeoutMs: 300 * 1e3
13
+ };
14
+ /** Delay between two reads of a sentinel owned by another process. */
15
+ const LOCK_POLL_INTERVAL_MS = 50;
16
+ const delay = (durationMs) => new Promise((resolve) => setTimeout(resolve, durationMs));
17
+ /**
18
+ * Sentinels owned by this process, released synchronously on exit so a crash or
19
+ * a Ctrl-C never leaves a `running` lock that would stall the next run.
20
+ */
21
+ const ownedSentinelFilePaths = /* @__PURE__ */ new Set();
22
+ process.on("exit", () => {
23
+ for (const sentinelFilePath of ownedSentinelFilePaths) try {
24
+ (0, node_fs.rmSync)(sentinelFilePath, { force: true });
25
+ } catch {}
26
+ });
27
+ /**
28
+ * Reads the sentinel file, returning `undefined` when it does not exist or
29
+ * cannot be parsed.
30
+ *
31
+ * Sentinels written by older versions carry no `status`; they always describe a
32
+ * finished run, so they are reported as `done`.
33
+ */
34
+ const readSentinelState = async (sentinelFilePath) => {
35
+ try {
36
+ const [sentinelStats, raw] = await Promise.all([(0, node_fs_promises.stat)(sentinelFilePath), (0, node_fs_promises.readFile)(sentinelFilePath, "utf8")]);
37
+ const parsed = JSON.parse(raw);
38
+ return {
39
+ version: parsed.version ?? "",
40
+ timestamp: parsed.timestamp ?? 0,
41
+ status: parsed.status ?? "done",
42
+ pid: parsed.pid ?? 0,
43
+ mtimeMs: sentinelStats.mtime.getTime()
44
+ };
45
+ } catch {
46
+ return;
47
+ }
48
+ };
49
+ /**
50
+ * Whether the process that wrote the sentinel is still alive. An unknown PID
51
+ * (legacy sentinel) is assumed alive so the staleness timeout stays the only
52
+ * way to reclaim it.
53
+ */
54
+ const isOwnerProcessAlive = (pid) => {
55
+ if (!pid || pid === process.pid) return true;
15
56
  try {
57
+ process.kill(pid, 0);
58
+ return true;
59
+ } catch (error) {
60
+ return error.code === "EPERM";
61
+ }
62
+ };
63
+ const serializeSentinel = (timestamp, status) => JSON.stringify({
64
+ version: _intlayer_core_package_json.default.version,
65
+ timestamp,
66
+ status,
67
+ pid: process.pid
68
+ });
69
+ /**
70
+ * Attempts to take ownership of the sentinel.
71
+ *
72
+ * `wx` makes the creation atomic, so exactly one process can win even when
73
+ * several start at the same moment.
74
+ *
75
+ * @returns `true` when this process now owns the sentinel, `false` when another
76
+ * process created it first.
77
+ */
78
+ const acquireSentinel = async (sentinelFilePath, timestamp) => {
79
+ const data = serializeSentinel(timestamp, "running");
80
+ for (let attempt = 0; attempt < 2; attempt++) try {
16
81
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(sentinelFilePath), { recursive: true });
17
- await (0, node_fs_promises.writeFile)(sentinelFilePath, JSON.stringify(data), { flag: "wx" });
18
- } catch (err) {
19
- if (err.code === "EEXIST") return;
20
- if (err.code === "ENOENT") try {
21
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(sentinelFilePath), { recursive: true });
22
- await (0, node_fs_promises.writeFile)(sentinelFilePath, JSON.stringify(data), { flag: "wx" });
23
- return;
24
- } catch (retryErr) {
25
- if (retryErr.code === "EEXIST") return;
26
- }
27
- throw err;
82
+ await (0, node_fs_promises.writeFile)(sentinelFilePath, data, { flag: "wx" });
83
+ return true;
84
+ } catch (error) {
85
+ const code = error.code;
86
+ if (code === "EEXIST") return false;
87
+ if (code === "ENOENT" && attempt === 0) continue;
88
+ throw error;
28
89
  }
90
+ return false;
91
+ };
92
+ /**
93
+ * Rewrites the sentinel owned by this process, overwriting any existing file.
94
+ */
95
+ const writeOwnedSentinel = async (sentinelFilePath, timestamp, status) => {
96
+ try {
97
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(sentinelFilePath), { recursive: true });
98
+ await (0, node_fs_promises.writeFile)(sentinelFilePath, serializeSentinel(timestamp, status));
99
+ } catch {}
100
+ };
101
+ const removeSentinel = async (sentinelFilePath) => {
102
+ try {
103
+ await (0, node_fs_promises.unlink)(sentinelFilePath);
104
+ } catch {}
29
105
  };
30
106
  /**
31
107
  * Ensures a callback function runs only once within a specified time window across multiple processes.
32
108
  * Uses a sentinel file to coordinate execution and prevent duplicate work.
33
109
  *
110
+ * Processes that lose the race for the sentinel wait for the owner to finish
111
+ * rather than running a competing copy of the callback — concurrent runs would
112
+ * otherwise write to (and clean) the same output directory at the same time.
113
+ *
34
114
  * @param sentinelFilePath - Path to the sentinel file used for coordination
35
115
  * @param callback - The function to execute (should be async)
36
116
  * @param options - The options for the runOnce function
37
117
  *
38
118
  * @example
39
119
  * ```typescript
40
- * await runPrepareIntlayerOnce(
120
+ * await runOnce(
41
121
  * '/tmp/intlayer-sentinel',
42
- * async () => {
43
- * // Your initialization logic here
122
+ * async ({ renewLock }) => {
123
+ * await cleanOutputDir(configuration); // may delete the sentinel
124
+ * await renewLock();
44
125
  * await prepareIntlayer();
45
126
  * },
46
- * 30 * 1000 // 30 seconds cache
127
+ * { cacheTimeoutMs: 30 * 1000 } // 30 seconds cache
47
128
  * );
48
129
  * ```
49
130
  *
50
131
  * @throws {Error} When there are unexpected filesystem errors
51
132
  */
52
133
  const runOnce = async (sentinelFilePath, callback, options) => {
53
- const { onIsCached, cacheTimeoutMs, forceRun } = {
134
+ const { onIsCached, cacheTimeoutMs, forceRun, lockWaitTimeoutMs } = {
54
135
  ...DEFAULT_RUN_ONCE_OPTIONS,
55
136
  ...options ?? {}
56
137
  };
57
138
  const currentTimestamp = Date.now();
58
- try {
59
- const sentinelAge = currentTimestamp - (await (0, node_fs_promises.stat)(sentinelFilePath)).mtime.getTime();
60
- let shouldRebuild = Boolean(forceRun) || sentinelAge > cacheTimeoutMs;
61
- if (!shouldRebuild) try {
62
- const raw = await (0, node_fs_promises.readFile)(sentinelFilePath, "utf8");
63
- let cachedVersion;
64
- try {
65
- cachedVersion = JSON.parse(raw).version;
66
- } catch {
67
- cachedVersion = void 0;
139
+ const waitDeadline = currentTimestamp + lockWaitTimeoutMs;
140
+ while (true) {
141
+ const sentinelState = await readSentinelState(sentinelFilePath);
142
+ if (sentinelState) {
143
+ const sentinelAge = Date.now() - sentinelState.mtimeMs;
144
+ if (sentinelState.status === "running") {
145
+ if (!(sentinelAge > lockWaitTimeoutMs || !isOwnerProcessAlive(sentinelState.pid)) && Date.now() < waitDeadline) {
146
+ await delay(LOCK_POLL_INTERVAL_MS);
147
+ continue;
148
+ }
149
+ await removeSentinel(sentinelFilePath);
150
+ continue;
68
151
  }
69
- if (!cachedVersion || cachedVersion !== _intlayer_core_package_json.default.version) shouldRebuild = true;
70
- } catch {
71
- shouldRebuild = true;
72
- }
73
- if (shouldRebuild) try {
74
- await (0, node_fs_promises.unlink)(sentinelFilePath);
75
- } catch {}
76
- else {
77
- await onIsCached?.();
78
- return;
152
+ if (!forceRun && sentinelAge <= cacheTimeoutMs && sentinelState.version === _intlayer_core_package_json.default.version) {
153
+ await onIsCached?.();
154
+ return;
155
+ }
156
+ await removeSentinel(sentinelFilePath);
79
157
  }
80
- } catch (err) {
81
- if (err.code === "ENOENT") {} else throw err;
158
+ if (await acquireSentinel(sentinelFilePath, currentTimestamp)) break;
159
+ await delay(LOCK_POLL_INTERVAL_MS);
82
160
  }
83
- await writeSentinelFile(sentinelFilePath, currentTimestamp);
161
+ ownedSentinelFilePaths.add(sentinelFilePath);
162
+ const renewLock = () => writeOwnedSentinel(sentinelFilePath, currentTimestamp, "running");
84
163
  try {
85
- await callback();
86
- await writeSentinelFile(sentinelFilePath, currentTimestamp);
164
+ await callback({ renewLock });
165
+ await writeOwnedSentinel(sentinelFilePath, currentTimestamp, "done");
87
166
  } catch {
88
- try {
89
- await (0, node_fs_promises.unlink)(sentinelFilePath);
90
- } catch {}
167
+ await removeSentinel(sentinelFilePath);
168
+ } finally {
169
+ ownedSentinelFilePaths.delete(sentinelFilePath);
91
170
  }
92
171
  };
93
172
 
@@ -1 +1 @@
1
- {"version":3,"file":"runOnce.cjs","names":["packageJson"],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n} satisfies RunOnceOptions;\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n};\n\nconst writeSentinelFile = async (\n sentinelFilePath: string,\n currentTimestamp: number\n) => {\n // O_EXCL ensures only the *first* process can create the file\n const data: SentinelData = {\n version: packageJson.version,\n timestamp: currentTimestamp,\n };\n\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n await writeFile(sentinelFilePath, JSON.stringify(data), { flag: 'wx' });\n } catch (err: any) {\n if (err.code === 'EEXIST') {\n // Another process already created it → we're done\n return;\n }\n // Optimization: If ENOENT occurs on write despite mkdir (race condition with external deletion), retry once.\n if (err.code === 'ENOENT') {\n try {\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n await writeFile(sentinelFilePath, JSON.stringify(data), { flag: 'wx' });\n return;\n } catch (retryErr: any) {\n if (retryErr.code === 'EEXIST') return;\n }\n }\n throw err; // unexpected FS error\n }\n};\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runPrepareIntlayerOnce(\n * '/tmp/intlayer-sentinel',\n * async () => {\n * // Your initialization logic here\n * await prepareIntlayer();\n * },\n * 30 * 1000 // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: () => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n\n try {\n // Check if sentinel file exists and get its stats\n const sentinelStats = await stat(sentinelFilePath);\n const sentinelAge = currentTimestamp - sentinelStats.mtime.getTime();\n\n // Determine if we should rebuild based on cache age, force flag, or version mismatch\n let shouldRebuild = Boolean(forceRun) || sentinelAge > cacheTimeoutMs!;\n\n if (!shouldRebuild) {\n try {\n const raw = await readFile(sentinelFilePath, 'utf8');\n let cachedVersion: string | undefined;\n try {\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n cachedVersion = parsed.version;\n } catch {\n // Legacy format (timestamp only). Force a rebuild once to write versioned sentinel.\n cachedVersion = undefined;\n }\n\n if (!cachedVersion || cachedVersion !== packageJson.version) {\n shouldRebuild = true;\n }\n } catch {\n // If we cannot read the file, err on the safe side and rebuild\n shouldRebuild = true;\n }\n }\n\n if (shouldRebuild) {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n // Fall through to create new sentinel and rebuild\n } else {\n await onIsCached?.();\n // Sentinel is recent and versions match, no need to rebuild\n return;\n }\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n // File doesn't exist, continue to create it\n } else {\n throw err; // unexpected FS error\n }\n }\n\n // Write sentinel file before to block parallel processes\n // Added await here\n await writeSentinelFile(sentinelFilePath, currentTimestamp);\n\n try {\n await callback();\n\n // Write sentinel file after to ensure the first one has not been removed with cleanOutputDir\n // Added await here\n await writeSentinelFile(sentinelFilePath, currentTimestamp);\n } catch {\n try {\n await unlink(sentinelFilePath); // Remove sentinel file if an error occurs\n } catch {}\n }\n};\n"],"mappings":";;;;;;;;AAuBA,MAAM,2BAA2B,EAC/B,gBAAgB,KAAK,IACvB;AAOA,MAAM,oBAAoB,OACxB,kBACA,qBACG;CAEH,MAAM,OAAqB;EACzB,SAASA,oCAAY;EACrB,WAAW;CACb;CAEA,IAAI;EAEF,yDAAoB,gBAAgB,GAAG,EAAE,WAAW,KAAK,CAAC;EAE1D,sCAAgB,kBAAkB,KAAK,UAAU,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC;CACxE,SAAS,KAAU;EACjB,IAAI,IAAI,SAAS,UAEf;EAGF,IAAI,IAAI,SAAS,UACf,IAAI;GACF,yDAAoB,gBAAgB,GAAG,EAAE,WAAW,KAAK,CAAC;GAC1D,sCAAgB,kBAAkB,KAAK,UAAU,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC;GACtE;EACF,SAAS,UAAe;GACtB,IAAI,SAAS,SAAS,UAAU;EAClC;EAEF,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,UAAU,OACrB,kBACA,UACA,YACG;CACH,MAAM,EAAE,YAAY,gBAAgB,aAAa;EAC/C,GAAG;EACH,GAAI,WAAW,CAAC;CAClB;CACA,MAAM,mBAAmB,KAAK,IAAI;CAElC,IAAI;EAGF,MAAM,cAAc,oBAAmB,iCADN,gBAAgB,EACG,CAAC,MAAM,QAAQ;EAGnE,IAAI,gBAAgB,QAAQ,QAAQ,KAAK,cAAc;EAEvD,IAAI,CAAC,eACH,IAAI;GACF,MAAM,MAAM,qCAAe,kBAAkB,MAAM;GACnD,IAAI;GACJ,IAAI;IAEF,gBADe,KAAK,MAAM,GACL,CAAC,CAAC;GACzB,QAAQ;IAEN,gBAAgB;GAClB;GAEA,IAAI,CAAC,iBAAiB,kBAAkBA,oCAAY,SAClD,gBAAgB;EAEpB,QAAQ;GAEN,gBAAgB;EAClB;EAGF,IAAI,eACF,IAAI;GACF,mCAAa,gBAAgB;EAC/B,QAAQ,CAAC;OAEJ;GACL,MAAM,aAAa;GAEnB;EACF;CACF,SAAS,KAAU;EACjB,IAAI,IAAI,SAAS,UAAU,CAE3B,OACE,MAAM;CAEV;CAIA,MAAM,kBAAkB,kBAAkB,gBAAgB;CAE1D,IAAI;EACF,MAAM,SAAS;EAIf,MAAM,kBAAkB,kBAAkB,gBAAgB;CAC5D,QAAQ;EACN,IAAI;GACF,mCAAa,gBAAgB;EAC/B,QAAQ,CAAC;CACX;AACF"}
1
+ {"version":3,"file":"runOnce.cjs","names":["packageJson"],"sources":["../../../src/utils/runOnce.ts"],"sourcesContent":["import { rmSync } from 'node:fs';\nimport { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport packageJson from '@intlayer/core/package.json' with { type: 'json' };\n\n/**\n * Lifecycle of the run described by a sentinel file.\n *\n * - `running` — a process owns the sentinel and its callback is still in flight.\n * Other processes must wait instead of starting a concurrent run.\n * - `done` — the callback completed; the sentinel is now a plain cache marker.\n */\ntype SentinelStatus = 'running' | 'done';\n\ntype SentinelData = {\n version: string;\n timestamp: number;\n status: SentinelStatus;\n /** PID of the process that owns the sentinel, used to detect abandoned locks. */\n pid: number;\n};\n\n/** Sentinel state as read from disk, enriched with the file's modification time. */\ntype SentinelState = SentinelData & { mtimeMs: number };\n\n/**\n * Context handed to the callback so it can interact with the lock it runs under.\n */\nexport type RunOnceContext = {\n /**\n * Re-create the sentinel file after an operation that may have deleted it —\n * typically cleaning the output directory, which wipes the cache directory the\n * sentinel lives in. Without this, concurrent processes would see no lock and\n * start a competing run while this one is still writing.\n */\n renewLock: () => Promise<void>;\n};\n\ntype RunOnceOptions = {\n /**\n * The function to execute when the sentinel is not found or is older than the cache timeout.\n */\n onIsCached?: () => void | Promise<void>;\n /**\n * The time window in milliseconds during which the sentinel is considered valid.\n *\n * @default 60000 = 1 minute\n */\n cacheTimeoutMs?: number;\n /**\n * If true, the callback will always run. If undefined, the callback will run only if the sentinel is older than the cache timeout.\n *\n * @default false\n */\n forceRun?: boolean;\n /**\n * How long to wait for another process to release the sentinel before\n * considering its run abandoned and taking the lock over.\n *\n * @default 300000 = 5 minutes\n */\n lockWaitTimeoutMs?: number;\n};\n\nconst DEFAULT_RUN_ONCE_OPTIONS = {\n cacheTimeoutMs: 60 * 1000, // 1 minute in milliseconds,\n lockWaitTimeoutMs: 5 * 60 * 1000, // 5 minutes in milliseconds\n} satisfies RunOnceOptions;\n\n/** Delay between two reads of a sentinel owned by another process. */\nconst LOCK_POLL_INTERVAL_MS = 50;\n\nconst delay = (durationMs: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, durationMs));\n\n/**\n * Sentinels owned by this process, released synchronously on exit so a crash or\n * a Ctrl-C never leaves a `running` lock that would stall the next run.\n */\nconst ownedSentinelFilePaths = new Set<string>();\n\nprocess.on('exit', () => {\n for (const sentinelFilePath of ownedSentinelFilePaths) {\n try {\n rmSync(sentinelFilePath, { force: true });\n } catch {}\n }\n});\n\n/**\n * Reads the sentinel file, returning `undefined` when it does not exist or\n * cannot be parsed.\n *\n * Sentinels written by older versions carry no `status`; they always describe a\n * finished run, so they are reported as `done`.\n */\nconst readSentinelState = async (\n sentinelFilePath: string\n): Promise<SentinelState | undefined> => {\n try {\n const [sentinelStats, raw] = await Promise.all([\n stat(sentinelFilePath),\n readFile(sentinelFilePath, 'utf8'),\n ]);\n\n const parsed = JSON.parse(raw) as Partial<SentinelData>;\n\n return {\n version: parsed.version ?? '',\n timestamp: parsed.timestamp ?? 0,\n status: parsed.status ?? 'done',\n pid: parsed.pid ?? 0,\n mtimeMs: sentinelStats.mtime.getTime(),\n };\n } catch {\n return undefined;\n }\n};\n\n/**\n * Whether the process that wrote the sentinel is still alive. An unknown PID\n * (legacy sentinel) is assumed alive so the staleness timeout stays the only\n * way to reclaim it.\n */\nconst isOwnerProcessAlive = (pid: number): boolean => {\n if (!pid || pid === process.pid) return true;\n\n try {\n // Signal 0 performs an existence check without delivering a signal.\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM means the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n};\n\nconst serializeSentinel = (timestamp: number, status: SentinelStatus): string =>\n JSON.stringify({\n version: packageJson.version,\n timestamp,\n status,\n pid: process.pid,\n } satisfies SentinelData);\n\n/**\n * Attempts to take ownership of the sentinel.\n *\n * `wx` makes the creation atomic, so exactly one process can win even when\n * several start at the same moment.\n *\n * @returns `true` when this process now owns the sentinel, `false` when another\n * process created it first.\n */\nconst acquireSentinel = async (\n sentinelFilePath: string,\n timestamp: number\n): Promise<boolean> => {\n const data = serializeSentinel(timestamp, 'running');\n\n for (let attempt = 0; attempt < 2; attempt++) {\n try {\n // Ensure the directory exists before writing the file\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n\n await writeFile(sentinelFilePath, data, { flag: 'wx' });\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n\n if (code === 'EEXIST') return false;\n // The directory was removed between the mkdir and the write (e.g. a\n // concurrent output-directory clean); retry once.\n if (code === 'ENOENT' && attempt === 0) continue;\n\n throw error;\n }\n }\n\n return false;\n};\n\n/**\n * Rewrites the sentinel owned by this process, overwriting any existing file.\n */\nconst writeOwnedSentinel = async (\n sentinelFilePath: string,\n timestamp: number,\n status: SentinelStatus\n): Promise<void> => {\n try {\n await mkdir(dirname(sentinelFilePath), { recursive: true });\n await writeFile(sentinelFilePath, serializeSentinel(timestamp, status));\n } catch {}\n};\n\nconst removeSentinel = async (sentinelFilePath: string): Promise<void> => {\n try {\n await unlink(sentinelFilePath);\n } catch {}\n};\n\n/**\n * Ensures a callback function runs only once within a specified time window across multiple processes.\n * Uses a sentinel file to coordinate execution and prevent duplicate work.\n *\n * Processes that lose the race for the sentinel wait for the owner to finish\n * rather than running a competing copy of the callback — concurrent runs would\n * otherwise write to (and clean) the same output directory at the same time.\n *\n * @param sentinelFilePath - Path to the sentinel file used for coordination\n * @param callback - The function to execute (should be async)\n * @param options - The options for the runOnce function\n *\n * @example\n * ```typescript\n * await runOnce(\n * '/tmp/intlayer-sentinel',\n * async ({ renewLock }) => {\n * await cleanOutputDir(configuration); // may delete the sentinel\n * await renewLock();\n * await prepareIntlayer();\n * },\n * { cacheTimeoutMs: 30 * 1000 } // 30 seconds cache\n * );\n * ```\n *\n * @throws {Error} When there are unexpected filesystem errors\n */\nexport const runOnce = async (\n sentinelFilePath: string,\n callback: (context: RunOnceContext) => void | Promise<void>,\n options?: RunOnceOptions\n) => {\n const { onIsCached, cacheTimeoutMs, forceRun, lockWaitTimeoutMs } = {\n ...DEFAULT_RUN_ONCE_OPTIONS,\n ...(options ?? {}),\n };\n const currentTimestamp = Date.now();\n const waitDeadline = currentTimestamp + lockWaitTimeoutMs;\n\n // Acquisition loop: read the sentinel, then either return early (fresh cache),\n // wait for the current owner, or take the lock. Every branch either returns or\n // makes progress, so the loop always terminates.\n while (true) {\n const sentinelState = await readSentinelState(sentinelFilePath);\n\n if (sentinelState) {\n const sentinelAge = Date.now() - sentinelState.mtimeMs;\n\n if (sentinelState.status === 'running') {\n const isAbandoned =\n sentinelAge > lockWaitTimeoutMs ||\n !isOwnerProcessAlive(sentinelState.pid);\n\n if (!isAbandoned && Date.now() < waitDeadline) {\n await delay(LOCK_POLL_INTERVAL_MS);\n continue;\n }\n\n // The owner died or overran the timeout: reclaim the sentinel.\n await removeSentinel(sentinelFilePath);\n continue;\n }\n\n const isCacheValid =\n !forceRun &&\n sentinelAge <= cacheTimeoutMs &&\n sentinelState.version === packageJson.version;\n\n if (isCacheValid) {\n await onIsCached?.();\n return;\n }\n\n await removeSentinel(sentinelFilePath);\n }\n\n const hasAcquiredSentinel = await acquireSentinel(\n sentinelFilePath,\n currentTimestamp\n );\n\n if (hasAcquiredSentinel) break;\n\n // Another process won the race in the meantime: loop back and wait for it.\n // The delay also guarantees the loop yields, so a sentinel being repeatedly\n // created and removed can never turn into a busy wait.\n await delay(LOCK_POLL_INTERVAL_MS);\n }\n\n ownedSentinelFilePaths.add(sentinelFilePath);\n\n const renewLock = () =>\n writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'running');\n\n try {\n await callback({ renewLock });\n\n // Mark the run as finished, re-creating the sentinel if the callback\n // deleted it (e.g. by cleaning the output directory).\n await writeOwnedSentinel(sentinelFilePath, currentTimestamp, 'done');\n } catch {\n await removeSentinel(sentinelFilePath); // Remove sentinel file if an error occurs\n } finally {\n ownedSentinelFilePaths.delete(sentinelFilePath);\n }\n};\n"],"mappings":";;;;;;;;;AAgEA,MAAM,2BAA2B;CAC/B,gBAAgB,KAAK;CACrB,mBAAmB,MAAS;AAC9B;;AAGA,MAAM,wBAAwB;AAE9B,MAAM,SAAS,eACb,IAAI,SAAS,YAAY,WAAW,SAAS,UAAU,CAAC;;;;;AAM1D,MAAM,yCAAyB,IAAI,IAAY;AAE/C,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,oBAAoB,wBAC7B,IAAI;E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, { encoding = "utf8", tempDir, atom
50
50
  const tempPath = tempDir ? (0, node_path.join)(tempDir, tempFileName) : `${path}.${tempFileName}`;
51
51
  activeTempFiles.add(tempPath);
52
52
  try {
53
- await (0, node_fs_promises.writeFile)(tempPath, newData);
54
- if (modeToRestore !== void 0) {
55
- if (defaultFileMode === void 0) try {
56
- defaultFileMode = (await (0, node_fs_promises.stat)(tempPath)).mode & 511;
57
- } catch {}
58
- if (modeToRestore !== defaultFileMode) await (0, node_fs_promises.chmod)(tempPath, modeToRestore);
53
+ for (let attempt = 0;; attempt++) try {
54
+ await (0, node_fs_promises.writeFile)(tempPath, newData);
55
+ if (modeToRestore !== void 0) {
56
+ if (defaultFileMode === void 0) try {
57
+ defaultFileMode = (await (0, node_fs_promises.stat)(tempPath)).mode & 511;
58
+ } catch {}
59
+ if (modeToRestore !== defaultFileMode) await (0, node_fs_promises.chmod)(tempPath, modeToRestore);
60
+ }
61
+ await (0, node_fs_promises.rename)(tempPath, path);
62
+ break;
63
+ } catch (error) {
64
+ if (!(error.code === "ENOENT") || attempt > 0) throw error;
65
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
66
+ if (tempDir) await (0, node_fs_promises.mkdir)(tempDir, { recursive: true });
59
67
  }
60
- await (0, node_fs_promises.rename)(tempPath, path);
61
68
  } catch (error) {
62
69
  try {
63
70
  await (0, node_fs_promises.rm)(tempPath, { force: true });
@@ -1 +1 @@
1
- {"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { rmSync } from 'node:fs';\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n/**\n * Permission bits a freshly created file receives on this system. Detected once\n * from the first temp file we actually write (`process.umask()` with no\n * argument is deprecated and thread-unsafe) and cached, so the atomic path can\n * skip restoring the mode whenever the source file already uses the default\n * mode — which is the case for essentially every generated file.\n */\nlet defaultFileMode: number | undefined;\n\n/**\n * Options for {@link writeFileIfChanged}.\n */\nexport type WriteFileIfChangedOptions = {\n /** Encoding used to turn `data` into bytes. Defaults to `'utf8'`. */\n encoding?: BufferEncoding;\n /** Directory to hold the temporary file used for the atomic swap. */\n tempDir?: string;\n /**\n * Write atomically via a temp file + `rename` so readers never observe a\n * half-written file. This creates a fresh inode on every write, which roughly\n * doubles the cost of a changed write compared to overwriting in place. Set to\n * `false` for callers whose consumers tolerate torn reads to write directly.\n * Defaults to `true`.\n */\n atomic?: boolean;\n};\n\n/**\n * Write `data` to `path` only when it differs from the file already on disk,\n * preserving the existing file's permission mode.\n *\n * The whole file is read back and byte-compared because the files written here\n * (dictionaries, entry points, types) are small, so reading beats streaming a\n * hash. When the content is unchanged the write is skipped entirely, which both\n * avoids inode churn and prevents downstream watchers from rebuilding.\n *\n * @returns `true` when the file was written, `false` when it was already up to date.\n */\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n { encoding = 'utf8', tempDir, atomic = true }: WriteFileIfChangedOptions = {}\n): Promise<boolean> => {\n const newData = Buffer.from(data, encoding);\n\n // Read the current content first: the common case is an unchanged file, and\n // this single read is the whole fast path (no stat/chmod needed to bail out).\n let existingData: Buffer | null = null;\n try {\n existingData = await readFile(path);\n } catch {}\n\n if (existingData?.equals(newData)) {\n return false;\n }\n\n // Fast path: overwrite in place. Truncating an existing file keeps its inode,\n // so its permission mode is preserved automatically (no chmod needed). This\n // skips the temp-file inode churn at the cost of exposing readers to a\n // partially written file.\n if (!atomic) {\n await writeFile(path, newData);\n return true;\n }\n\n // The atomic swap replaces the inode, so the existing mode is not preserved\n // and must be reapplied. Only a file that already exists has a mode to keep.\n let modeToRestore: number | undefined;\n if (existingData !== null) {\n try {\n modeToRestore = (await stat(path)).mode & 0o777;\n } catch {}\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n await writeFile(tempPath, newData);\n\n if (modeToRestore !== undefined) {\n // Learn the ambient default mode once from a real temp file, then only\n // chmod when the source file used a non-default mode.\n if (defaultFileMode === undefined) {\n try {\n defaultFileMode = (await stat(tempPath)).mode & 0o777;\n } catch {}\n }\n if (modeToRestore !== defaultFileMode) {\n await chmod(tempPath, modeToRestore);\n }\n }\n\n await rename(tempPath, path);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAY;AAGxC,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,QAAQ,iBACjB,IAAI;EACF,oBAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CAC9B,QAAQ,CAAC;AAEb,CAAC;;;;;;;;AASD,IAAI;;;;;;;;;;;;AA+BJ,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,WAAW,QAAQ,SAAS,SAAS,SAAoC,CAAC,MACvD;CACrB,MAAM,UAAU,OAAO,KAAK,MAAM,QAAQ;CAI1C,IAAI,eAA8B;CAClC,IAAI;EACF,eAAe,qCAAe,IAAI;CACpC,QAAQ,CAAC;CAET,IAAI,cAAc,OAAO,OAAO,GAC9B,OAAO;CAOT,IAAI,CAAC,QAAQ;EACX,sCAAgB,MAAM,OAAO;EAC7B,OAAO;CACT;CAIA,IAAI;CACJ,IAAI,iBAAiB,MACnB,IAAI;EACF,iBAAiB,iCAAW,IAAI,EAAC,CAAE,OAAO;CAC5C,QAAQ,CAAC;CAGX,IAAI,SACF,kCAAY,SAAS,EAAE,WAAW,KAAK,CAAC;CAG1C,MAAM,eAAe,2BAAY,IAAI,EAAE,GAAG,KAAK,IAAI,EAAE,gCAAe,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CACvF,MAAM,WAAW,8BACR,SAAS,YAAY,IAC1B,GAAG,KAAK,GAAG;CACf,gBAAgB,IAAI,QAAQ;CAE5B,IAAI;EACF,sCAAgB,UAAU,OAAO;EAEjC,IAAI,kBAAkB,QAAW;GAG/B,IAAI,oBAAoB,QACtB,IAAI;IACF,mBAAmB,iCAAW,QAAQ,EAAC,CAAE,OAAO;GAClD,QAAQ,CAAC;GAEX,IAAI,kBAAkB,iBACpB,kCAAY,UAAU,aAAa;EAEvC;EAEA,mCAAa,UAAU,IAAI;CAC7B,SAAS,OAAO;EACd,IAAI;GACF,+BAAS,UAAU,EAAE,OAAO,KAAK,CAAC;EACpC,QAAQ,CAAC;EACT,MAAM;CACR,UAAU;EACR,gBAAgB,OAAO,QAAQ;CACjC;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"writeFileIfChanged.cjs","names":[],"sources":["../../src/writeFileIfChanged.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { rmSync } from 'node:fs';\nimport {\n chmod,\n mkdir,\n readFile,\n rename,\n rm,\n stat,\n writeFile,\n} from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\n\nconst activeTempFiles = new Set<string>();\n\n// Synchronous cleanup on process exit\nprocess.on('exit', () => {\n for (const file of activeTempFiles) {\n try {\n rmSync(file, { force: true });\n } catch {}\n }\n});\n\n/**\n * Permission bits a freshly created file receives on this system. Detected once\n * from the first temp file we actually write (`process.umask()` with no\n * argument is deprecated and thread-unsafe) and cached, so the atomic path can\n * skip restoring the mode whenever the source file already uses the default\n * mode — which is the case for essentially every generated file.\n */\nlet defaultFileMode: number | undefined;\n\n/**\n * Options for {@link writeFileIfChanged}.\n */\nexport type WriteFileIfChangedOptions = {\n /** Encoding used to turn `data` into bytes. Defaults to `'utf8'`. */\n encoding?: BufferEncoding;\n /** Directory to hold the temporary file used for the atomic swap. */\n tempDir?: string;\n /**\n * Write atomically via a temp file + `rename` so readers never observe a\n * half-written file. This creates a fresh inode on every write, which roughly\n * doubles the cost of a changed write compared to overwriting in place. Set to\n * `false` for callers whose consumers tolerate torn reads to write directly.\n * Defaults to `true`.\n */\n atomic?: boolean;\n};\n\n/**\n * Write `data` to `path` only when it differs from the file already on disk,\n * preserving the existing file's permission mode.\n *\n * The whole file is read back and byte-compared because the files written here\n * (dictionaries, entry points, types) are small, so reading beats streaming a\n * hash. When the content is unchanged the write is skipped entirely, which both\n * avoids inode churn and prevents downstream watchers from rebuilding.\n *\n * @returns `true` when the file was written, `false` when it was already up to date.\n */\nexport const writeFileIfChanged = async (\n path: string,\n data: string,\n { encoding = 'utf8', tempDir, atomic = true }: WriteFileIfChangedOptions = {}\n): Promise<boolean> => {\n const newData = Buffer.from(data, encoding);\n\n // Read the current content first: the common case is an unchanged file, and\n // this single read is the whole fast path (no stat/chmod needed to bail out).\n let existingData: Buffer | null = null;\n try {\n existingData = await readFile(path);\n } catch {}\n\n if (existingData?.equals(newData)) {\n return false;\n }\n\n // Fast path: overwrite in place. Truncating an existing file keeps its inode,\n // so its permission mode is preserved automatically (no chmod needed). This\n // skips the temp-file inode churn at the cost of exposing readers to a\n // partially written file.\n if (!atomic) {\n await writeFile(path, newData);\n return true;\n }\n\n // The atomic swap replaces the inode, so the existing mode is not preserved\n // and must be reapplied. Only a file that already exists has a mode to keep.\n let modeToRestore: number | undefined;\n if (existingData !== null) {\n try {\n modeToRestore = (await stat(path)).mode & 0o777;\n } catch {}\n }\n\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(path)}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${path}.${tempFileName}`;\n activeTempFiles.add(tempPath);\n\n try {\n for (let attempt = 0; ; attempt++) {\n try {\n await writeFile(tempPath, newData);\n\n if (modeToRestore !== undefined) {\n // Learn the ambient default mode once from a real temp file, then only\n // chmod when the source file used a non-default mode.\n if (defaultFileMode === undefined) {\n try {\n defaultFileMode = (await stat(tempPath)).mode & 0o777;\n } catch {}\n }\n if (modeToRestore !== defaultFileMode) {\n await chmod(tempPath, modeToRestore);\n }\n }\n\n await rename(tempPath, path);\n break;\n } catch (error) {\n const isMissingDirectory =\n (error as NodeJS.ErrnoException).code === 'ENOENT';\n\n if (!isMissingDirectory || attempt > 0) throw error;\n\n await mkdir(dirname(path), { recursive: true });\n if (tempDir) await mkdir(tempDir, { recursive: true });\n }\n }\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {}\n throw error;\n } finally {\n activeTempFiles.delete(tempPath);\n }\n\n return true;\n};\n"],"mappings":";;;;;;;AAaA,MAAM,kCAAkB,IAAI,IAAY;AAGxC,QAAQ,GAAG,cAAc;CACvB,KAAK,MAAM,QAAQ,iBACjB,IAAI;EACF,oBAAO,MAAM,EAAE,OAAO,KAAK,CAAC;CAC9B,QAAQ,CAAC;AAEb,CAAC;;;;;;;;AASD,IAAI;;;;;;;;;;;;AA+BJ,MAAa,qBAAqB,OAChC,MACA,MACA,EAAE,WAAW,QAAQ,SAAS,SAAS,SAAoC,CAAC,MACvD;CACrB,MAAM,UAAU,OAAO,KAAK,MAAM,QAAQ;CAI1C,IAAI,eAA8B;CAClC,IAAI;EACF,eAAe,qCAAe,IAAI;CACpC,QAAQ,CAAC;CAET,IAAI,cAAc,OAAO,OAAO,GAC9B,OAAO;CAOT,IAAI,CAAC,QAAQ;EACX,sCAAgB,MAAM,OAAO;EAC7B,OAAO;CACT;CAIA,IAAI;CACJ,IAAI,iBAAiB,MACnB,IAAI;EACF,iBAAiB,iCAAW,IAAI,EAAC,CAAE,OAAO;CAC5C,QAAQ,CAAC;CAGX,IAAI,SACF,kCAAY,SAAS,EAAE,WAAW,KAAK,CAAC;CAG1C,MAAM,eAAe,2BAAY,IAAI,EAAE,GAAG,KAAK,IAAI,EAAE,gCAAe,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE;CACvF,MAAM,WAAW,8BACR,SAAS,YAAY,IAC1B,GAAG,KAAK,GAAG;CACf,gBAAgB,IAAI,QAAQ;CAE5B,IAAI;EACF,KAAK,IAAI,UAAU,IAAK,WACtB,IAAI;GACF,sCAAgB,UAAU,OAAO;GAEjC,IAAI,kBAAkB,QAAW;IAG/B,IAAI,oBAAoB,QACtB,IAAI;KACF,mBAAmB,iCAAW,QAAQ,EAAC,CAAE,OAAO;IAClD,QAAQ,CAAC;IAEX,IAAI,kBAAkB,iBACpB,kCAAY,UAAU,aAAa;GAEvC;GAEA,mCAAa,UAAU,IAAI;GAC3B;EACF,SAAS,OAAO;GAId,IAAI,EAFD,MAAgC,SAAS,aAEjB,UAAU,GAAG,MAAM;GAE9C,yDAAoB,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,IAAI,SAAS,kCAAY,SAAS,EAAE,WAAW,KAAK,CAAC;EACvD;CAEJ,SAAS,OAAO;EACd,IAAI;GACF,+BAAS,UAAU,EAAE,OAAO,KAAK,CAAC;EACpC,QAAQ,CAAC;EACT,MAAM;CACR,UAAU;EACR,gBAAgB,OAAO,QAAQ;CACjC;CAEA,OAAO;AACT"}
@@ -1,12 +1,54 @@
1
1
  import { computeJaccardSimilarity } from "./computeSimilarity.mjs";
2
2
 
3
3
  //#region src/docReview/alignBlocks.ts
4
+ /** Cost of leaving a block unaligned (an insertion or a deletion). */
5
+ const GAP_PENALTY = -2;
6
+ /**
7
+ * Score of a pair that structural evidence rules out.
8
+ *
9
+ * Strictly below the cost of two gaps (`2 * GAP_PENALTY`) so the aligner always
10
+ * prefers reporting an insertion plus a deletion over such a pair. Every other
11
+ * score is positive, which means that without an explicit veto the aligner would
12
+ * rather pair two unrelated blocks than leave them unaligned — and a bogus pair
13
+ * is planned as `reuse`, which keeps the stale translation verbatim *and*
14
+ * inserts the freshly translated base block next to it, producing the duplicated
15
+ * headings this penalty exists to prevent.
16
+ */
17
+ const STRUCTURAL_MISMATCH_PENALTY = GAP_PENALTY * 2 - 1;
18
+ /** Reward for two blocks opened by a heading of the very same depth. */
19
+ const HEADING_DEPTH_MATCH_BONUS = 3;
20
+ /** Minimum length ratio for the (small) "comparable size" reward. */
21
+ const COMPARABLE_LENGTH_RATIO = .75;
22
+ /**
23
+ * Body length from which a section is considered to carry content of its own.
24
+ *
25
+ * Kept above a single sentence so a translator's short lead-in paragraph is not
26
+ * mistaken for a whole section body.
27
+ */
28
+ const SUBSTANTIAL_BODY_LENGTH = 80;
29
+ /**
30
+ * Length of the body a block carries below its opening heading.
31
+ *
32
+ * A section that only holds its heading (because subsections carry all of its
33
+ * content) is structurally different from one that holds a full body, and that
34
+ * difference survives translation.
35
+ *
36
+ * @param block - The block to measure.
37
+ * @returns The trimmed length of everything below the opening heading line.
38
+ */
39
+ const measureBodyLength = (block) => {
40
+ if (block.headingDepth === null) return block.content.trim().length;
41
+ const [, ...bodyLines] = block.content.split("\n");
42
+ return bodyLines.join("\n").trim().length;
43
+ };
4
44
  /**
5
45
  * Align the blocks of a base document with the blocks of its translation using a
6
- * Needleman–Wunsch global alignment over anchor similarity and block type.
46
+ * Needleman–Wunsch global alignment over heading depth, anchor similarity and
47
+ * block type.
7
48
  *
8
49
  * Because prose differs across languages, the score is weighted toward the
9
- * structural anchor (digits and symbols) rather than the words themselves.
50
+ * structural signals — heading depth first, then the anchor (digits and symbols)
51
+ * — rather than the words themselves.
10
52
  *
11
53
  * @param baseBlocks - Blocks of the base (source) document.
12
54
  * @param targetBlocks - Blocks of the target (translated) document.
@@ -17,26 +59,33 @@ const alignBaseAndTargetBlocks = (baseBlocks, targetBlocks) => {
17
59
  const targetLength = targetBlocks.length;
18
60
  const scoreMatrix = Array.from({ length: baseLength + 1 }, () => Array.from({ length: targetLength + 1 }, () => 0));
19
61
  const traceMatrix = Array.from({ length: baseLength + 1 }, () => Array.from({ length: targetLength + 1 }, () => "diagonal"));
20
- const gapPenalty = -2;
21
62
  const computeMatchScore = (baseIndex, targetIndex) => {
22
63
  const baseBlock = baseBlocks[baseIndex];
23
64
  const targetBlock = targetBlocks[targetIndex];
65
+ const hasComparableHeadingDepths = baseBlock.headingDepth !== null && targetBlock.headingDepth !== null;
66
+ if (hasComparableHeadingDepths && baseBlock.headingDepth !== targetBlock.headingDepth) return STRUCTURAL_MISMATCH_PENALTY;
67
+ const baseBodyLength = measureBodyLength(baseBlock);
68
+ const targetBodyLength = measureBodyLength(targetBlock);
69
+ if (baseBodyLength === 0 && targetBodyLength >= SUBSTANTIAL_BODY_LENGTH || targetBodyLength === 0 && baseBodyLength >= SUBSTANTIAL_BODY_LENGTH) return STRUCTURAL_MISMATCH_PENALTY;
70
+ const lengthRatio = Math.min(baseBlock.content.length, targetBlock.content.length) / Math.max(baseBlock.content.length, targetBlock.content.length);
71
+ const headingDepthBonus = hasComparableHeadingDepths ? HEADING_DEPTH_MATCH_BONUS : 0;
24
72
  const typeBonus = baseBlock.type === targetBlock.type ? 2 : 0;
25
73
  const anchorSimilarity = computeJaccardSimilarity(baseBlock.anchorText, targetBlock.anchorText, 3);
26
- return typeBonus + (Math.min(baseBlock.content.length, targetBlock.content.length) / Math.max(baseBlock.content.length, targetBlock.content.length) > .75 ? 1 : 0) + anchorSimilarity * 8;
74
+ const lengthBonus = lengthRatio > COMPARABLE_LENGTH_RATIO ? 1 : 0;
75
+ return headingDepthBonus + typeBonus + lengthBonus + anchorSimilarity * 8;
27
76
  };
28
77
  for (let i = 1; i <= baseLength; i += 1) {
29
- scoreMatrix[i][0] = scoreMatrix[i - 1][0] + gapPenalty;
78
+ scoreMatrix[i][0] = scoreMatrix[i - 1][0] + GAP_PENALTY;
30
79
  traceMatrix[i][0] = "up";
31
80
  }
32
81
  for (let j = 1; j <= targetLength; j += 1) {
33
- scoreMatrix[0][j] = scoreMatrix[0][j - 1] + gapPenalty;
82
+ scoreMatrix[0][j] = scoreMatrix[0][j - 1] + GAP_PENALTY;
34
83
  traceMatrix[0][j] = "left";
35
84
  }
36
85
  for (let i = 1; i <= baseLength; i += 1) for (let j = 1; j <= targetLength; j += 1) {
37
86
  const match = scoreMatrix[i - 1][j - 1] + computeMatchScore(i - 1, j - 1);
38
- const deleteGap = scoreMatrix[i - 1][j] + gapPenalty;
39
- const insertGap = scoreMatrix[i][j - 1] + gapPenalty;
87
+ const deleteGap = scoreMatrix[i - 1][j] + GAP_PENALTY;
88
+ const insertGap = scoreMatrix[i][j - 1] + GAP_PENALTY;
40
89
  const best = Math.max(match, deleteGap, insertGap);
41
90
  scoreMatrix[i][j] = best;
42
91
  traceMatrix[i][j] = best === match ? "diagonal" : best === deleteGap ? "up" : "left";
@@ -1 +1 @@
1
- {"version":3,"file":"alignBlocks.mjs","names":[],"sources":["../../../src/docReview/alignBlocks.ts"],"sourcesContent":["import { computeJaccardSimilarity } from './computeSimilarity';\nimport type { AlignmentPair, FingerprintedBlock } from './types';\n\n/**\n * Align the blocks of a base document with the blocks of its translation using a\n * Needleman–Wunsch global alignment over anchor similarity and block type.\n *\n * Because prose differs across languages, the score is weighted toward the\n * structural anchor (digits and symbols) rather than the words themselves.\n *\n * @param baseBlocks - Blocks of the base (source) document.\n * @param targetBlocks - Blocks of the target (translated) document.\n * @returns The ordered list of alignment pairs, including insertions and deletions.\n */\nexport const alignBaseAndTargetBlocks = (\n baseBlocks: FingerprintedBlock[],\n targetBlocks: FingerprintedBlock[]\n): AlignmentPair[] => {\n const baseLength = baseBlocks.length;\n const targetLength = targetBlocks.length;\n\n const scoreMatrix: number[][] = Array.from({ length: baseLength + 1 }, () =>\n Array.from({ length: targetLength + 1 }, () => 0)\n );\n const traceMatrix: ('diagonal' | 'up' | 'left')[][] = Array.from(\n { length: baseLength + 1 },\n () => Array.from({ length: targetLength + 1 }, () => 'diagonal')\n );\n\n const gapPenalty = -2;\n\n const computeMatchScore = (\n baseIndex: number,\n targetIndex: number\n ): number => {\n const baseBlock = baseBlocks[baseIndex];\n const targetBlock = targetBlocks[targetIndex];\n const typeBonus = baseBlock.type === targetBlock.type ? 2 : 0;\n const anchorSimilarity = computeJaccardSimilarity(\n baseBlock.anchorText,\n targetBlock.anchorText,\n 3\n );\n const lengthRatio =\n Math.min(baseBlock.content.length, targetBlock.content.length) /\n Math.max(baseBlock.content.length, targetBlock.content.length);\n const lengthBonus = lengthRatio > 0.75 ? 1 : 0;\n return typeBonus + lengthBonus + anchorSimilarity * 8; // weighted toward anchor similarity\n };\n\n // initialize first row and column\n for (let i = 1; i <= baseLength; i += 1) {\n scoreMatrix[i][0] = scoreMatrix[i - 1][0] + gapPenalty;\n traceMatrix[i][0] = 'up';\n }\n for (let j = 1; j <= targetLength; j += 1) {\n scoreMatrix[0][j] = scoreMatrix[0][j - 1] + gapPenalty;\n traceMatrix[0][j] = 'left';\n }\n\n // fill\n for (let i = 1; i <= baseLength; i += 1) {\n for (let j = 1; j <= targetLength; j += 1) {\n const match = scoreMatrix[i - 1][j - 1] + computeMatchScore(i - 1, j - 1);\n const deleteGap = scoreMatrix[i - 1][j] + gapPenalty;\n const insertGap = scoreMatrix[i][j - 1] + gapPenalty;\n\n const best = Math.max(match, deleteGap, insertGap);\n scoreMatrix[i][j] = best;\n traceMatrix[i][j] =\n best === match ? 'diagonal' : best === deleteGap ? 'up' : 'left';\n }\n }\n\n // traceback\n const result: AlignmentPair[] = [];\n let i = baseLength;\n let j = targetLength;\n while (i > 0 || j > 0) {\n if (i > 0 && j > 0 && traceMatrix[i][j] === 'diagonal') {\n const baseIndex = i - 1;\n const targetIndex = j - 1;\n const similarityScore = computeJaccardSimilarity(\n baseBlocks[baseIndex].anchorText,\n targetBlocks[targetIndex].anchorText,\n 3\n );\n result.unshift({ baseIndex, targetIndex, similarityScore });\n i -= 1;\n j -= 1;\n } else if (i > 0 && (j === 0 || traceMatrix[i][j] === 'up')) {\n result.unshift({\n baseIndex: i - 1,\n targetIndex: null,\n similarityScore: 0,\n });\n i -= 1;\n } else if (j > 0 && (i === 0 || traceMatrix[i][j] === 'left')) {\n // target block has no corresponding base block (deleted)\n result.unshift({\n baseIndex: -1,\n targetIndex: j - 1,\n similarityScore: 0,\n });\n j -= 1;\n }\n }\n return result;\n};\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,4BACX,YACA,iBACoB;CACpB,MAAM,aAAa,WAAW;CAC9B,MAAM,eAAe,aAAa;CAElC,MAAM,cAA0B,MAAM,KAAK,EAAE,QAAQ,aAAa,EAAE,SAClE,MAAM,KAAK,EAAE,QAAQ,eAAe,EAAE,SAAS,CAAC,CAClD;CACA,MAAM,cAAgD,MAAM,KAC1D,EAAE,QAAQ,aAAa,EAAE,SACnB,MAAM,KAAK,EAAE,QAAQ,eAAe,EAAE,SAAS,UAAU,CACjE;CAEA,MAAM,aAAa;CAEnB,MAAM,qBACJ,WACA,gBACW;EACX,MAAM,YAAY,WAAW;EAC7B,MAAM,cAAc,aAAa;EACjC,MAAM,YAAY,UAAU,SAAS,YAAY,OAAO,IAAI;EAC5D,MAAM,mBAAmB,yBACvB,UAAU,YACV,YAAY,YACZ,CACF;EAKA,OAAO,aAHL,KAAK,IAAI,UAAU,QAAQ,QAAQ,YAAY,QAAQ,MAAM,IAC7D,KAAK,IAAI,UAAU,QAAQ,QAAQ,YAAY,QAAQ,MAAM,IAC7B,MAAO,IAAI,KACZ,mBAAmB;CACtD;CAGA,KAAK,IAAI,IAAI,GAAG,KAAK,YAAY,KAAK,GAAG;EACvC,YAAY,EAAE,CAAC,KAAK,YAAY,IAAI,EAAE,CAAC,KAAK;EAC5C,YAAY,EAAE,CAAC,KAAK;CACtB;CACA,KAAK,IAAI,IAAI,GAAG,KAAK,cAAc,KAAK,GAAG;EACzC,YAAY,EAAE,CAAC,KAAK,YAAY,EAAE,CAAC,IAAI,KAAK;EAC5C,YAAY,EAAE,CAAC,KAAK;CACtB;CAGA,KAAK,IAAI,IAAI,GAAG,KAAK,YAAY,KAAK,GACpC,KAAK,IAAI,IAAI,GAAG,KAAK,cAAc,KAAK,GAAG;EACzC,MAAM,QAAQ,YAAY,IAAI,EAAE,CAAC,IAAI,KAAK,kBAAkB,IAAI,GAAG,IAAI,CAAC;EACxE,MAAM,YAAY,YAAY,IAAI,EAAE,CAAC,KAAK;EAC1C,MAAM,YAAY,YAAY,EAAE,CAAC,IAAI,KAAK;EAE1C,MAAM,OAAO,KAAK,IAAI,OAAO,WAAW,SAAS;EACjD,YAAY,EAAE,CAAC,KAAK;EACpB,YAAY,EAAE,CAAC,KACb,SAAS,QAAQ,aAAa,SAAS,YAAY,OAAO;CAC9D;CAIF,MAAM,SAA0B,CAAC;CACjC,IAAI,IAAI;CACR,IAAI,IAAI;CACR,OAAO,IAAI,KAAK,IAAI,GAClB,IAAI,IAAI,KAAK,IAAI,KAAK,YAAY,EAAE,CAAC,OAAO,YAAY;EACtD,MAAM,YAAY,IAAI;EACtB,MAAM,cAAc,IAAI;EACxB,MAAM,kBAAkB,yBACtB,WAAW,UAAU,CAAC,YACtB,aAAa,YAAY,CAAC,YAC1B,CACF;EACA,OAAO,QAAQ;GAAE;GAAW;GAAa;EAAgB,CAAC;EAC1D,KAAK;EACL,KAAK;CACP,OAAO,IAAI,IAAI,MAAM,MAAM,KAAK,YAAY,EAAE,CAAC,OAAO,OAAO;EAC3D,OAAO,QAAQ;GACb,WAAW,IAAI;GACf,aAAa;GACb,iBAAiB;EACnB,CAAC;EACD,KAAK;CACP,OAAO,IAAI,IAAI,MAAM,MAAM,KAAK,YAAY,EAAE,CAAC,OAAO,SAAS;EAE7D,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,IAAI;GACjB,iBAAiB;EACnB,CAAC;EACD,KAAK;CACP;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"alignBlocks.mjs","names":[],"sources":["../../../src/docReview/alignBlocks.ts"],"sourcesContent":["import { computeJaccardSimilarity } from './computeSimilarity';\nimport type { AlignmentPair, FingerprintedBlock } from './types';\n\n/** Cost of leaving a block unaligned (an insertion or a deletion). */\nconst GAP_PENALTY = -2;\n\n/**\n * Score of a pair that structural evidence rules out.\n *\n * Strictly below the cost of two gaps (`2 * GAP_PENALTY`) so the aligner always\n * prefers reporting an insertion plus a deletion over such a pair. Every other\n * score is positive, which means that without an explicit veto the aligner would\n * rather pair two unrelated blocks than leave them unaligned — and a bogus pair\n * is planned as `reuse`, which keeps the stale translation verbatim *and*\n * inserts the freshly translated base block next to it, producing the duplicated\n * headings this penalty exists to prevent.\n */\nconst STRUCTURAL_MISMATCH_PENALTY = GAP_PENALTY * 2 - 1;\n\n/** Reward for two blocks opened by a heading of the very same depth. */\nconst HEADING_DEPTH_MATCH_BONUS = 3;\n\n/** Minimum length ratio for the (small) \"comparable size\" reward. */\nconst COMPARABLE_LENGTH_RATIO = 0.75;\n\n/**\n * Body length from which a section is considered to carry content of its own.\n *\n * Kept above a single sentence so a translator's short lead-in paragraph is not\n * mistaken for a whole section body.\n */\nconst SUBSTANTIAL_BODY_LENGTH = 80;\n\n/**\n * Length of the body a block carries below its opening heading.\n *\n * A section that only holds its heading (because subsections carry all of its\n * content) is structurally different from one that holds a full body, and that\n * difference survives translation.\n *\n * @param block - The block to measure.\n * @returns The trimmed length of everything below the opening heading line.\n */\nconst measureBodyLength = (block: FingerprintedBlock): number => {\n if (block.headingDepth === null) return block.content.trim().length;\n\n const [, ...bodyLines] = block.content.split('\\n');\n\n return bodyLines.join('\\n').trim().length;\n};\n\n/**\n * Align the blocks of a base document with the blocks of its translation using a\n * Needleman–Wunsch global alignment over heading depth, anchor similarity and\n * block type.\n *\n * Because prose differs across languages, the score is weighted toward the\n * structural signals — heading depth first, then the anchor (digits and symbols)\n * — rather than the words themselves.\n *\n * @param baseBlocks - Blocks of the base (source) document.\n * @param targetBlocks - Blocks of the target (translated) document.\n * @returns The ordered list of alignment pairs, including insertions and deletions.\n */\nexport const alignBaseAndTargetBlocks = (\n baseBlocks: FingerprintedBlock[],\n targetBlocks: FingerprintedBlock[]\n): AlignmentPair[] => {\n const baseLength = baseBlocks.length;\n const targetLength = targetBlocks.length;\n\n const scoreMatrix: number[][] = Array.from({ length: baseLength + 1 }, () =>\n Array.from({ length: targetLength + 1 }, () => 0)\n );\n const traceMatrix: ('diagonal' | 'up' | 'left')[][] = Array.from(\n { length: baseLength + 1 },\n () => Array.from({ length: targetLength + 1 }, () => 'diagonal')\n );\n\n const computeMatchScore = (\n baseIndex: number,\n targetIndex: number\n ): number => {\n const baseBlock = baseBlocks[baseIndex]!;\n const targetBlock = targetBlocks[targetIndex]!;\n\n // Translating a document never changes its heading depths, so two headings\n // of different depths cannot be counterparts, however similar their content.\n const hasComparableHeadingDepths =\n baseBlock.headingDepth !== null && targetBlock.headingDepth !== null;\n\n if (\n hasComparableHeadingDepths &&\n baseBlock.headingDepth !== targetBlock.headingDepth\n ) {\n return STRUCTURAL_MISMATCH_PENALTY;\n }\n\n // A section reduced to its bare heading (its content living in subsections)\n // is not the translation of a section holding a full body. Pairing them\n // reuses that whole body while the base heading is translated again right\n // next to it — which is exactly how a duplicated heading appears.\n const baseBodyLength = measureBodyLength(baseBlock);\n const targetBodyLength = measureBodyLength(targetBlock);\n const isBodyPresenceMismatched =\n (baseBodyLength === 0 && targetBodyLength >= SUBSTANTIAL_BODY_LENGTH) ||\n (targetBodyLength === 0 && baseBodyLength >= SUBSTANTIAL_BODY_LENGTH);\n\n if (isBodyPresenceMismatched) return STRUCTURAL_MISMATCH_PENALTY;\n\n const lengthRatio =\n Math.min(baseBlock.content.length, targetBlock.content.length) /\n Math.max(baseBlock.content.length, targetBlock.content.length);\n\n const headingDepthBonus = hasComparableHeadingDepths\n ? HEADING_DEPTH_MATCH_BONUS\n : 0;\n const typeBonus = baseBlock.type === targetBlock.type ? 2 : 0;\n const anchorSimilarity = computeJaccardSimilarity(\n baseBlock.anchorText,\n targetBlock.anchorText,\n 3\n );\n const lengthBonus = lengthRatio > COMPARABLE_LENGTH_RATIO ? 1 : 0;\n\n // weighted toward the structural signals (heading depth, then anchor)\n return headingDepthBonus + typeBonus + lengthBonus + anchorSimilarity * 8;\n };\n\n // initialize first row and column\n for (let i = 1; i <= baseLength; i += 1) {\n scoreMatrix[i][0] = scoreMatrix[i - 1][0] + GAP_PENALTY;\n traceMatrix[i][0] = 'up';\n }\n for (let j = 1; j <= targetLength; j += 1) {\n scoreMatrix[0][j] = scoreMatrix[0][j - 1] + GAP_PENALTY;\n traceMatrix[0][j] = 'left';\n }\n\n // fill\n for (let i = 1; i <= baseLength; i += 1) {\n for (let j = 1; j <= targetLength; j += 1) {\n const match = scoreMatrix[i - 1][j - 1] + computeMatchScore(i - 1, j - 1);\n const deleteGap = scoreMatrix[i - 1][j] + GAP_PENALTY;\n const insertGap = scoreMatrix[i][j - 1] + GAP_PENALTY;\n\n const best = Math.max(match, deleteGap, insertGap);\n scoreMatrix[i][j] = best;\n traceMatrix[i][j] =\n best === match ? 'diagonal' : best === deleteGap ? 'up' : 'left';\n }\n }\n\n // traceback\n const result: AlignmentPair[] = [];\n let i = baseLength;\n let j = targetLength;\n while (i > 0 || j > 0) {\n if (i > 0 && j > 0 && traceMatrix[i][j] === 'diagonal') {\n const baseIndex = i - 1;\n const targetIndex = j - 1;\n const similarityScore = computeJaccardSimilarity(\n baseBlocks[baseIndex].anchorText,\n targetBlocks[targetIndex].anchorText,\n 3\n );\n result.unshift({ baseIndex, targetIndex, similarityScore });\n i -= 1;\n j -= 1;\n } else if (i > 0 && (j === 0 || traceMatrix[i][j] === 'up')) {\n result.unshift({\n baseIndex: i - 1,\n targetIndex: null,\n similarityScore: 0,\n });\n i -= 1;\n } else if (j > 0 && (i === 0 || traceMatrix[i][j] === 'left')) {\n // target block has no corresponding base block (deleted)\n result.unshift({\n baseIndex: -1,\n targetIndex: j - 1,\n similarityScore: 0,\n });\n j -= 1;\n }\n }\n return result;\n};\n"],"mappings":";;;;AAIA,MAAM,cAAc;;;;;;;;;;;;AAapB,MAAM,8BAA8B,cAAc,IAAI;;AAGtD,MAAM,4BAA4B;;AAGlC,MAAM,0BAA0B;;;;;;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O,QAAQ;GACb,WAAW,IAAI;GACf,aAAa;GACb,iBAAiB;EACnB,CAAC;EACD,KAAK;CACP,OAAO,IAAI,IAAI,MAAM,MAAM,KAAK,YAAY,EAAE,CAAC,OAAO,SAAS;EAE7D,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,IAAI;GACjB,iBAAiB;EACnB,CAAC;EACD,KAAK;CACP;CAEF,OAAO;AACT"}
@@ -29,6 +29,18 @@ const identifySegmentsToReview = ({ baseBlocks, targetBlocks, plan }) => {
29
29
  });
30
30
  return { segmentsToReview };
31
31
  };
32
+ /** Markdown separates two blocks with a blank line. */
33
+ const endsWithBlockBoundary = (text) => /\n[ \t]*\n$/.test(text);
34
+ /**
35
+ * The newlines missing at the end of `text` for it to close a markdown block.
36
+ *
37
+ * @param text - The document built so far.
38
+ * @returns `''`, `'\n'` or `'\n\n'` depending on how the text already ends.
39
+ */
40
+ const buildBlockSeparator = (text) => {
41
+ if (text.length === 0 || endsWithBlockBoundary(text)) return "";
42
+ return text.endsWith("\n") ? "\n" : "\n\n";
43
+ };
32
44
  /**
33
45
  * Merge reviewed translations back into the final document following the
34
46
  * alignment plan, reusing untouched target blocks as-is.
@@ -39,22 +51,38 @@ const identifySegmentsToReview = ({ baseBlocks, targetBlocks, plan }) => {
39
51
  * @returns The rebuilt target document.
40
52
  */
41
53
  const mergeReviewedSegments = (plan, targetBlocks, reviewedSegments) => {
42
- const outputParts = [];
54
+ let mergedText = "";
55
+ let previousPartWasGenerated = false;
56
+ /**
57
+ * Append one part, keeping a blank line around the content this run produced.
58
+ *
59
+ * Blocks own the blank lines that trail them, so two verbatim blocks already
60
+ * separate themselves and are appended untouched — a document with nothing to
61
+ * change merges back byte for byte. Generated content is the exception: the
62
+ * block it lands after may be the one that used to end the document, which
63
+ * carries no trailing blank line, and the two would be glued into a single
64
+ * markdown block (a heading swallowed by the paragraph above it).
65
+ */
66
+ const appendPart = (content, isGenerated) => {
67
+ if (content.length === 0) return;
68
+ if (isGenerated || previousPartWasGenerated) mergedText += buildBlockSeparator(mergedText);
69
+ mergedText += content;
70
+ previousPartWasGenerated = isGenerated;
71
+ };
43
72
  plan.actions.forEach((action, actionIndex) => {
44
- if (action.kind === "reuse") outputParts.push(targetBlocks[action.targetIndex].content);
73
+ if (action.kind === "reuse") appendPart(targetBlocks[action.targetIndex].content, false);
45
74
  else if (action.kind === "review" || action.kind === "insert_new") {
46
75
  const reviewedContent = reviewedSegments.get(actionIndex);
47
- if (reviewedContent !== void 0) outputParts.push(reviewedContent);
48
- else if (action.kind === "review" && action.targetIndex !== null) outputParts.push(targetBlocks[action.targetIndex].content);
49
- else outputParts.push("\n");
76
+ if (reviewedContent !== void 0) appendPart(reviewedContent, true);
77
+ else if (action.kind === "review" && action.targetIndex !== null) appendPart(targetBlocks[action.targetIndex].content, false);
78
+ else appendPart("\n", false);
50
79
  } else if (action.kind === "delete") {
51
80
  const reviewedContent = reviewedSegments.get(actionIndex);
52
- if (reviewedContent !== void 0) {
53
- if (reviewedContent) outputParts.push(reviewedContent);
54
- } else outputParts.push(targetBlocks[action.targetIndex].content);
81
+ if (reviewedContent !== void 0) appendPart(reviewedContent, true);
82
+ else appendPart(targetBlocks[action.targetIndex].content, false);
55
83
  }
56
84
  });
57
- return outputParts.join("");
85
+ return mergedText;
58
86
  };
59
87
 
60
88
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"rebuildDocument.mjs","names":[],"sources":["../../../src/docReview/rebuildDocument.ts"],"sourcesContent":["import type { AlignmentPlan, FingerprintedBlock } from './types';\n\n/**\n * A block that needs to be translated or re-translated by an external consumer\n * (an AI client, a human, or an agent).\n */\nexport type SegmentToReview = {\n /** The base block to translate. */\n baseBlock: FingerprintedBlock;\n /** Existing target translation, or `null` when the block is new. */\n targetBlockText: string | null;\n /** Index of the originating action within {@link AlignmentPlan.actions}. */\n actionIndex: number;\n};\n\nexport type RebuildInput = {\n baseBlocks: FingerprintedBlock[];\n targetBlocks: FingerprintedBlock[];\n plan: AlignmentPlan;\n};\n\nexport type RebuildResult = {\n segmentsToReview: SegmentToReview[];\n};\n\n/**\n * Analyze the alignment plan and return only the segments that need\n * review/translation. Does not generate output text - that is done by\n * {@link mergeReviewedSegments} once the translations are available.\n *\n * @param input - The base/target blocks and the alignment plan.\n * @returns The list of segments that require translation.\n */\nexport const identifySegmentsToReview = ({\n baseBlocks,\n targetBlocks,\n plan,\n}: RebuildInput): RebuildResult => {\n const segmentsToReview: SegmentToReview[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'review') {\n const baseBlock = baseBlocks[action.baseIndex];\n const targetBlockText =\n action.targetIndex !== null\n ? targetBlocks[action.targetIndex].content\n : null;\n\n segmentsToReview.push({ baseBlock, targetBlockText, actionIndex });\n } else if (action.kind === 'insert_new') {\n const baseBlock = baseBlocks[action.baseIndex];\n\n segmentsToReview.push({\n baseBlock,\n targetBlockText: null,\n actionIndex,\n });\n }\n });\n\n return { segmentsToReview };\n};\n\n/**\n * Merge reviewed translations back into the final document following the\n * alignment plan, reusing untouched target blocks as-is.\n *\n * @param plan - The alignment plan.\n * @param targetBlocks - Blocks of the existing target document.\n * @param reviewedSegments - Map of action index to its reviewed translation.\n * @returns The rebuilt target document.\n */\nexport const mergeReviewedSegments = (\n plan: AlignmentPlan,\n targetBlocks: FingerprintedBlock[],\n reviewedSegments: Map<number, string>\n): string => {\n const outputParts: string[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'reuse') {\n outputParts.push(targetBlocks[action.targetIndex].content);\n } else if (action.kind === 'review' || action.kind === 'insert_new') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n\n if (reviewedContent !== undefined) {\n outputParts.push(reviewedContent);\n } else {\n // Fallback: if review failed, use existing or blank\n if (action.kind === 'review' && action.targetIndex !== null) {\n outputParts.push(targetBlocks[action.targetIndex].content);\n } else {\n outputParts.push('\\n');\n }\n }\n } else if (action.kind === 'delete') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n if (reviewedContent !== undefined) {\n // Caller explicitly resolved this block: empty string = actually delete,\n // non-empty string = replacement content.\n if (reviewedContent) outputParts.push(reviewedContent);\n } else {\n // Default: keep verbatim. A target block with no base counterpart may\n // just be a section the aligner could not follow (reordering, split\n // prose) — keeping it prevents accidental data loss in log/read-only mode.\n outputParts.push(targetBlocks[action.targetIndex].content);\n }\n }\n });\n\n return outputParts.join('');\n};\n"],"mappings":";;;;;;;;;AAiCA,MAAa,4BAA4B,EACvC,YACA,cACA,WACiC;CACjC,MAAM,mBAAsC,CAAC;CAE7C,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAAO,SAAS,UAAU;GAC5B,MAAM,YAAY,WAAW,OAAO;GACpC,MAAM,kBACJ,OAAO,gBAAgB,OACnB,aAAa,OAAO,YAAY,CAAC,UACjC;GAEN,iBAAiB,KAAK;IAAE;IAAW;IAAiB;GAAY,CAAC;EACnE,OAAO,IAAI,OAAO,SAAS,cAAc;GACvC,MAAM,YAAY,WAAW,OAAO;GAEpC,iBAAiB,KAAK;IACpB;IACA,iBAAiB;IACjB;GACF,CAAC;EACH;CACF,CAAC;CAED,OAAO,EAAE,iBAAiB;AAC5B;;;;;;;;;;AAWA,MAAa,yBACX,MACA,cACA,qBACW;CACX,MAAM,cAAwB,CAAC;CAE/B,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAAO,SAAS,SAClB,YAAY,KAAK,aAAa,OAAO,YAAY,CAAC,OAAO;OACpD,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,cAAc;GACnE,MAAM,kBAAkB,iBAAiB,IAAI,WAAW;GAExD,IAAI,oBAAoB,QACtB,YAAY,KAAK,eAAe;QAGhC,IAAI,OAAO,SAAS,YAAY,OAAO,gBAAgB,MACrD,YAAY,KAAK,aAAa,OAAO,YAAY,CAAC,OAAO;QAEzD,YAAY,KAAK,IAAI;EAG3B,OAAO,IAAI,OAAO,SAAS,UAAU;GACnC,MAAM,kBAAkB,iBAAiB,IAAI,WAAW;GACxD,IAAI,oBAAoB,QAGtB;QAAI,iBAAiB,YAAY,KAAK,eAAe;GAAC,OAKtD,YAAY,KAAK,aAAa,OAAO,YAAY,CAAC,OAAO;EAE7D;CACF,CAAC;CAED,OAAO,YAAY,KAAK,EAAE;AAC5B"}
1
+ {"version":3,"file":"rebuildDocument.mjs","names":[],"sources":["../../../src/docReview/rebuildDocument.ts"],"sourcesContent":["import type { AlignmentPlan, FingerprintedBlock } from './types';\n\n/**\n * A block that needs to be translated or re-translated by an external consumer\n * (an AI client, a human, or an agent).\n */\nexport type SegmentToReview = {\n /** The base block to translate. */\n baseBlock: FingerprintedBlock;\n /** Existing target translation, or `null` when the block is new. */\n targetBlockText: string | null;\n /** Index of the originating action within {@link AlignmentPlan.actions}. */\n actionIndex: number;\n};\n\nexport type RebuildInput = {\n baseBlocks: FingerprintedBlock[];\n targetBlocks: FingerprintedBlock[];\n plan: AlignmentPlan;\n};\n\nexport type RebuildResult = {\n segmentsToReview: SegmentToReview[];\n};\n\n/**\n * Analyze the alignment plan and return only the segments that need\n * review/translation. Does not generate output text - that is done by\n * {@link mergeReviewedSegments} once the translations are available.\n *\n * @param input - The base/target blocks and the alignment plan.\n * @returns The list of segments that require translation.\n */\nexport const identifySegmentsToReview = ({\n baseBlocks,\n targetBlocks,\n plan,\n}: RebuildInput): RebuildResult => {\n const segmentsToReview: SegmentToReview[] = [];\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'review') {\n const baseBlock = baseBlocks[action.baseIndex];\n const targetBlockText =\n action.targetIndex !== null\n ? targetBlocks[action.targetIndex].content\n : null;\n\n segmentsToReview.push({ baseBlock, targetBlockText, actionIndex });\n } else if (action.kind === 'insert_new') {\n const baseBlock = baseBlocks[action.baseIndex];\n\n segmentsToReview.push({\n baseBlock,\n targetBlockText: null,\n actionIndex,\n });\n }\n });\n\n return { segmentsToReview };\n};\n\n/** Markdown separates two blocks with a blank line. */\nconst endsWithBlockBoundary = (text: string): boolean =>\n /\\n[ \\t]*\\n$/.test(text);\n\n/**\n * The newlines missing at the end of `text` for it to close a markdown block.\n *\n * @param text - The document built so far.\n * @returns `''`, `'\\n'` or `'\\n\\n'` depending on how the text already ends.\n */\nconst buildBlockSeparator = (text: string): string => {\n if (text.length === 0 || endsWithBlockBoundary(text)) return '';\n\n return text.endsWith('\\n') ? '\\n' : '\\n\\n';\n};\n\n/**\n * Merge reviewed translations back into the final document following the\n * alignment plan, reusing untouched target blocks as-is.\n *\n * @param plan - The alignment plan.\n * @param targetBlocks - Blocks of the existing target document.\n * @param reviewedSegments - Map of action index to its reviewed translation.\n * @returns The rebuilt target document.\n */\nexport const mergeReviewedSegments = (\n plan: AlignmentPlan,\n targetBlocks: FingerprintedBlock[],\n reviewedSegments: Map<number, string>\n): string => {\n let mergedText = '';\n let previousPartWasGenerated = false;\n\n /**\n * Append one part, keeping a blank line around the content this run produced.\n *\n * Blocks own the blank lines that trail them, so two verbatim blocks already\n * separate themselves and are appended untouched — a document with nothing to\n * change merges back byte for byte. Generated content is the exception: the\n * block it lands after may be the one that used to end the document, which\n * carries no trailing blank line, and the two would be glued into a single\n * markdown block (a heading swallowed by the paragraph above it).\n */\n const appendPart = (content: string, isGenerated: boolean): void => {\n if (content.length === 0) return;\n\n if (isGenerated || previousPartWasGenerated) {\n mergedText += buildBlockSeparator(mergedText);\n }\n\n mergedText += content;\n previousPartWasGenerated = isGenerated;\n };\n\n plan.actions.forEach((action, actionIndex) => {\n if (action.kind === 'reuse') {\n appendPart(targetBlocks[action.targetIndex]!.content, false);\n } else if (action.kind === 'review' || action.kind === 'insert_new') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n\n if (reviewedContent !== undefined) {\n appendPart(reviewedContent, true);\n } else {\n // Fallback: if review failed, use existing or blank\n if (action.kind === 'review' && action.targetIndex !== null) {\n appendPart(targetBlocks[action.targetIndex]!.content, false);\n } else {\n appendPart('\\n', false);\n }\n }\n } else if (action.kind === 'delete') {\n const reviewedContent = reviewedSegments.get(actionIndex);\n if (reviewedContent !== undefined) {\n // Caller explicitly resolved this block: empty string = actually delete,\n // non-empty string = replacement content.\n appendPart(reviewedContent, true);\n } else {\n // Default: keep verbatim. A target block with no base counterpart may\n // just be a section the aligner could not follow (reordering, split\n // prose) — keeping it prevents accidental data loss in log/read-only mode.\n appendPart(targetBlocks[action.targetIndex]!.content, false);\n }\n }\n });\n\n return mergedText;\n};\n"],"mappings":";;;;;;;;;AAiCA,MAAa,4BAA4B,EACvC,YACA,cACA,WACiC;CACjC,MAAM,mBAAsC,CAAC;CAE7C,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAAO,SAAS,UAAU;GAC5B,MAAM,YAAY,WAAW,OAAO;GACpC,MAAM,kBACJ,OAAO,gBAAgB,OACnB,aAAa,OAAO,YAAY,CAAC,UACjC;GAEN,iBAAiB,KAAK;IAAE;IAAW;IAAiB;GAAY,CAAC;EACnE,OAAO,IAAI,OAAO,SAAS,cAAc;GACvC,MAAM,YAAY,WAAW,OAAO;GAEpC,iBAAiB,KAAK;IACpB;IACA,iBAAiB;IACjB;GACF,CAAC;EACH;CACF,CAAC;CAED,OAAO,EAAE,iBAAiB;AAC5B;;AAGA,MAAM,yBAAyB,SAC7B,cAAc,KAAK,IAAI;;;;;;;AAQzB,MAAM,uBAAuB,SAAyB;CACpD,IAAI,KAAK,WAAW,KAAK,sBAAsB,IAAI,GAAG,OAAO;CAE7D,OAAO,KAAK,SAAS,IAAI,IAAI,OAAO;AACtC;;;;;;;;;;AAWA,MAAa,yBACX,MACA,cACA,qBACW;CACX,IAAI,aAAa;CACjB,IAAI,2BAA2B;;;;;;;;;;;CAY/B,MAAM,cAAc,SAAiB,gBAA+B;EAClE,IAAI,QAAQ,WAAW,GAAG;EAE1B,IAAI,eAAe,0BACjB,cAAc,oBAAoB,UAAU;EAG9C,cAAc;EACd,2BAA2B;CAC7B;CAEA,KAAK,QAAQ,SAAS,QAAQ,gBAAgB;EAC5C,IAAI,OAA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