@better-fs-tools/write 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +442 -2
- package/dist/authorize/ask-before-write.d.ts +11 -0
- package/dist/authorize/ask-before-write.js +49 -0
- package/dist/authorize/index.d.ts +3 -0
- package/dist/authorize/index.js +3 -0
- package/dist/authorize/protect-paths.d.ts +12 -0
- package/dist/authorize/protect-paths.js +74 -0
- package/dist/authorize/write-authorizers.d.ts +9 -0
- package/dist/authorize/write-authorizers.js +48 -0
- package/dist/bundle/create-fs-tools.d.ts +71 -0
- package/dist/bundle/create-fs-tools.js +125 -0
- package/dist/codecs/index.d.ts +1 -0
- package/dist/codecs/index.js +1 -0
- package/dist/codecs/utf8.d.ts +7 -0
- package/dist/codecs/utf8.js +61 -0
- package/dist/contract/codec.d.ts +26 -0
- package/dist/contract/codec.js +0 -0
- package/dist/contract/context.d.ts +14 -0
- package/dist/contract/context.js +0 -0
- package/dist/contract/deps.d.ts +55 -0
- package/dist/contract/deps.js +0 -0
- package/dist/contract/extensions.d.ts +103 -0
- package/dist/contract/extensions.js +0 -0
- package/dist/contract/format.d.ts +15 -0
- package/dist/contract/format.js +0 -0
- package/dist/contract/input.d.ts +35 -0
- package/dist/contract/input.js +0 -0
- package/dist/contract/limits.d.ts +26 -0
- package/dist/contract/limits.js +0 -0
- package/dist/contract/locks.d.ts +14 -0
- package/dist/contract/locks.js +0 -0
- package/dist/contract/matcher.d.ts +30 -0
- package/dist/contract/matcher.js +0 -0
- package/dist/contract/messages.d.ts +211 -0
- package/dist/contract/messages.js +0 -0
- package/dist/contract/patch.d.ts +50 -0
- package/dist/contract/patch.js +0 -0
- package/dist/contract/preconditions.d.ts +9 -0
- package/dist/contract/preconditions.js +5 -0
- package/dist/contract/result.d.ts +102 -0
- package/dist/contract/result.js +0 -0
- package/dist/core/abort.d.ts +4 -0
- package/dist/core/abort.js +23 -0
- package/dist/core/authorize.d.ts +9 -0
- package/dist/core/authorize.js +87 -0
- package/dist/core/bytes.d.ts +3 -0
- package/dist/core/bytes.js +14 -0
- package/dist/core/commit-patch.d.ts +20 -0
- package/dist/core/commit-patch.js +224 -0
- package/dist/core/commit.d.ts +9 -0
- package/dist/core/commit.js +111 -0
- package/dist/core/create-tools.d.ts +23 -0
- package/dist/core/create-tools.js +54 -0
- package/dist/core/deps.d.ts +11 -0
- package/dist/core/deps.js +207 -0
- package/dist/core/diff.d.ts +10 -0
- package/dist/core/diff.js +221 -0
- package/dist/core/encode.d.ts +3 -0
- package/dist/core/encode.js +26 -0
- package/dist/core/extension-error.d.ts +8 -0
- package/dist/core/extension-error.js +17 -0
- package/dist/core/format.d.ts +4 -0
- package/dist/core/format.js +36 -0
- package/dist/core/guards.d.ts +3 -0
- package/dist/core/guards.js +45 -0
- package/dist/core/hints.d.ts +14 -0
- package/dist/core/hints.js +75 -0
- package/dist/core/hooks.d.ts +15 -0
- package/dist/core/hooks.js +115 -0
- package/dist/core/input.d.ts +20 -0
- package/dist/core/input.js +91 -0
- package/dist/core/limits.d.ts +10 -0
- package/dist/core/limits.js +48 -0
- package/dist/core/line-index.d.ts +10 -0
- package/dist/core/line-index.js +38 -0
- package/dist/core/load.d.ts +14 -0
- package/dist/core/load.js +221 -0
- package/dist/core/lock.d.ts +2 -0
- package/dist/core/lock.js +56 -0
- package/dist/core/match.d.ts +15 -0
- package/dist/core/match.js +66 -0
- package/dist/core/messages.d.ts +8 -0
- package/dist/core/messages.js +147 -0
- package/dist/core/outcomes.d.ts +21 -0
- package/dist/core/outcomes.js +127 -0
- package/dist/core/parse-patch.d.ts +3 -0
- package/dist/core/parse-patch.js +64 -0
- package/dist/core/patch-hunks.d.ts +25 -0
- package/dist/core/patch-hunks.js +177 -0
- package/dist/core/patch-pipeline.d.ts +4 -0
- package/dist/core/patch-pipeline.js +285 -0
- package/dist/core/pipeline.d.ts +22 -0
- package/dist/core/pipeline.js +153 -0
- package/dist/core/plan-edit.d.ts +13 -0
- package/dist/core/plan-edit.js +215 -0
- package/dist/core/plan-patch.d.ts +29 -0
- package/dist/core/plan-patch.js +169 -0
- package/dist/core/plan-write.d.ts +6 -0
- package/dist/core/plan-write.js +27 -0
- package/dist/core/planned.d.ts +35 -0
- package/dist/core/planned.js +36 -0
- package/dist/core/precondition.d.ts +10 -0
- package/dist/core/precondition.js +76 -0
- package/dist/core/record.d.ts +3 -0
- package/dist/core/record.js +58 -0
- package/dist/core/resolve.d.ts +3 -0
- package/dist/core/resolve.js +65 -0
- package/dist/core/scope.d.ts +33 -0
- package/dist/core/scope.js +109 -0
- package/dist/core/snippet.d.ts +4 -0
- package/dist/core/snippet.js +36 -0
- package/dist/core/splice.d.ts +10 -0
- package/dist/core/splice.js +19 -0
- package/dist/core/target.d.ts +10 -0
- package/dist/core/target.js +46 -0
- package/dist/formatters/default.d.ts +16 -0
- package/dist/formatters/default.js +122 -0
- package/dist/formatters/index.d.ts +2 -0
- package/dist/formatters/index.js +1 -0
- package/dist/guards/generated-file.d.ts +10 -0
- package/dist/guards/generated-file.js +39 -0
- package/dist/guards/index.d.ts +13 -0
- package/dist/guards/index.js +25 -0
- package/dist/guards/non-text.d.ts +3 -0
- package/dist/guards/non-text.js +46 -0
- package/dist/guards/omission.d.ts +9 -0
- package/dist/guards/omission.js +48 -0
- package/dist/guards/read-prefix.d.ts +12 -0
- package/dist/guards/read-prefix.js +87 -0
- package/dist/guards/shared.d.ts +11 -0
- package/dist/guards/shared.js +46 -0
- package/dist/guards/syntax.d.ts +10 -0
- package/dist/guards/syntax.js +54 -0
- package/dist/guards/truncation-notice.d.ts +8 -0
- package/dist/guards/truncation-notice.js +32 -0
- package/dist/hooks/executable-shebang.d.ts +9 -0
- package/dist/hooks/executable-shebang.js +46 -0
- package/dist/hooks/index.d.ts +2 -0
- package/dist/hooks/index.js +2 -0
- package/dist/hooks/verify-write.d.ts +9 -0
- package/dist/hooks/verify-write.js +63 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +15 -0
- package/dist/locks/index.d.ts +1 -0
- package/dist/locks/index.js +1 -0
- package/dist/locks/memory-locks.d.ts +9 -0
- package/dist/locks/memory-locks.js +94 -0
- package/dist/matchers/block-anchor.d.ts +9 -0
- package/dist/matchers/block-anchor.js +69 -0
- package/dist/matchers/escape.d.ts +6 -0
- package/dist/matchers/escape.js +32 -0
- package/dist/matchers/exact.d.ts +4 -0
- package/dist/matchers/exact.js +29 -0
- package/dist/matchers/fold.d.ts +11 -0
- package/dist/matchers/fold.js +144 -0
- package/dist/matchers/indentation.d.ts +3 -0
- package/dist/matchers/indentation.js +81 -0
- package/dist/matchers/index.d.ts +11 -0
- package/dist/matchers/index.js +18 -0
- package/dist/matchers/line-trimmed.d.ts +3 -0
- package/dist/matchers/line-trimmed.js +32 -0
- package/dist/matchers/lines.d.ts +24 -0
- package/dist/matchers/lines.js +74 -0
- package/dist/matchers/normalized.d.ts +7 -0
- package/dist/matchers/normalized.js +69 -0
- package/dist/patch/grammar.d.ts +5 -0
- package/dist/patch/grammar.js +24 -0
- package/dist/patch/index.d.ts +4 -0
- package/dist/patch/index.js +3 -0
- package/dist/patch/parse.d.ts +11 -0
- package/dist/patch/parse.js +209 -0
- package/dist/signature/contract.d.ts +8 -0
- package/dist/signature/contract.js +0 -0
- package/dist/signature/edit.d.ts +19 -0
- package/dist/signature/edit.js +158 -0
- package/dist/signature/index.d.ts +6 -0
- package/dist/signature/index.js +4 -0
- package/dist/signature/matching.d.ts +3 -0
- package/dist/signature/matching.js +25 -0
- package/dist/signature/messages.d.ts +4 -0
- package/dist/signature/messages.js +9 -0
- package/dist/signature/patch.d.ts +6 -0
- package/dist/signature/patch.js +55 -0
- package/dist/signature/schema.d.ts +19 -0
- package/dist/signature/schema.js +117 -0
- package/dist/signature/write.d.ts +9 -0
- package/dist/signature/write.js +52 -0
- package/dist/state/index.d.ts +2 -0
- package/dist/state/index.js +1 -0
- package/dist/state/invalidate.d.ts +29 -0
- package/dist/state/invalidate.js +37 -0
- package/docs/architecture.md +221 -0
- package/docs/hosts.md +95 -0
- package/docs/result-schema.md +268 -0
- package/package.json +54 -4
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
const CONTEXT_LINES = 3;
|
|
2
|
+
const MAX_MYERS_WORK = 20_000_000;
|
|
3
|
+
const MAX_EDIT_DISTANCE = 1_000;
|
|
4
|
+
export function unifiedDiff(before, after, path, maxLines, beforePath = path) {
|
|
5
|
+
const a = tokens(before ?? "");
|
|
6
|
+
const b = tokens(after ?? "");
|
|
7
|
+
const ops = editScript(a, b);
|
|
8
|
+
let linesAdded = 0;
|
|
9
|
+
let linesRemoved = 0;
|
|
10
|
+
for (const op of ops) {
|
|
11
|
+
if (op.kind === "+")
|
|
12
|
+
linesAdded += 1;
|
|
13
|
+
else if (op.kind === "-")
|
|
14
|
+
linesRemoved += 1;
|
|
15
|
+
}
|
|
16
|
+
if (linesAdded === 0 && linesRemoved === 0) {
|
|
17
|
+
return { linesAdded, linesRemoved, text: "", truncated: false, changed: [] };
|
|
18
|
+
}
|
|
19
|
+
const name = path.replace(/^\/+/u, "");
|
|
20
|
+
const out = new Output(maxLines);
|
|
21
|
+
out.push(before === null ? "--- /dev/null" : `--- a/${beforePath.replace(/^\/+/u, "")}`);
|
|
22
|
+
out.push(after === null ? "+++ /dev/null" : `+++ b/${name}`);
|
|
23
|
+
for (const hunk of hunks(ops)) {
|
|
24
|
+
if (out.full)
|
|
25
|
+
break;
|
|
26
|
+
out.push(hunk.header);
|
|
27
|
+
for (const op of hunk.ops) {
|
|
28
|
+
if (out.full)
|
|
29
|
+
break;
|
|
30
|
+
const newline = op.token.endsWith("\n");
|
|
31
|
+
out.push(`${op.kind}${newline ? op.token.slice(0, -1) : op.token}`);
|
|
32
|
+
if (!newline)
|
|
33
|
+
out.push("\");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
linesAdded,
|
|
38
|
+
linesRemoved,
|
|
39
|
+
text: out.text(),
|
|
40
|
+
truncated: out.truncated,
|
|
41
|
+
changed: changedRuns(ops),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function changedRuns(ops) {
|
|
45
|
+
const runs = [];
|
|
46
|
+
let line = 0;
|
|
47
|
+
let index = 0;
|
|
48
|
+
while (index < ops.length) {
|
|
49
|
+
if (ops[index].kind === " ") {
|
|
50
|
+
line += 1;
|
|
51
|
+
index += 1;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const first = line + 1;
|
|
55
|
+
let added = 0;
|
|
56
|
+
while (index < ops.length && ops[index].kind !== " ") {
|
|
57
|
+
if (ops[index].kind === "+")
|
|
58
|
+
added += 1;
|
|
59
|
+
index += 1;
|
|
60
|
+
}
|
|
61
|
+
line += added;
|
|
62
|
+
runs.push([first, Math.max(first, line)]);
|
|
63
|
+
}
|
|
64
|
+
return runs;
|
|
65
|
+
}
|
|
66
|
+
export function tokens(text) {
|
|
67
|
+
if (text === "")
|
|
68
|
+
return [];
|
|
69
|
+
const parts = text.split("\n");
|
|
70
|
+
const last = parts.pop() ?? "";
|
|
71
|
+
const lines = parts.map((part) => `${part}\n`);
|
|
72
|
+
if (last !== "")
|
|
73
|
+
lines.push(last);
|
|
74
|
+
return lines;
|
|
75
|
+
}
|
|
76
|
+
class Output {
|
|
77
|
+
max;
|
|
78
|
+
lines = [];
|
|
79
|
+
truncated = false;
|
|
80
|
+
constructor(max) {
|
|
81
|
+
this.max = max;
|
|
82
|
+
}
|
|
83
|
+
get full() {
|
|
84
|
+
return this.truncated;
|
|
85
|
+
}
|
|
86
|
+
push(line) {
|
|
87
|
+
if (this.lines.length >= this.max) {
|
|
88
|
+
this.truncated = true;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
this.lines.push(line);
|
|
92
|
+
}
|
|
93
|
+
text() {
|
|
94
|
+
return this.lines.length === 0 ? "" : `${this.lines.join("\n")}\n`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function editScript(a, b) {
|
|
98
|
+
let head = 0;
|
|
99
|
+
while (head < a.length && head < b.length && a[head] === b[head])
|
|
100
|
+
head += 1;
|
|
101
|
+
let tail = 0;
|
|
102
|
+
while (tail < a.length - head &&
|
|
103
|
+
tail < b.length - head &&
|
|
104
|
+
a[a.length - 1 - tail] === b[b.length - 1 - tail]) {
|
|
105
|
+
tail += 1;
|
|
106
|
+
}
|
|
107
|
+
const middleA = a.slice(head, a.length - tail);
|
|
108
|
+
const middleB = b.slice(head, b.length - tail);
|
|
109
|
+
const ops = a.slice(0, head).map((token) => ({ kind: " ", token }));
|
|
110
|
+
ops.push(...(myers(middleA, middleB) ?? replaceAll(middleA, middleB)));
|
|
111
|
+
for (const token of a.slice(a.length - tail))
|
|
112
|
+
ops.push({ kind: " ", token });
|
|
113
|
+
return ops;
|
|
114
|
+
}
|
|
115
|
+
function replaceAll(a, b) {
|
|
116
|
+
return [
|
|
117
|
+
...a.map((token) => ({ kind: "-", token })),
|
|
118
|
+
...b.map((token) => ({ kind: "+", token })),
|
|
119
|
+
];
|
|
120
|
+
}
|
|
121
|
+
function myers(a, b) {
|
|
122
|
+
const n = a.length;
|
|
123
|
+
const m = b.length;
|
|
124
|
+
if (n === 0 || m === 0)
|
|
125
|
+
return replaceAll(a, b);
|
|
126
|
+
const max = Math.min(n + m, MAX_EDIT_DISTANCE, Math.max(1, Math.floor(MAX_MYERS_WORK / (n + m))));
|
|
127
|
+
const offset = max + 1;
|
|
128
|
+
const v = new Int32Array(2 * max + 3);
|
|
129
|
+
const trace = [];
|
|
130
|
+
for (let d = 0; d <= max; d += 1) {
|
|
131
|
+
trace.push(v.slice(offset - d - 1, offset + d + 2));
|
|
132
|
+
for (let k = -d; k <= d; k += 2) {
|
|
133
|
+
let x = k === -d || (k !== d && (v[offset + k - 1] ?? 0) < (v[offset + k + 1] ?? 0))
|
|
134
|
+
? (v[offset + k + 1] ?? 0)
|
|
135
|
+
: (v[offset + k - 1] ?? 0) + 1;
|
|
136
|
+
let y = x - k;
|
|
137
|
+
while (x < n && y < m && a[x] === b[y]) {
|
|
138
|
+
x += 1;
|
|
139
|
+
y += 1;
|
|
140
|
+
}
|
|
141
|
+
v[offset + k] = x;
|
|
142
|
+
if (x >= n && y >= m)
|
|
143
|
+
return backtrack(a, b, trace, d);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
// Row d of the trace holds v[k] for k in -d-1..d+1.
|
|
149
|
+
function backtrack(a, b, trace, distance) {
|
|
150
|
+
const ops = [];
|
|
151
|
+
let x = a.length;
|
|
152
|
+
let y = b.length;
|
|
153
|
+
for (let d = distance; d > 0; d -= 1) {
|
|
154
|
+
const row = trace[d];
|
|
155
|
+
const at = (k) => row[k + d + 1] ?? 0;
|
|
156
|
+
const k = x - y;
|
|
157
|
+
const down = k === -d || (k !== d && at(k - 1) < at(k + 1));
|
|
158
|
+
const prevK = down ? k + 1 : k - 1;
|
|
159
|
+
const prevX = at(prevK);
|
|
160
|
+
const prevY = prevX - prevK;
|
|
161
|
+
while (x > prevX && y > prevY) {
|
|
162
|
+
x -= 1;
|
|
163
|
+
y -= 1;
|
|
164
|
+
ops.push({ kind: " ", token: a[x] });
|
|
165
|
+
}
|
|
166
|
+
if (down) {
|
|
167
|
+
y -= 1;
|
|
168
|
+
ops.push({ kind: "+", token: b[y] });
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
x -= 1;
|
|
172
|
+
ops.push({ kind: "-", token: a[x] });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
while (x > 0 && y > 0) {
|
|
176
|
+
x -= 1;
|
|
177
|
+
y -= 1;
|
|
178
|
+
ops.push({ kind: " ", token: a[x] });
|
|
179
|
+
}
|
|
180
|
+
return ops.reverse();
|
|
181
|
+
}
|
|
182
|
+
function hunks(ops) {
|
|
183
|
+
const changed = [];
|
|
184
|
+
ops.forEach((op, index) => {
|
|
185
|
+
if (op.kind !== " ")
|
|
186
|
+
changed.push(index);
|
|
187
|
+
});
|
|
188
|
+
const result = [];
|
|
189
|
+
let start = 0;
|
|
190
|
+
while (start < changed.length) {
|
|
191
|
+
let end = start;
|
|
192
|
+
while (end + 1 < changed.length &&
|
|
193
|
+
changed[end + 1] - changed[end] <= 2 * CONTEXT_LINES + 1) {
|
|
194
|
+
end += 1;
|
|
195
|
+
}
|
|
196
|
+
const from = Math.max(0, changed[start] - CONTEXT_LINES);
|
|
197
|
+
const to = Math.min(ops.length, changed[end] + CONTEXT_LINES + 1);
|
|
198
|
+
result.push(hunk(ops, from, to));
|
|
199
|
+
start = end + 1;
|
|
200
|
+
}
|
|
201
|
+
return result;
|
|
202
|
+
}
|
|
203
|
+
function hunk(ops, from, to) {
|
|
204
|
+
let oldLine = 0;
|
|
205
|
+
let newLine = 0;
|
|
206
|
+
for (let index = 0; index < from; index += 1) {
|
|
207
|
+
const op = ops[index];
|
|
208
|
+
if (op.kind !== "+")
|
|
209
|
+
oldLine += 1;
|
|
210
|
+
if (op.kind !== "-")
|
|
211
|
+
newLine += 1;
|
|
212
|
+
}
|
|
213
|
+
const slice = ops.slice(from, to);
|
|
214
|
+
const oldCount = slice.filter((op) => op.kind !== "+").length;
|
|
215
|
+
const newCount = slice.filter((op) => op.kind !== "-").length;
|
|
216
|
+
const range = (line, count) => `${count === 0 ? line : line + 1}${count === 1 ? "" : `,${count}`}`;
|
|
217
|
+
return {
|
|
218
|
+
header: `@@ -${range(oldLine, oldCount)} +${range(newLine, newCount)} @@`,
|
|
219
|
+
ops: slice,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { sameBytes } from "./bytes.js";
|
|
2
|
+
import { extensionId } from "./extension-error.js";
|
|
3
|
+
export function encodePlanned(scope, planned) {
|
|
4
|
+
scope.enter("encode");
|
|
5
|
+
scope.checkAbort();
|
|
6
|
+
const { limits, messages } = scope.deps;
|
|
7
|
+
const { codec, style, change, loaded, target } = planned;
|
|
8
|
+
const text = change.after?.text ?? "";
|
|
9
|
+
let bytes;
|
|
10
|
+
try {
|
|
11
|
+
bytes = codec.encode(text, style);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw scope.extensionFailure("codecs", extensionId(codec, error));
|
|
15
|
+
}
|
|
16
|
+
if (!(bytes instanceof Uint8Array))
|
|
17
|
+
throw scope.extensionFailure("codecs", extensionId(codec));
|
|
18
|
+
if (bytes.byteLength > limits.maxWriteBytes) {
|
|
19
|
+
const limit = limits.maxWriteBytes;
|
|
20
|
+
const path = target.requestedPath;
|
|
21
|
+
throw scope.stop("TOO_LARGE", messages.tooLarge({ path, what: "content", limit, existing: loaded !== null }), { limit, bytes: bytes.byteLength });
|
|
22
|
+
}
|
|
23
|
+
if (loaded !== null && sameBytes(bytes, loaded.bytes))
|
|
24
|
+
return "same";
|
|
25
|
+
return bytes;
|
|
26
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare class ExtensionStepError extends Error {
|
|
2
|
+
readonly id: string;
|
|
3
|
+
constructor(id: string, cause: unknown);
|
|
4
|
+
}
|
|
5
|
+
export declare function stepFailure(step: {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
}, error: unknown): ExtensionStepError;
|
|
8
|
+
export declare function extensionId(extension: unknown, error?: unknown): string | null;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export class ExtensionStepError extends Error {
|
|
2
|
+
id;
|
|
3
|
+
constructor(id, cause) {
|
|
4
|
+
super(`extension step ${id} failed`, { cause });
|
|
5
|
+
this.id = id;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export function stepFailure(step, error) {
|
|
9
|
+
return error instanceof ExtensionStepError ? error : new ExtensionStepError(step.id, error);
|
|
10
|
+
}
|
|
11
|
+
export function extensionId(extension, error) {
|
|
12
|
+
if (error instanceof ExtensionStepError)
|
|
13
|
+
return error.id;
|
|
14
|
+
if (extension === null || typeof extension !== "object" || !("id" in extension))
|
|
15
|
+
return null;
|
|
16
|
+
return typeof extension.id === "string" ? extension.id : null;
|
|
17
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ToolCallContext } from "@better-fs-tools/read";
|
|
2
|
+
import type { WriteDependencies } from "../contract/deps.ts";
|
|
3
|
+
import type { MutationReport, MutationResult } from "../contract/result.ts";
|
|
4
|
+
export declare function formatResult<THost>(deps: WriteDependencies<THost>, call: ToolCallContext<THost>, report: MutationReport): MutationResult;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { defaultWriteFormatter } from "../formatters/default.js";
|
|
2
|
+
import { extensionId } from "./extension-error.js";
|
|
3
|
+
export function formatResult(deps, call, report) {
|
|
4
|
+
const ctx = {
|
|
5
|
+
digest: deps.digest,
|
|
6
|
+
limits: deps.limits,
|
|
7
|
+
mode: "model",
|
|
8
|
+
call,
|
|
9
|
+
};
|
|
10
|
+
let content = null;
|
|
11
|
+
try {
|
|
12
|
+
content = toContent(deps.formatter.format(report, ctx));
|
|
13
|
+
}
|
|
14
|
+
catch { }
|
|
15
|
+
if (content !== null)
|
|
16
|
+
return { ...report, content };
|
|
17
|
+
const id = extensionId(deps.formatter);
|
|
18
|
+
const failed = {
|
|
19
|
+
...report,
|
|
20
|
+
notes: [
|
|
21
|
+
...report.notes,
|
|
22
|
+
{
|
|
23
|
+
code: "extension-failed",
|
|
24
|
+
severity: "warning",
|
|
25
|
+
message: deps.messages.formatterFailed({ formatter: id ?? "formatter" }),
|
|
26
|
+
data: id === null ? { extension: "formatter" } : { extension: "formatter", id },
|
|
27
|
+
},
|
|
28
|
+
],
|
|
29
|
+
};
|
|
30
|
+
return { ...failed, content: toContent(defaultWriteFormatter().format(failed, ctx)) ?? [] };
|
|
31
|
+
}
|
|
32
|
+
function toContent(output) {
|
|
33
|
+
if (typeof output === "string")
|
|
34
|
+
return [{ type: "text", text: output }];
|
|
35
|
+
return Array.isArray(output) ? [...output] : null;
|
|
36
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { AbortStop } from "./abort.js";
|
|
2
|
+
import { extensionId } from "./extension-error.js";
|
|
3
|
+
import { isRecord } from "./input.js";
|
|
4
|
+
import { errorNote, hostErrorNote, isNote, isNoteList } from "./outcomes.js";
|
|
5
|
+
export async function runGuards(scope, changes) {
|
|
6
|
+
const { guards, classifiers } = scope.deps;
|
|
7
|
+
if (guards.length === 0)
|
|
8
|
+
return;
|
|
9
|
+
scope.enter("guards");
|
|
10
|
+
const ctx = Object.freeze({ ...scope.hookContext(), classifiers });
|
|
11
|
+
for (const change of changes) {
|
|
12
|
+
for (const guard of guards) {
|
|
13
|
+
scope.checkAbort();
|
|
14
|
+
let decision;
|
|
15
|
+
try {
|
|
16
|
+
decision = await scope.race(() => guard.check(change, ctx));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error instanceof AbortStop)
|
|
20
|
+
throw error;
|
|
21
|
+
throw scope.extensionFailure("guards", extensionId(guard, error));
|
|
22
|
+
}
|
|
23
|
+
const malformed = () => scope.extensionFailure("guards", extensionId(guard));
|
|
24
|
+
if (!isRecord(decision))
|
|
25
|
+
throw malformed();
|
|
26
|
+
if (decision.allow === true) {
|
|
27
|
+
if (decision.notes === undefined)
|
|
28
|
+
continue;
|
|
29
|
+
if (!isNoteList(decision.notes))
|
|
30
|
+
throw malformed();
|
|
31
|
+
scope.notes.push(...decision.notes);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (decision.allow !== false)
|
|
35
|
+
throw malformed();
|
|
36
|
+
const { note } = decision;
|
|
37
|
+
if (note !== undefined && !isNote(note))
|
|
38
|
+
throw malformed();
|
|
39
|
+
const data = { guard: guard.id, path: change.displayPath };
|
|
40
|
+
throw scope.stopWith(note === undefined
|
|
41
|
+
? errorNote("GUARD_REFUSED", scope.deps.messages.guardRefused({ guard: guard.id, path: change.displayPath }), data)
|
|
42
|
+
: hostErrorNote("GUARD_REFUSED", note, data));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function trailingNewline(text: string, oldText: string): "extra" | null;
|
|
2
|
+
export declare function closestRegion(text: string, oldText: string, maxLines: number): {
|
|
3
|
+
readonly text: string;
|
|
4
|
+
readonly lines: readonly [number, number];
|
|
5
|
+
} | null;
|
|
6
|
+
export declare function isAlreadyApplied(text: string, newText: string): boolean;
|
|
7
|
+
export declare class MissCounter {
|
|
8
|
+
private readonly max;
|
|
9
|
+
private readonly counts;
|
|
10
|
+
constructor(max?: number);
|
|
11
|
+
miss(key: string): number;
|
|
12
|
+
reset(key: string): void;
|
|
13
|
+
get size(): number;
|
|
14
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { findExact } from "../matchers/exact.js";
|
|
2
|
+
import { LineIndex } from "./line-index.js";
|
|
3
|
+
const MAX_CLOSEST_REGION_COMPARISONS = 2_000_000;
|
|
4
|
+
const MAX_HINT_LINE_LENGTH = 200;
|
|
5
|
+
const MAX_TRACKED_PATHS = 256;
|
|
6
|
+
export function trailingNewline(text, oldText) {
|
|
7
|
+
if (!oldText.endsWith("\n") || text.endsWith("\n"))
|
|
8
|
+
return null;
|
|
9
|
+
const trimmed = oldText.slice(0, -1);
|
|
10
|
+
return trimmed !== "" && text.endsWith(trimmed) ? "extra" : null;
|
|
11
|
+
}
|
|
12
|
+
export function closestRegion(text, oldText, maxLines) {
|
|
13
|
+
const index = new LineIndex(text);
|
|
14
|
+
const total = index.count;
|
|
15
|
+
const needle = oldText.split("\n").map((line) => line.trim());
|
|
16
|
+
if (needle.at(-1) === "" && needle.length > 1)
|
|
17
|
+
needle.pop();
|
|
18
|
+
const size = needle.length;
|
|
19
|
+
if (total === 0 || total * size > MAX_CLOSEST_REGION_COMPARISONS)
|
|
20
|
+
return null;
|
|
21
|
+
const lines = Array.from({ length: total }, (_, offset) => index.line(offset + 1).trim());
|
|
22
|
+
let best = 0;
|
|
23
|
+
let bestLine = 0;
|
|
24
|
+
for (let first = 0; first + Math.min(size, total) <= total; first += 1) {
|
|
25
|
+
let score = 0;
|
|
26
|
+
for (let offset = 0; offset < size && first + offset < total; offset += 1) {
|
|
27
|
+
const wanted = needle[offset];
|
|
28
|
+
if (wanted !== "" && lines[first + offset] === wanted)
|
|
29
|
+
score += 1;
|
|
30
|
+
}
|
|
31
|
+
if (score > best) {
|
|
32
|
+
best = score;
|
|
33
|
+
bestLine = first + 1;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (best === 0)
|
|
37
|
+
return null;
|
|
38
|
+
const from = Math.max(1, bestLine - 1);
|
|
39
|
+
const to = Math.min(total, bestLine + size, from + maxLines - 1);
|
|
40
|
+
const shown = [];
|
|
41
|
+
for (let line = from; line <= to; line += 1) {
|
|
42
|
+
const content = index.line(line);
|
|
43
|
+
shown.push(`${line}|${content.length > MAX_HINT_LINE_LENGTH ? `${content.slice(0, MAX_HINT_LINE_LENGTH)}…` : content}`);
|
|
44
|
+
}
|
|
45
|
+
return { text: shown.join("\n"), lines: [from, to] };
|
|
46
|
+
}
|
|
47
|
+
export function isAlreadyApplied(text, newText) {
|
|
48
|
+
return (newText !== "" &&
|
|
49
|
+
findExact(text, newText, { mode: "text", from: 0, maxMatches: 2 }).length === 1);
|
|
50
|
+
}
|
|
51
|
+
export class MissCounter {
|
|
52
|
+
max;
|
|
53
|
+
counts = new Map();
|
|
54
|
+
constructor(max = MAX_TRACKED_PATHS) {
|
|
55
|
+
this.max = max;
|
|
56
|
+
}
|
|
57
|
+
miss(key) {
|
|
58
|
+
const count = (this.counts.get(key) ?? 0) + 1;
|
|
59
|
+
this.counts.delete(key);
|
|
60
|
+
this.counts.set(key, count);
|
|
61
|
+
while (this.counts.size > this.max) {
|
|
62
|
+
const oldest = this.counts.keys().next().value;
|
|
63
|
+
if (oldest === undefined)
|
|
64
|
+
break;
|
|
65
|
+
this.counts.delete(oldest);
|
|
66
|
+
}
|
|
67
|
+
return count;
|
|
68
|
+
}
|
|
69
|
+
reset(key) {
|
|
70
|
+
this.counts.delete(key);
|
|
71
|
+
}
|
|
72
|
+
get size() {
|
|
73
|
+
return this.counts.size;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { MutatedFile, WritableFileSystem } from "@better-fs-tools/fs";
|
|
2
|
+
import type { PlannedChange } from "../contract/extensions.ts";
|
|
3
|
+
import type { FileChange } from "../contract/result.ts";
|
|
4
|
+
import type { Planned } from "./planned.ts";
|
|
5
|
+
import type { MutationScope } from "./scope.ts";
|
|
6
|
+
export interface Committed {
|
|
7
|
+
readonly planned: Planned;
|
|
8
|
+
change: FileChange;
|
|
9
|
+
identity: string | null;
|
|
10
|
+
finalStateKnown: boolean;
|
|
11
|
+
rewrittenByHook: boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare function committedFile<THost>(scope: MutationScope<THost>, planned: Planned, change: FileChange, file: MutatedFile): Committed;
|
|
14
|
+
export declare function newFileMode<THost>(scope: MutationScope<THost>, change: PlannedChange): number | null;
|
|
15
|
+
export declare function runWriteHooks<THost>(scope: MutationScope<THost>, fs: WritableFileSystem, committed: readonly Committed[]): Promise<void>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { hashBytes } from "./bytes.js";
|
|
2
|
+
import { extensionId } from "./extension-error.js";
|
|
3
|
+
import { isRecord } from "./input.js";
|
|
4
|
+
import { readCapped } from "./load.js";
|
|
5
|
+
import { isNoteList } from "./outcomes.js";
|
|
6
|
+
export function committedFile(scope, planned, change, file) {
|
|
7
|
+
const identity = scope.fileSystem().capabilities.identity ? file.identity : null;
|
|
8
|
+
return { planned, change, identity, finalStateKnown: true, rewrittenByHook: false };
|
|
9
|
+
}
|
|
10
|
+
export function newFileMode(scope, change) {
|
|
11
|
+
for (const hook of scope.deps.hooks) {
|
|
12
|
+
if (hook.newFileMode === undefined)
|
|
13
|
+
continue;
|
|
14
|
+
let mode;
|
|
15
|
+
try {
|
|
16
|
+
mode = hook.newFileMode(change, scope.hookContext());
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw scope.extensionFailure("hooks", extensionId(hook, error));
|
|
20
|
+
}
|
|
21
|
+
if (mode === null)
|
|
22
|
+
continue;
|
|
23
|
+
if (!Number.isInteger(mode) || mode < 0 || mode > 0o7777) {
|
|
24
|
+
throw scope.extensionFailure("hooks", extensionId(hook));
|
|
25
|
+
}
|
|
26
|
+
return mode;
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
export async function runWriteHooks(scope, fs, committed) {
|
|
31
|
+
const { hooks, messages } = scope.deps;
|
|
32
|
+
if (hooks.length === 0)
|
|
33
|
+
return;
|
|
34
|
+
scope.enter("hooks");
|
|
35
|
+
const ctx = Object.freeze({ ...scope.hookContext(), fs });
|
|
36
|
+
for (const file of committed) {
|
|
37
|
+
const path = file.change.path;
|
|
38
|
+
const rewrote = [];
|
|
39
|
+
for (const hook of hooks) {
|
|
40
|
+
const result = await runHook(hook, file.change, ctx);
|
|
41
|
+
if (result === null) {
|
|
42
|
+
scope.notes.push({
|
|
43
|
+
code: "hook-failed",
|
|
44
|
+
severity: "warning",
|
|
45
|
+
message: messages.hookFailed({ hook: hook.id, path }),
|
|
46
|
+
data: { hook: hook.id },
|
|
47
|
+
});
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
scope.notes.push(...result.notes);
|
|
51
|
+
if (result.rewrote)
|
|
52
|
+
rewrote.push(hook.id);
|
|
53
|
+
}
|
|
54
|
+
if (rewrote.length === 0)
|
|
55
|
+
continue;
|
|
56
|
+
file.rewrittenByHook = true;
|
|
57
|
+
await readBackRewrittenFile(scope, fs, file);
|
|
58
|
+
for (const hook of rewrote) {
|
|
59
|
+
scope.notes.push({
|
|
60
|
+
code: "hook-rewrote",
|
|
61
|
+
severity: "warning",
|
|
62
|
+
message: messages.hookRewrote({ hook, path }),
|
|
63
|
+
data: { hook },
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function runHook(hook, change, ctx) {
|
|
69
|
+
let result;
|
|
70
|
+
try {
|
|
71
|
+
result = await hook.afterWrite(change, ctx);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
if (!isRecord(result))
|
|
77
|
+
return null;
|
|
78
|
+
const { notes, rewrote } = result;
|
|
79
|
+
if (notes !== undefined && !isNoteList(notes))
|
|
80
|
+
return null;
|
|
81
|
+
if (rewrote !== undefined && typeof rewrote !== "boolean")
|
|
82
|
+
return null;
|
|
83
|
+
return { notes: notes ?? [], rewrote: rewrote === true };
|
|
84
|
+
}
|
|
85
|
+
async function readBackRewrittenFile(scope, fs, file) {
|
|
86
|
+
const { digest, limits } = scope.deps;
|
|
87
|
+
const { resolvedPath, requestedPath } = file.change;
|
|
88
|
+
let handle = null;
|
|
89
|
+
try {
|
|
90
|
+
const opened = await fs.open(resolvedPath, {});
|
|
91
|
+
if (!opened.ok)
|
|
92
|
+
throw new Error(opened.error.reason);
|
|
93
|
+
handle = opened.file;
|
|
94
|
+
const bytes = await readCapped(scope, handle, limits.maxFileBytes, requestedPath, () => {
|
|
95
|
+
return new Error("too large");
|
|
96
|
+
});
|
|
97
|
+
const { info } = handle;
|
|
98
|
+
file.identity = fs.capabilities.identity ? info.identity : null;
|
|
99
|
+
file.change = {
|
|
100
|
+
...file.change,
|
|
101
|
+
after: {
|
|
102
|
+
contentId: digest === null ? null : hashBytes(digest, bytes),
|
|
103
|
+
version: info.version ?? null,
|
|
104
|
+
bytes: bytes.byteLength,
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
file.finalStateKnown = false;
|
|
110
|
+
file.change = { ...file.change, after: { contentId: null, version: null, bytes: 0 } };
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
await handle?.close().catch(() => { });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ApplyPatchRequest, EditRequest, WriteRequest } from "../contract/input.ts";
|
|
2
|
+
import type { WriteLimits } from "../contract/limits.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Validates edit tool input. Throws TypeError on any key other than path and
|
|
5
|
+
* edits, a bad path, an edit list outside 1 to limits.maxEdits, an empty
|
|
6
|
+
* oldText, a non-string newText, or a non-boolean replaceAll.
|
|
7
|
+
*/
|
|
8
|
+
export declare function parseEditInput(input: unknown, limits: Readonly<WriteLimits>): EditRequest;
|
|
9
|
+
/**
|
|
10
|
+
* Validates write tool input. Throws TypeError on any key other than path and
|
|
11
|
+
* content, a bad path, or a non-string content.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseWriteInput(input: unknown, _limits: Readonly<WriteLimits>): WriteRequest;
|
|
14
|
+
/**
|
|
15
|
+
* Validates apply_patch tool input. Throws TypeError unless it holds only a
|
|
16
|
+
* non-empty patch of at most limits.maxPatchBytes UTF-8 bytes.
|
|
17
|
+
*/
|
|
18
|
+
export declare function parseApplyPatchInput(input: unknown, limits: Readonly<WriteLimits>): ApplyPatchRequest;
|
|
19
|
+
export declare function isPath(value: unknown): value is string;
|
|
20
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|