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
@@ -0,0 +1,223 @@
1
+ import { abortIf, splitLines } from "../utils.js";
2
+ import { _lineHashesPure, HASH_SEP } from "./hash.js";
3
+ import { AnchorMismatchError, verifyServedRange, } from "./served.js";
4
+ import { valEdit, stripBarePrefixes, stripDiffPrefixes, swapReversedRanges, warnUnicodeEsc, fmtMismatchWithServes, } from "./resolve.js";
5
+ export function buildIdx(content) {
6
+ const fileLines = splitLines(content);
7
+ const lineStarts = [];
8
+ let offset = 0;
9
+ for (let index = 0; index < fileLines.length; index++) {
10
+ lineStarts.push(offset);
11
+ offset += fileLines[index].length;
12
+ if (index < fileLines.length - 1) {
13
+ offset += 1;
14
+ }
15
+ }
16
+ return {
17
+ fileLines,
18
+ lineStarts,
19
+ };
20
+ }
21
+ function assertNotEmpty(originalContent, result) {
22
+ if (originalContent.length > 0 && result.length === 0) {
23
+ throw new Error("[E_WOULD_EMPTY] Cannot empty a non-empty file via edit. Use `write` if you need to clear the file.");
24
+ }
25
+ }
26
+ function resToSpan(edit, content, lineIndex) {
27
+ const { fileLines, lineStarts } = lineIndex;
28
+ const startLine = edit.hash_bounds[0].line;
29
+ const endLine = edit.hash_bounds[1].line;
30
+ const originalLines = fileLines.slice(startLine - 1, endLine);
31
+ if (originalLines.length === edit.content_lines.length &&
32
+ originalLines.every((line, lineIndex) => line === edit.content_lines[lineIndex])) {
33
+ return {
34
+ kind: "noop",
35
+ loc: edit.hash_bounds[0].hash,
36
+ currentContent: originalLines.join("\n"),
37
+ };
38
+ }
39
+ if (edit.content_lines.length > 0) {
40
+ return {
41
+ kind: "replace",
42
+ start: lineStarts[startLine - 1],
43
+ end: lineStarts[endLine - 1] + fileLines[endLine - 1].length,
44
+ replacement: edit.content_lines.join("\n"),
45
+ };
46
+ }
47
+ if (startLine === 1 && endLine === fileLines.length) {
48
+ return {
49
+ kind: "replace",
50
+ start: 0,
51
+ end: content.length,
52
+ replacement: "",
53
+ };
54
+ }
55
+ if (endLine < fileLines.length) {
56
+ return {
57
+ kind: "replace",
58
+ start: lineStarts[startLine - 1],
59
+ end: lineStarts[endLine],
60
+ replacement: "",
61
+ };
62
+ }
63
+ if (content.endsWith("\n")) {
64
+ return {
65
+ kind: "replace",
66
+ start: lineStarts[startLine - 1],
67
+ end: content.length,
68
+ replacement: "",
69
+ };
70
+ }
71
+ const prevLine = startLine >= 2 ? fileLines[startLine - 2] : undefined;
72
+ return {
73
+ kind: "replace",
74
+ start: prevLine !== undefined && prevLine.length === 0
75
+ ? lineStarts[startLine - 1]
76
+ : Math.max(0, lineStarts[startLine - 1] - 1),
77
+ end: content.length,
78
+ replacement: "",
79
+ };
80
+ }
81
+ function assemble(content, span, signal) {
82
+ abortIf(signal);
83
+ return (content.slice(0, span.start) + span.replacement + content.slice(span.end));
84
+ }
85
+ export function applyEdit(content, edit, signal, precomputedHashes, filePath, served) {
86
+ abortIf(signal);
87
+ const lineIndex = buildIdx(content);
88
+ const fileHashes = precomputedHashes ?? _lineHashesPure(content);
89
+ const warnings = [];
90
+ const rangeFixed = swapReversedRanges(edit, fileHashes, warnings);
91
+ const prefixFixed = stripDiffPrefixes(stripBarePrefixes(rangeFixed, fileHashes, warnings), warnings);
92
+ const { resolved: initialResolved, mismatches, boundaryDups, } = valEdit(prefixFixed, lineIndex.fileLines, fileHashes, warnings, signal);
93
+ if (mismatches.length || !initialResolved) {
94
+ const { message, servedRows } = fmtMismatchWithServes(mismatches, lineIndex.fileLines, fileHashes, filePath);
95
+ throw new AnchorMismatchError(message, servedRows);
96
+ }
97
+ warnUnicodeEsc(prefixFixed, warnings);
98
+ let resolved = initialResolved;
99
+ let autoFixes;
100
+ if (boundaryDups.length > 0) {
101
+ autoFixes = [];
102
+ const correctedEdit = {
103
+ ...prefixFixed,
104
+ content_lines: [...prefixFixed.content_lines],
105
+ };
106
+ const seen = new Set();
107
+ const uniqueDups = [];
108
+ for (const dup of boundaryDups) {
109
+ if (seen.has(dup.replacementLineIndex))
110
+ continue;
111
+ seen.add(dup.replacementLineIndex);
112
+ uniqueDups.push(dup);
113
+ }
114
+ const dupsByIndex = uniqueDups.sort((a, b) => b.replacementLineIndex - a.replacementLineIndex);
115
+ for (const dup of dupsByIndex) {
116
+ const idx = dup.replacementLineIndex;
117
+ if (idx < 0 || idx >= correctedEdit.content_lines.length)
118
+ continue;
119
+ const removed = correctedEdit.content_lines.splice(idx, 1)[0];
120
+ autoFixes.push({
121
+ kind: dup.kind,
122
+ removedLine: removed,
123
+ removedLineIndex: idx,
124
+ });
125
+ }
126
+ const correctedResult = valEdit(correctedEdit, lineIndex.fileLines, fileHashes, warnings, signal);
127
+ if (correctedResult.mismatches.length || !correctedResult.resolved) {
128
+ const { message, servedRows } = fmtMismatchWithServes(correctedResult.mismatches, lineIndex.fileLines, fileHashes, filePath);
129
+ throw new AnchorMismatchError(message, servedRows);
130
+ }
131
+ resolved = correctedResult.resolved;
132
+ }
133
+ if (served) {
134
+ const startAnchor = resolved.hash_bounds[0];
135
+ const endAnchor = resolved.hash_bounds[1];
136
+ verifyServedRange({
137
+ served,
138
+ startHash: startAnchor.hash,
139
+ endHash: endAnchor.hash,
140
+ startLine: startAnchor.line,
141
+ endLine: endAnchor.line,
142
+ fileHashes,
143
+ fileLines: lineIndex.fileLines,
144
+ filePath,
145
+ });
146
+ }
147
+ const spanResult = resToSpan(resolved, content, lineIndex);
148
+ if (spanResult.kind === "noop") {
149
+ return {
150
+ content,
151
+ firstChangedLine: undefined,
152
+ lastChangedLine: undefined,
153
+ range: resolvedRange(resolved),
154
+ ...(warnings.length ? { warnings } : {}),
155
+ noopEdit: {
156
+ loc: spanResult.loc,
157
+ currentContent: spanResult.currentContent,
158
+ },
159
+ };
160
+ }
161
+ const result = assemble(content, spanResult, signal);
162
+ assertNotEmpty(content, result);
163
+ const changed = changedRange(content, result);
164
+ return {
165
+ content: result,
166
+ firstChangedLine: changed?.firstChangedLine,
167
+ lastChangedLine: changed?.lastChangedLine,
168
+ range: resolvedRange(resolved),
169
+ ...(warnings.length ? { warnings } : {}),
170
+ ...(autoFixes ? { autoFixes } : {}),
171
+ };
172
+ }
173
+ function resolvedRange(resolved) {
174
+ const [start, end] = resolved.hash_bounds;
175
+ return {
176
+ startLine: start.line,
177
+ endLine: end.line,
178
+ startHash: start.hash,
179
+ endHash: end.hash,
180
+ delta: resolved.content_lines.length - (Math.abs(end.line - start.line) + 1),
181
+ };
182
+ }
183
+ export function fmtRegion(hashes, lines) {
184
+ if (hashes.length !== lines.length) {
185
+ throw new Error(`fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`);
186
+ }
187
+ return lines
188
+ .map((line, index) => `${hashes[index]}${HASH_SEP}${line}`)
189
+ .join("\n");
190
+ }
191
+ export function changedRange(original, result) {
192
+ if (original === result)
193
+ return null;
194
+ if (original.length === 0) {
195
+ return {
196
+ firstChangedLine: 1,
197
+ lastChangedLine: splitLines(result).length,
198
+ };
199
+ }
200
+ const originalLines = splitLines(original);
201
+ const resultLines = splitLines(result);
202
+ if (originalLines.length === resultLines.length &&
203
+ originalLines.every((line, index) => line === resultLines[index])) {
204
+ return null;
205
+ }
206
+ const minLen = Math.min(originalLines.length, resultLines.length);
207
+ let first = 0;
208
+ while (first < minLen && originalLines[first] === resultLines[first]) {
209
+ first++;
210
+ }
211
+ let lastOrig = originalLines.length - 1;
212
+ let lastRes = resultLines.length - 1;
213
+ while (lastOrig >= first &&
214
+ lastRes >= first &&
215
+ originalLines[lastOrig] === resultLines[lastRes]) {
216
+ lastOrig--;
217
+ lastRes--;
218
+ }
219
+ return {
220
+ firstChangedLine: first + 1,
221
+ lastChangedLine: Math.max(first, lastRes) + 1,
222
+ };
223
+ }
@@ -0,0 +1,241 @@
1
+ import { splitLines } from "../utils.js";
2
+ import { loadHashStore, getSnapshot, upsertSnapshot, } from "../hash-store.js";
3
+ import { xxh32, contentChecksum, initHasher } from "./hasher.js";
4
+ import { HASH_LEN, ALPH, ALPH_RE, HASH_CLASS } from "./alphabet.js";
5
+ export { initHasher, HASH_LEN, ALPH_RE, HASH_CLASS };
6
+ export const ANCHOR_LEN = HASH_LEN;
7
+ export const HASH_SEP = "│";
8
+ export const HASH_SPACE = ALPH.length ** HASH_LEN;
9
+ export const MAX_HASH_LINES = HASH_SPACE;
10
+ export const HASH_PROBE_STRIDE = ALPH.length ** 2 + ALPH.length + 1;
11
+ function idxToHash(idx) {
12
+ let out = "";
13
+ for (let j = 0; j < HASH_LEN; j++) {
14
+ out = ALPH[idx % ALPH.length] + out;
15
+ idx = Math.floor(idx / ALPH.length);
16
+ }
17
+ return out;
18
+ }
19
+ const hashCache = new Map();
20
+ function hashAt(idx) {
21
+ let hash = hashCache.get(idx);
22
+ if (hash === undefined) {
23
+ hash = idxToHash(idx);
24
+ hashCache.set(idx, hash);
25
+ }
26
+ return hash;
27
+ }
28
+ export const HL_PREFIX_PLUS_RE = new RegExp(`^\\+${HASH_CLASS}│`);
29
+ export const HL_PREFIX_MINUS_RE = new RegExp(`^-(?:${HASH_CLASS}│| {${ANCHOR_LEN}}│)`);
30
+ export const HL_BARE_PREFIX_RE = new RegExp(`^\\s*(${HASH_CLASS})│`);
31
+ export function canon(line) {
32
+ return line.replace(/\r/g, "").trimEnd();
33
+ }
34
+ const BITSET_WORDS = Math.ceil(HASH_SPACE / 32);
35
+ function getBit(bits, idx) {
36
+ return (bits[idx >>> 5] >>> (idx & 31) & 1) !== 0;
37
+ }
38
+ function setBit(bits, idx) {
39
+ bits[idx >>> 5] |= 1 << (idx & 31);
40
+ }
41
+ function nextZeroBit(bits, start) {
42
+ const totalBits = HASH_SPACE;
43
+ let idx = start % totalBits;
44
+ for (let i = 0; i < totalBits; i++) {
45
+ if (!getBit(bits, idx))
46
+ return idx;
47
+ idx += HASH_PROBE_STRIDE;
48
+ if (idx >= totalBits)
49
+ idx -= totalBits;
50
+ }
51
+ throw new Error(`[E_FILE_TOO_LARGE] Cannot allocate a unique hash anchor: the file exceeds the ${HASH_SPACE}-line limit for ${HASH_LEN}-char hashline anchors. For very large files use write or a non-line-based approach.`);
52
+ }
53
+ function assignHash(used, baseIdx, hint) {
54
+ if (!getBit(used, baseIdx)) {
55
+ setBit(used, baseIdx);
56
+ hint.value = baseIdx + HASH_PROBE_STRIDE;
57
+ return hashAt(baseIdx);
58
+ }
59
+ const nextIdx = nextZeroBit(used, hint.value);
60
+ setBit(used, nextIdx);
61
+ hint.value = nextIdx + HASH_PROBE_STRIDE;
62
+ return hashAt(nextIdx);
63
+ }
64
+ export function _lineHashesPure(content) {
65
+ const lines = splitLines(content);
66
+ const hashes = new Array(lines.length);
67
+ const used = new Uint32Array(BITSET_WORDS);
68
+ const hint = { value: 0 };
69
+ for (let i = 0; i < lines.length; i++) {
70
+ const c = canon(lines[i]);
71
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
72
+ hashes[i] = assignHash(used, baseIdx, hint);
73
+ }
74
+ return hashes;
75
+ }
76
+ export async function lineHashes(content, path, previous, store, persist) {
77
+ await initHasher();
78
+ if (!path) {
79
+ return _lineHashesPure(content);
80
+ }
81
+ const hashStore = store ?? await loadHashStore();
82
+ if (previous) {
83
+ const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes);
84
+ if (persist !== false) {
85
+ try {
86
+ upsertSnapshot(hashStore, path, contentChecksum(content), splitLines(content).length, newHashes);
87
+ }
88
+ catch (error) {
89
+ console.error("Failed to persist hash snapshot:", error);
90
+ }
91
+ }
92
+ return newHashes;
93
+ }
94
+ let cached;
95
+ try {
96
+ cached = getSnapshot(hashStore, path, content, persist !== false);
97
+ }
98
+ catch (error) {
99
+ console.error("Failed to read hash store snapshot:", error);
100
+ }
101
+ if (cached) {
102
+ return cached;
103
+ }
104
+ const newHashes = _lineHashesPure(content);
105
+ if (persist !== false) {
106
+ try {
107
+ upsertSnapshot(hashStore, path, contentChecksum(content), splitLines(content).length, newHashes);
108
+ }
109
+ catch (error) {
110
+ console.error("Failed to persist hash snapshot:", error);
111
+ }
112
+ }
113
+ return newHashes;
114
+ }
115
+ function hashToIndex(hash) {
116
+ let idx = 0;
117
+ for (let j = 0; j < HASH_LEN; j++) {
118
+ const charIdx = ALPH.indexOf(hash[j]);
119
+ if (charIdx < 0)
120
+ return -1;
121
+ idx = idx * ALPH.length + charIdx;
122
+ }
123
+ return idx;
124
+ }
125
+ function nearestNew(candidates, target) {
126
+ let lo = 0;
127
+ let hi = candidates.length;
128
+ while (lo < hi) {
129
+ const mid = (lo + hi) >>> 1;
130
+ if (candidates[mid] < target)
131
+ lo = mid + 1;
132
+ else
133
+ hi = mid;
134
+ }
135
+ const left = lo - 1;
136
+ const right = lo;
137
+ if (left >= 0 &&
138
+ (right >= candidates.length ||
139
+ target - candidates[left] <= candidates[right] - target)) {
140
+ return left;
141
+ }
142
+ return right < candidates.length ? right : -1;
143
+ }
144
+ function mapStableHashes(oldContent, oldHashes, newContent, removedHashes) {
145
+ const oldLines = splitLines(oldContent);
146
+ const newLines = splitLines(newContent);
147
+ const newHashes = new Array(newLines.length);
148
+ const used = new Uint32Array(BITSET_WORDS);
149
+ const hint = { value: 0 };
150
+ const removed = removedHashes ?? new Set();
151
+ const oldHashIndex = new Map();
152
+ for (let i = 0; i < oldHashes.length; i++) {
153
+ const hash = oldHashes[i];
154
+ oldHashIndex.set(hash, i);
155
+ const idx = hashToIndex(hash);
156
+ if (idx >= 0)
157
+ setBit(used, idx);
158
+ }
159
+ const removedIndexes = new Set();
160
+ for (const hash of removed) {
161
+ const idx = oldHashIndex.get(hash);
162
+ if (idx !== undefined)
163
+ removedIndexes.add(idx);
164
+ }
165
+ let spanStart = oldLines.length;
166
+ let spanEnd = -1;
167
+ for (const idx of removedIndexes) {
168
+ if (idx < spanStart)
169
+ spanStart = idx;
170
+ if (idx > spanEnd)
171
+ spanEnd = idx;
172
+ }
173
+ const spanLen = spanEnd >= spanStart ? spanEnd - spanStart + 1 : 0;
174
+ const replacementLen = newLines.length - oldLines.length + spanLen;
175
+ const shiftAfterSpan = spanEnd >= spanStart ? replacementLen - spanLen : 0;
176
+ const survivors = [];
177
+ const removedEntries = [];
178
+ for (let i = 0; i < oldLines.length; i++) {
179
+ const entry = { index: i, hash: oldHashes[i] };
180
+ if (removedIndexes.has(i))
181
+ removedEntries.push(entry);
182
+ else
183
+ survivors.push(entry);
184
+ }
185
+ const newByContent = new Map();
186
+ for (let i = 0; i < newLines.length; i++) {
187
+ const key = canon(newLines[i]);
188
+ const list = newByContent.get(key);
189
+ if (list)
190
+ list.push(i);
191
+ else
192
+ newByContent.set(key, [i]);
193
+ }
194
+ const markUsed = (hash) => {
195
+ const idx = hashToIndex(hash);
196
+ if (idx >= 0) {
197
+ setBit(used, idx);
198
+ if (idx + HASH_PROBE_STRIDE > hint.value)
199
+ hint.value = idx + HASH_PROBE_STRIDE;
200
+ }
201
+ };
202
+ for (const entry of survivors) {
203
+ const candidates = newByContent.get(canon(oldLines[entry.index]));
204
+ if (!candidates || candidates.length === 0)
205
+ continue;
206
+ const target = entry.index > spanEnd ? entry.index + shiftAfterSpan : entry.index;
207
+ const pos = nearestNew(candidates, target);
208
+ if (pos < 0)
209
+ continue;
210
+ const newIdx = candidates.splice(pos, 1)[0];
211
+ newHashes[newIdx] = entry.hash;
212
+ markUsed(entry.hash);
213
+ }
214
+ const removedByContent = new Map();
215
+ for (const entry of removedEntries) {
216
+ const key = canon(oldLines[entry.index]);
217
+ let queue = removedByContent.get(key);
218
+ if (!queue) {
219
+ queue = { hashes: [], pos: 0 };
220
+ removedByContent.set(key, queue);
221
+ }
222
+ queue.hashes.push(entry.hash);
223
+ }
224
+ for (let i = 0; i < newLines.length; i++) {
225
+ if (newHashes[i])
226
+ continue;
227
+ const queue = removedByContent.get(canon(newLines[i]));
228
+ if (!queue || queue.pos >= queue.hashes.length)
229
+ continue;
230
+ newHashes[i] = queue.hashes[queue.pos];
231
+ queue.pos += 1;
232
+ }
233
+ for (let i = 0; i < newLines.length; i++) {
234
+ if (newHashes[i])
235
+ continue;
236
+ const c = canon(newLines[i]);
237
+ const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
238
+ newHashes[i] = assignHash(used, baseIdx, hint);
239
+ }
240
+ return newHashes;
241
+ }
@@ -0,0 +1,23 @@
1
+ import xxhash from "xxhash-wasm";
2
+ let hasher = null;
3
+ export function getH() {
4
+ if (hasher)
5
+ return hasher;
6
+ throw new Error("xxhash-wasm hasher not initialized; await initHasher() before calling hashline APIs.");
7
+ }
8
+ const hasherP = xxhash().then((h) => {
9
+ hasher = h;
10
+ return hasher;
11
+ }).catch((err) => {
12
+ console.error("xxhash-wasm initialization failed:", err);
13
+ throw err;
14
+ });
15
+ export function initHasher() {
16
+ return hasherP;
17
+ }
18
+ export function xxh32(input, seed = 0) {
19
+ return getH().h32(input, seed) >>> 0;
20
+ }
21
+ export function contentChecksum(content) {
22
+ return getH().h64ToString(content);
23
+ }
@@ -0,0 +1,4 @@
1
+ export { HASH_LEN, ANCHOR_LEN, HASH_SEP, HASH_CLASS, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, lineHashes, _lineHashesPure, initHasher, canon, } from "./hash.js";
2
+ export { parseHashRef, parseText, } from "./parse.js";
3
+ export { resEdit, valEdit, stripBarePrefixes, stripDiffPrefixes, swapReversedRanges, fmtMismatch, findNewEdge, } from "./resolve.js";
4
+ export { buildIdx, applyEdit, fmtRegion, changedRange, } from "./apply.js";
@@ -0,0 +1,35 @@
1
+ import { ANCHOR_LEN, ALPH_RE, } from "./hash.js";
2
+ import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
3
+ function diagRef(ref) {
4
+ const trimmed = ref.trim();
5
+ if (!trimmed.length) {
6
+ return `[E_BAD_REF] Invalid anchor. Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
7
+ }
8
+ if (/^\d+/.test(trimmed)) {
9
+ return `[E_BAD_REF] Invalid anchor. Use the hash alone (e.g. "aB3") — no line numbers or trailing content.`;
10
+ }
11
+ if (trimmed.includes("│")) {
12
+ return `[E_BAD_REF] Invalid anchor "${trimmed}". remove_from and remove_to must contain the 3-char hash only — remove everything from "│" onward.`;
13
+ }
14
+ return `[E_BAD_REF] Invalid anchor "${trimmed}". Expected a 3-char alphanumeric anchor (e.g. "aB3").`;
15
+ }
16
+ function parseRef(ref) {
17
+ const trimmed = ref.trim();
18
+ if (trimmed.length === ANCHOR_LEN &&
19
+ ALPH_RE.test(trimmed)) {
20
+ return { hash: trimmed };
21
+ }
22
+ throw new Error(diagRef(ref));
23
+ }
24
+ export const parseHashRef = parseRef;
25
+ export function parseText(edit) {
26
+ if (typeof edit !== "string") {
27
+ throw new Error(NEW_CONTENT_NOT_STRING_MSG);
28
+ }
29
+ const normalized = edit.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
30
+ if (normalized === "")
31
+ return [];
32
+ if (/^\n+$/.test(normalized))
33
+ return new Array(normalized.length).fill("");
34
+ return normalized.split("\n");
35
+ }