dsh-better-edit 0.1.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 (82) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +188 -0
  3. package/cordis.patch.yml +8 -0
  4. package/lib/constants.js +12 -0
  5. package/lib/drift.js +98 -0
  6. package/lib/dsh-context.js +27 -0
  7. package/lib/edit-diff.js +121 -0
  8. package/lib/edit-normalize.js +9 -0
  9. package/lib/edit-pipeline.js +199 -0
  10. package/lib/edit-response.js +172 -0
  11. package/lib/file-kind.js +121 -0
  12. package/lib/file-reader.js +80 -0
  13. package/lib/fs-bridge.js +106 -0
  14. package/lib/fs-write.js +151 -0
  15. package/lib/hash-store.js +380 -0
  16. package/lib/hashline/alphabet.js +6 -0
  17. package/lib/hashline/apply.js +223 -0
  18. package/lib/hashline/hash.js +241 -0
  19. package/lib/hashline/hasher.js +23 -0
  20. package/lib/hashline/index.js +4 -0
  21. package/lib/hashline/parse.js +35 -0
  22. package/lib/hashline/resolve.js +365 -0
  23. package/lib/hashline/served.js +120 -0
  24. package/lib/index.js +91 -0
  25. package/lib/noop-guard.js +15 -0
  26. package/lib/paths.js +37 -0
  27. package/lib/prompts.js +54 -0
  28. package/lib/read-render.js +142 -0
  29. package/lib/schema.js +24 -0
  30. package/lib/served-state.js +34 -0
  31. package/lib/served-store.js +230 -0
  32. package/lib/snapshot-store.js +108 -0
  33. package/lib/tool-batch-edit.js +434 -0
  34. package/lib/tool-edit.js +152 -0
  35. package/lib/tool-read.js +86 -0
  36. package/lib/tool-undo.js +118 -0
  37. package/lib/truncate.js +98 -0
  38. package/lib/types/constants.d.ts +11 -0
  39. package/lib/types/drift.d.ts +29 -0
  40. package/lib/types/dsh-context.d.ts +23 -0
  41. package/lib/types/edit-diff.d.ts +14 -0
  42. package/lib/types/edit-normalize.d.ts +1 -0
  43. package/lib/types/edit-pipeline.d.ts +54 -0
  44. package/lib/types/edit-response.d.ts +107 -0
  45. package/lib/types/file-kind.d.ts +18 -0
  46. package/lib/types/file-reader.d.ts +47 -0
  47. package/lib/types/fs-bridge.d.ts +32 -0
  48. package/lib/types/fs-write.d.ts +2 -0
  49. package/lib/types/hash-store.d.ts +33 -0
  50. package/lib/types/hashline/alphabet.d.ts +5 -0
  51. package/lib/types/hashline/apply.d.ts +22 -0
  52. package/lib/types/hashline/hash.d.ts +19 -0
  53. package/lib/types/hashline/hasher.d.ts +8 -0
  54. package/lib/types/hashline/index.d.ts +4 -0
  55. package/lib/types/hashline/parse.d.ts +7 -0
  56. package/lib/types/hashline/resolve.d.ts +59 -0
  57. package/lib/types/hashline/served.d.ts +43 -0
  58. package/lib/types/index.d.ts +23 -0
  59. package/lib/types/noop-guard.d.ts +5 -0
  60. package/lib/types/paths.d.ts +11 -0
  61. package/lib/types/prompts.d.ts +17 -0
  62. package/lib/types/read-render.d.ts +21 -0
  63. package/lib/types/schema.d.ts +39 -0
  64. package/lib/types/served-state.d.ts +3 -0
  65. package/lib/types/served-store.d.ts +53 -0
  66. package/lib/types/snapshot-store.d.ts +14 -0
  67. package/lib/types/tool-batch-edit.d.ts +21 -0
  68. package/lib/types/tool-edit.d.ts +22 -0
  69. package/lib/types/tool-read.d.ts +21 -0
  70. package/lib/types/tool-undo.d.ts +20 -0
  71. package/lib/types/truncate.d.ts +32 -0
  72. package/lib/types/undo-edit.d.ts +32 -0
  73. package/lib/types/undo-store.d.ts +14 -0
  74. package/lib/types/utils.d.ts +13 -0
  75. package/lib/types/validation.d.ts +7 -0
  76. package/lib/types/write-hook.d.ts +21 -0
  77. package/lib/undo-edit.js +83 -0
  78. package/lib/undo-store.js +43 -0
  79. package/lib/utils.js +76 -0
  80. package/lib/validation.js +33 -0
  81. package/lib/write-hook.js +72 -0
  82. package/package.json +87 -0
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RimuruW and Yugimob (original pi-hashline-edit / pi-hashline-edit-pro)
4
+ Copyright (c) 2026 pi-hashline-edit-lsz contributors (pi port, hashline core)
5
+ Copyright (c) 2026 dsh-better-edit contributors (dsh port)
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # dsh-better-edit
2
+
3
+ Hash-anchored `read` / `edit` / `batch_edit` / `undo_last_edit` tools for
4
+ [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh`).
5
+ Every line of a file gets a unique 3-character hash, and you edit by hash. No
6
+ line numbers, no fuzzy matching, no edits landing on the wrong line.
7
+
8
+ This is a dsh port of
9
+ [pi-hashline-edit-lsz](https://github.com/Rianico/pi-hashline-edit-lsz) (itself
10
+ a self-maintained fork of pi-hashline-edit / pi-hashline-edit-pro by RimuruW
11
+ and Yugimob). The hashline core is ported byte-for-byte; the tool layer is
12
+ rewritten on dsh's plugin API.
13
+
14
+ ## What you get
15
+
16
+ - **Read with anchors.** Every line comes back as `HASH│content`. The hash is
17
+ the line's address.
18
+ - **Edit by hash.** `edit` targets a range of hashes
19
+ (`remove_from` / `remove_to`), so edits always land on the lines you meant.
20
+ - **Anchors that stay put.** Edit one part of a file and the hashes of the
21
+ rest stay the same. Read once, keep editing.
22
+ - **Fresh anchors, automatically.** After every `write` you get the new
23
+ anchors (auto-read). After every `edit` you get the diff with the new
24
+ hashes.
25
+ - **Undo when you need it.** The last edit on a file can be reverted, even
26
+ after a restart.
27
+ - **Safe writes.** Permissions, line endings, BOMs, symlinks, and hard links
28
+ survive every edit (writes go through `ctx.fs`, honoring sandboxed/remote
29
+ backends).
30
+ - **Reject-and-serve.** A stale or never-served range is hard-rejected with
31
+ fresh `HASH│content` rows so the retry needs no `read`.
32
+
33
+ ## How it replaces the built-in tools
34
+
35
+ dsh's tool registry resolves per scope: an agent sees `agent → preset →
36
+ global`, and its **own** layer always wins. The built-in `read`/`edit` live on
37
+ the agent-preset layer, so a plain global registration cannot replace them.
38
+ This plugin:
39
+
40
+ 1. Mounts as a host-plane Cordis plugin via its `cordis.patch.yml` bundle
41
+ patch.
42
+ 2. On `agent/session-start`, registers the hashline tools **and** the
43
+ `tool:read` / `tool:edit` prompt sections on the agent's own scope layer —
44
+ they shadow the preset's built-ins for that agent and unwind automatically
45
+ when the agent is disposed.
46
+ 3. Leaves the built-in `write` in place, but a scoped `tools/post-execute`
47
+ listener appends the hashline auto-read to write results.
48
+
49
+ ## Installation
50
+
51
+ From npm:
52
+
53
+ ```sh
54
+ dsh plugin --profile <name> add dsh-better-edit
55
+ ```
56
+
57
+ From a local checkout:
58
+
59
+ ```sh
60
+ dsh plugin --profile <name> add /path/to/dsh-better-edit
61
+ ```
62
+
63
+ The profile's next session runs with the hashline tools installed. To verify
64
+ the layer is active:
65
+
66
+ ```sh
67
+ dsh --profile <name> --dump-config # shows a "# == dsh-better-edit" layer
68
+ ```
69
+
70
+ ### Requirements
71
+
72
+ - Node `^22.19.0 || >=24.0.0` (dsh's requirement; the store uses `node:sqlite`)
73
+ - A dsh profile (`dsh plugin` initializes one on first use)
74
+
75
+ ## Usage
76
+
77
+ 1. Read a file:
78
+
79
+ ```text
80
+ ve7│function hello() {
81
+ szJ│ console.log("world");
82
+ kQm│}
83
+ ```
84
+
85
+ 1. Edit a line by its hash:
86
+
87
+ ```json
88
+ {
89
+ "path": "src/main.ts",
90
+ "remove_from": "szJ",
91
+ "remove_to": "szJ",
92
+ "replacement_text": " console.log('hi');"
93
+ }
94
+ ```
95
+
96
+ 1. Keep editing. Anchors for lines you didn't touch stay valid; the post-edit
97
+ diff and the auto-read after `write` hand you fresh anchors.
98
+
99
+ ### The read tool
100
+
101
+ `read` returns a text file with every line prefixed by `HASH│content` (hash =
102
+ 3 chars from `A-Za-z0-9`). Parameters: `offset` (1-based start line), `limit`
103
+ (maximum lines). Paged output ends with `[Showing lines N-M of T. Use
104
+ offset=… to continue.]`. Lines larger than 200KB are shown as a marker with a
105
+ `sed` inspection hint — hash anchors need full lines.
106
+
107
+ ### The edit tool
108
+
109
+ | Field | Meaning |
110
+ | --- | --- |
111
+ | `path` | Path to edit (relative to the session cwd; absolute works). |
112
+ | `remove_from` | Bare 3-char hash of the first line to remove. |
113
+ | `remove_to` | Bare 3-char hash of the last line to remove. |
114
+ | `replacement_text` | Replacement text; `""` deletes the range. |
115
+
116
+ The tool verifies **every line** of the resolved range against what the model
117
+ was actually shown. A line inside the range that changed on disk since it was
118
+ served is hard-rejected with `[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]` /
119
+ `[E_RANGE_UNVERIFIED]`, and the current range is echoed back as fresh anchors
120
+ (reject-and-serve). Anchors for lines outside the post-edit diff window are
121
+ recovered with a `read` — that is the documented on-demand recovery.
122
+
123
+ ### batch_edit
124
+
125
+ Several edits in one atomic call: `{ edits: [{ path?, remove_from,
126
+ remove_to, replacement_text }, …] }`. All-or-nothing — any failing item
127
+ rejects the whole batch with nothing written, and the failing item's current
128
+ range is echoed as fresh serves. Up to 32 items.
129
+
130
+ ### undo_last_edit
131
+
132
+ `{ path }` reverts the last hashline edit on the file, only while the file
133
+ still matches the stored post-edit content. A later external write clears the
134
+ history instead of being overwritten. Undo survives restarts (stored in the
135
+ hash store).
136
+
137
+ ## Store
138
+
139
+ Hash snapshots, served-state rows, and undo history live in one SQLite store
140
+ under the DeepSeek Harness home:
141
+
142
+ - `$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite` (default
143
+ `~/.dsh/plugins/dsh-better-edit/hash-store.sqlite`)
144
+
145
+ A 7-day TTL prunes served rows; missing-file snapshots are pruned at startup.
146
+ Corrupt stores are quarantined and rebuilt automatically.
147
+
148
+ ## Error codes
149
+
150
+ | Code | Meaning |
151
+ | --- | --- |
152
+ | `[E_ACCESS]` | File exists but is not readable/writable by the tool. |
153
+ | `[E_AMBIGUOUS_ANCHOR]` | A hash matches more than one current line; call `read` for fresh anchors. |
154
+ | `[E_BAD_OP]` | Range end precedes range start (autocorrected when the pair was reversed). |
155
+ | `[E_BAD_REF]` | `remove_from`/`remove_to` is not a bare 3-char hash. |
156
+ | `[E_BAD_SHAPE]` | Request/field shape is wrong (unknown fields, missing path, non-string text, …). |
157
+ | `[E_BARE_HASH_PREFIX]` | `HASH│` prefix pasted into `replacement_text` (autocorrected). |
158
+ | `[E_BATCH_ABORT]` | A batch item failed; the whole batch was rejected, nothing written. |
159
+ | `[E_FILE_TOO_LARGE]` | File exceeds the hashline line ceiling; use `write` or another approach. |
160
+ | `[E_INVALID_PATCH]` | Diff-preview markers pasted into `replacement_text` (autocorrected). |
161
+ | `[E_NOOP_LOOP]` | The exact same edit keeps producing no change; resubmitting is rejected. |
162
+ | `[E_NOT_FOUND]` | File does not exist. |
163
+ | `[E_NOT_OBSERVED]` | The file has not been observed in this session (read-before-write policy); call `read` first. |
164
+ | `[E_NOT_TEXT]` | Path is a directory, binary, or non-UTF-8 file; hashline edits only text. |
165
+ | `[E_RANGE_STALE]` | A served line differs on disk since it was read; the range is echoed fresh. |
166
+ | `[E_RANGE_UNSERVED]` | The range includes lines never served to the model. |
167
+ | `[E_RANGE_UNVERIFIED]` | Boundary anchor cannot be verified against served state. |
168
+ | `[E_STALE_ANCHOR]` | Anchor(s) no longer resolve; call `read` for fresh anchors. |
169
+ | `[E_UNDO_STALE]` | Cannot undo: the file was modified (or deleted) after the edit. |
170
+ | `[E_UNDO_UNAVAILABLE]` | Undo history could not be persisted; the edit was not applied. |
171
+ | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` to clear it. |
172
+
173
+ ## Development
174
+
175
+ ```sh
176
+ npm install
177
+ npm run typecheck # tsc --noEmit
178
+ npm test # vitest run
179
+ npm run build # tsc → lib/
180
+ ```
181
+
182
+ The test suite is ported from pi-hashline-edit-lsz (598 tests) and drives the
183
+ dsh tool builders directly over a local filesystem bridge.
184
+
185
+ ## License
186
+
187
+ MIT — see [LICENSE](LICENSE). Ported from pi-hashline-edit-lsz (MIT), which
188
+ itself carries the upstream copyrights of RimuruW and Yugimob.
@@ -0,0 +1,8 @@
1
+ # dsh-better-edit bundle patch: mount the host-plane plugin row.
2
+ # Installed via `dsh plugin add dsh-better-edit` (or a profile's bundle list).
3
+ # The plugin hooks agent/session-start and shadows the built-in read/edit tools
4
+ # (plus batch_edit / undo_last_edit) on each agent's own scope layer, so no
5
+ # preset editing or user config is needed.
6
+ - insert:
7
+ - id: dsh-better-edit
8
+ name: dsh-better-edit
@@ -0,0 +1,12 @@
1
+ export const AUTO_READ_MAX = 2000;
2
+ export const SNIFF_BYTES = 8192;
3
+ export const MAX_BYTES = 100 * 1024 * 1024;
4
+ export const MAX_READ_LINE_BYTES = 200 * 1024;
5
+ export const HASH_STORE_BUSY_TIMEOUT = 1000;
6
+ export const HASH_STORE_VERSION = 6;
7
+ export const BATCH_EDIT_MAX_ITEMS = 32;
8
+ export const SERVED_TTL_MS = 7 * 24 * 60 * 60 * 1000;
9
+ export const SERVED_ECHO_CAP = 150;
10
+ export const NOOP_LOOP_THRESHOLD = 3;
11
+ export const NEW_CONTENT_NOT_STRING_MSG = `[E_BAD_SHAPE] "replacement_text" must be a string with \\n line separators, not an array.` +
12
+ ` Do not pass an array of lines — pass the replacement text as one string: "line1\\nline2". Use "" to delete a range.`;
package/lib/drift.js ADDED
@@ -0,0 +1,98 @@
1
+ import { SERVED_ECHO_CAP } from "./constants.js";
2
+ import { fmtServedRows, } from "./hashline/served.js";
3
+ import { currentPositionOfDrifted, driftReported, markDriftReported, recordServed, servedPositionsOf, } from "./served-state.js";
4
+ export const DRIFT_NOTICE_HEADING = "Drift notice:";
5
+ export function computeDrift(input) {
6
+ const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP, } = input;
7
+ const resultHashSet = new Set(resultHashes);
8
+ const currentPosOfHash = new Map();
9
+ for (let i = 0; i < resultHashes.length; i++) {
10
+ currentPosOfHash.set(resultHashes[i], i);
11
+ }
12
+ const startPositions = servedPositionsOf(served, range.startHash);
13
+ const endPositions = servedPositionsOf(served, range.endHash);
14
+ let servedStartIdx;
15
+ let servedEndIdx;
16
+ if (startPositions.length === 1 && endPositions.length === 1) {
17
+ servedStartIdx = startPositions[0];
18
+ servedEndIdx = endPositions[0];
19
+ }
20
+ else {
21
+ servedStartIdx = range.startLine - 1;
22
+ servedEndIdx = range.endLine - 1;
23
+ }
24
+ const rangeFrom = Math.min(servedStartIdx, servedEndIdx);
25
+ const rangeTo = Math.max(servedStartIdx, servedEndIdx);
26
+ let total = 0;
27
+ let unshown = 0;
28
+ let anyNotReported = false;
29
+ const driftedPositions = [];
30
+ for (let p = 0; p < served.length; p++) {
31
+ const servedHash = served[p];
32
+ if (servedHash === null)
33
+ continue;
34
+ if (p >= rangeFrom && p <= rangeTo)
35
+ continue;
36
+ if (resultHashSet.has(servedHash))
37
+ continue;
38
+ total++;
39
+ if (!reported.has(servedHash))
40
+ anyNotReported = true;
41
+ const currentPos = currentPositionOfDrifted(served, currentPosOfHash, resultHashSet, p, range.delta);
42
+ if (currentPos >= 0 &&
43
+ currentPos < resultHashes.length &&
44
+ currentPos < resultLines.length) {
45
+ driftedPositions.push(currentPos);
46
+ }
47
+ else {
48
+ unshown++;
49
+ }
50
+ }
51
+ if (total === 0)
52
+ return undefined;
53
+ const countLabel = `${total} line(s)`;
54
+ if (!anyNotReported) {
55
+ return {
56
+ text: `${DRIFT_NOTICE_HEADING} ${countLabel} outside the edited range drifted and were already reported — call read to refresh.`,
57
+ rows: [],
58
+ total,
59
+ allAlreadyReported: true,
60
+ };
61
+ }
62
+ const driftedSet = new Set(driftedPositions);
63
+ const windowSet = new Set();
64
+ for (const pos of driftedPositions) {
65
+ for (const w of [pos - 1, pos, pos + 1]) {
66
+ if (w >= 0 && w < resultLines.length)
67
+ windowSet.add(w);
68
+ }
69
+ }
70
+ const windowPositions = [...windowSet].sort((a, b) => a - b);
71
+ const shownPositions = windowPositions.slice(0, cap);
72
+ unshown += windowPositions.length - shownPositions.length;
73
+ const rows = shownPositions.map((position) => ({
74
+ position,
75
+ hash: resultHashes[position],
76
+ content: resultLines[position],
77
+ drifted: driftedSet.has(position),
78
+ }));
79
+ const rowsText = fmtServedRows(rows, resultLines);
80
+ const moreText = unshown > 0
81
+ ? `\n[... ${unshown} more line(s) — call read to see them]`
82
+ : "";
83
+ return {
84
+ text: `${DRIFT_NOTICE_HEADING} ${countLabel} outside the edited range drifted. Current content around the drift:\n${rowsText}${moreText}`,
85
+ rows,
86
+ total,
87
+ allAlreadyReported: false,
88
+ };
89
+ }
90
+ export async function scanDrift(input) {
91
+ const reported = await driftReported(input.sessionKey, input.path);
92
+ const result = computeDrift({ ...input, reported });
93
+ if (!result || result.allAlreadyReported)
94
+ return result?.text;
95
+ await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })));
96
+ await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
97
+ return result.text;
98
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * dsh execution-context helpers shared by the tool layer: session cwd and
3
+ * served-state session key derived from the dsh {@link ToolExecution}.
4
+ * @module dsh-better-edit/dsh-context
5
+ */
6
+ import { sessionKeyFor } from './served-store.js';
7
+ /**
8
+ * The workspace directory a model-facing filesystem tool resolves relative
9
+ * paths against: the calling agent's per-session cwd (each session's tools act
10
+ * on ITS workspace), falling back to the process cwd for non-agent callers.
11
+ * Mirrors how `dsh-tool-bash` defaults a bash `workdir` to the session cwd.
12
+ * @param exec - the tool-execution context; only its optional `agent` is read.
13
+ * @returns the session cwd, or the process cwd when no agent applies.
14
+ */
15
+ export function execCwd(exec) {
16
+ return exec.agent?.session.header.cwd ?? process.cwd();
17
+ }
18
+ /**
19
+ * The served-state session key for one execution: the live session id. A
20
+ * stable key per session keeps served rows (what the model was shown) and
21
+ * undo history correctly scoped — never shared across sessions.
22
+ * @param exec - the tool-execution context.
23
+ * @returns the session key.
24
+ */
25
+ export function execSessionKey(exec) {
26
+ return sessionKeyFor(exec.agent?.session.id);
27
+ }
@@ -0,0 +1,121 @@
1
+ import * as Diff from "diff";
2
+ import { _lineHashesPure, ANCHOR_LEN, HASH_SEP } from "./hashline/index.js";
3
+ export function detectEnding(content) {
4
+ const lfIdx = content.indexOf("\n");
5
+ if (lfIdx === -1) {
6
+ return content.indexOf("\r") >= 0 ? "\r" : "\n";
7
+ }
8
+ const crlfIdx = content.indexOf("\r\n");
9
+ if (crlfIdx === -1)
10
+ return "\n";
11
+ return crlfIdx < lfIdx ? "\r\n" : "\n";
12
+ }
13
+ export function toLF(text) {
14
+ return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
15
+ }
16
+ export function restoreEndings(text, ending) {
17
+ if (ending === "\r\n")
18
+ return text.replace(/\n/g, "\r\n");
19
+ if (ending === "\r")
20
+ return text.replace(/\n/g, "\r");
21
+ return text;
22
+ }
23
+ export function stripBOM(content) {
24
+ return content.startsWith("\uFEFF")
25
+ ? { bom: "\uFEFF", text: content.slice(1) }
26
+ : { bom: "", text: content };
27
+ }
28
+ function fmtDiffLine(prefix, line, hash) {
29
+ if (hash === undefined) {
30
+ return `${prefix}${" ".repeat(ANCHOR_LEN)}${HASH_SEP}${line}`;
31
+ }
32
+ return `${prefix}${hash}${HASH_SEP}${line}`;
33
+ }
34
+ const ELLIPSIS_MARKER = Symbol("ellipsis");
35
+ const isEllipsisMarker = (line) => line === ELLIPSIS_MARKER;
36
+ export function genDiff(oldContent, newContent, contextLines = 2, newContentHashes, oldContentHashes) {
37
+ const effectiveNewHashes = newContentHashes ?? _lineHashesPure(newContent);
38
+ const parts = Diff.diffLines(oldContent, newContent);
39
+ const output = [];
40
+ const servedRows = [];
41
+ let newLineNum = 1;
42
+ let oldLineNum = 1;
43
+ let lastWasChange = false;
44
+ let firstChangedLine;
45
+ for (let i = 0; i < parts.length; i++) {
46
+ const part = parts[i];
47
+ const raw = part.value.split("\n");
48
+ if (raw[raw.length - 1] === "")
49
+ raw.pop();
50
+ const displayLines = raw;
51
+ if (part.added || part.removed) {
52
+ if (firstChangedLine === undefined)
53
+ firstChangedLine = newLineNum;
54
+ for (let k = 0; k < displayLines.length; k++) {
55
+ if (part.added) {
56
+ const hash = effectiveNewHashes[newLineNum - 1];
57
+ output.push(fmtDiffLine("+", displayLines[k], hash));
58
+ if (hash !== undefined) {
59
+ servedRows.push({ position: newLineNum - 1, hash });
60
+ }
61
+ newLineNum++;
62
+ }
63
+ else {
64
+ const hash = oldContentHashes?.[oldLineNum - 1];
65
+ output.push(fmtDiffLine("-", displayLines[k], hash));
66
+ oldLineNum++;
67
+ }
68
+ }
69
+ lastWasChange = true;
70
+ continue;
71
+ }
72
+ const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
73
+ if (lastWasChange || nextPartIsChange) {
74
+ let linesToShow = displayLines;
75
+ let skipStart = 0;
76
+ let skipMiddle = 0;
77
+ if (!lastWasChange) {
78
+ skipStart = Math.max(0, displayLines.length - contextLines);
79
+ linesToShow = displayLines.slice(skipStart);
80
+ }
81
+ else if (nextPartIsChange && displayLines.length > contextLines * 2) {
82
+ const tail = displayLines.slice(-contextLines);
83
+ linesToShow = [
84
+ ...displayLines.slice(0, contextLines),
85
+ ELLIPSIS_MARKER,
86
+ ...tail,
87
+ ];
88
+ skipMiddle = displayLines.length - contextLines * 2;
89
+ }
90
+ else if (linesToShow.length > contextLines) {
91
+ linesToShow = linesToShow.slice(0, contextLines);
92
+ }
93
+ if (skipStart > 0) {
94
+ output.push(" ...");
95
+ newLineNum += skipStart;
96
+ oldLineNum += skipStart;
97
+ }
98
+ for (const line of linesToShow) {
99
+ if (isEllipsisMarker(line)) {
100
+ output.push(" ...");
101
+ newLineNum += skipMiddle;
102
+ oldLineNum += skipMiddle;
103
+ continue;
104
+ }
105
+ const hash = effectiveNewHashes[newLineNum - 1];
106
+ output.push(fmtDiffLine(" ", line, hash));
107
+ if (hash !== undefined) {
108
+ servedRows.push({ position: newLineNum - 1, hash });
109
+ }
110
+ newLineNum++;
111
+ oldLineNum++;
112
+ }
113
+ }
114
+ else {
115
+ newLineNum += displayLines.length;
116
+ oldLineNum += displayLines.length;
117
+ }
118
+ lastWasChange = false;
119
+ }
120
+ return { diff: output.join("\n"), firstChangedLine, servedRows };
121
+ }
@@ -0,0 +1,9 @@
1
+ import { isRec, normalizeFilePath } from "./utils.js";
2
+ export function normReq(input) {
3
+ if (!isRec(input)) {
4
+ return input;
5
+ }
6
+ const record = { ...input };
7
+ normalizeFilePath(record);
8
+ return record;
9
+ }