@crewhaus/tool-changeset 0.7.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.
@@ -0,0 +1,560 @@
1
+ /**
2
+ * Every rule, in the order findings are reported within one line.
3
+ *
4
+ * The ids are the caller's vocabulary — `enable`, `disable` and every finding
5
+ * name one — so they are a closed set, and an id that is not in it is refused
6
+ * rather than ignored. A typo that silently disables nothing is how a team
7
+ * ends up believing a rule is off for a year.
8
+ */
9
+ export const RULE_IDS = [
10
+ "conflictMarker",
11
+ "debugger",
12
+ "focusedTest",
13
+ "consoleLog",
14
+ "suppression",
15
+ "ticketlessTodo",
16
+ "machinePath",
17
+ "crlf",
18
+ "longLine",
19
+ "oversizedFile",
20
+ "commentedCode",
21
+ ];
22
+ const RULE_SET = new Set(RULE_IDS);
23
+ /**
24
+ * Rules that are OFF unless the caller asks for them.
25
+ *
26
+ * `commentedCode` is a heuristic with a genuine false-positive rate (see
27
+ * `looksLikeCommentedCode`), and a heuristic that fires on prose is how the
28
+ * whole tool gets disabled. It ships opt-in and at warning severity.
29
+ */
30
+ export const OPT_IN_RULES = Object.freeze(["commentedCode"]);
31
+ /** Default severity per rule; a few rules pick per finding (see `machinePath`). */
32
+ const DEFAULT_SEVERITY = {
33
+ conflictMarker: "error",
34
+ debugger: "error",
35
+ focusedTest: "error",
36
+ consoleLog: "warning",
37
+ suppression: "warning",
38
+ ticketlessTodo: "warning",
39
+ machinePath: "warning",
40
+ crlf: "warning",
41
+ longLine: "warning",
42
+ oversizedFile: "warning",
43
+ commentedCode: "warning",
44
+ };
45
+ const DEFAULT_TICKET = /(?:\b[A-Z][A-Z0-9]{1,9}-\d+\b|#\d+|https?:\/\/\S+)/;
46
+ const DEFAULT_MAX_LINE_CHARS = 1_000;
47
+ const DEFAULT_MAX_ADDED_LINES = 800;
48
+ const DEFAULT_MAX_FINDINGS = 500;
49
+ const SNIPPET_CHARS = 160;
50
+ /** Ids in `ids` that are not rules — returned so a caller can refuse by name. */
51
+ export function unknownRuleIds(ids) {
52
+ return ids.filter((id) => !RULE_SET.has(id));
53
+ }
54
+ /** The rules that will actually run, after the opt-in list and the caller's edits. */
55
+ export function activeRules(options = {}) {
56
+ const optIn = new Set(OPT_IN_RULES);
57
+ const active = new Set(RULE_IDS.filter((id) => !optIn.has(id)));
58
+ for (const id of options.enable ?? [])
59
+ active.add(id);
60
+ for (const id of options.disable ?? [])
61
+ active.delete(id);
62
+ return active;
63
+ }
64
+ const EXT_LANG = {
65
+ js: "js",
66
+ jsx: "js",
67
+ mjs: "js",
68
+ cjs: "js",
69
+ ts: "js",
70
+ tsx: "js",
71
+ mts: "js",
72
+ cts: "js",
73
+ svelte: "js",
74
+ vue: "js",
75
+ py: "python",
76
+ pyi: "python",
77
+ go: "go",
78
+ rs: "rust",
79
+ java: "jvm",
80
+ kt: "jvm",
81
+ kts: "jvm",
82
+ scala: "jvm",
83
+ groovy: "jvm",
84
+ c: "c",
85
+ h: "c",
86
+ cc: "c",
87
+ cpp: "c",
88
+ hpp: "c",
89
+ cs: "c",
90
+ m: "c",
91
+ swift: "c",
92
+ rb: "ruby",
93
+ php: "php",
94
+ sh: "shell",
95
+ bash: "shell",
96
+ zsh: "shell",
97
+ fish: "shell",
98
+ sql: "sql",
99
+ json: "config",
100
+ jsonc: "config",
101
+ yaml: "config",
102
+ yml: "config",
103
+ toml: "config",
104
+ ini: "config",
105
+ cfg: "config",
106
+ conf: "config",
107
+ env: "config",
108
+ properties: "config",
109
+ md: "markdown",
110
+ mdx: "markdown",
111
+ markdown: "markdown",
112
+ };
113
+ export function languageOf(path) {
114
+ const base = path.slice(path.lastIndexOf("/") + 1);
115
+ const dot = base.lastIndexOf(".");
116
+ if (dot <= 0)
117
+ return "other";
118
+ return EXT_LANG[base.slice(dot + 1).toLowerCase()] ?? "other";
119
+ }
120
+ /** Comment openers, per language, for the comment-aware rules. */
121
+ const COMMENT_PREFIXES = {
122
+ js: ["//", "/*", "*/", "*"],
123
+ go: ["//", "/*", "*/", "*"],
124
+ rust: ["//", "/*", "*/", "*"],
125
+ jvm: ["//", "/*", "*/", "*"],
126
+ c: ["//", "/*", "*/", "*"],
127
+ php: ["//", "#", "/*", "*/", "*"],
128
+ python: ["#"],
129
+ ruby: ["#"],
130
+ shell: ["#"],
131
+ sql: ["--"],
132
+ config: ["#"],
133
+ markdown: [],
134
+ other: [],
135
+ };
136
+ /** True when the whole line is a comment — not merely when one trails the code. */
137
+ export function isCommentLine(text, lang) {
138
+ const trimmed = text.trim();
139
+ if (trimmed === "")
140
+ return false;
141
+ return COMMENT_PREFIXES[lang].some((prefix) => trimmed.startsWith(prefix));
142
+ }
143
+ /** The comment's body: what is left after its opener. */
144
+ function commentBody(text, lang) {
145
+ const trimmed = text.trim();
146
+ for (const prefix of COMMENT_PREFIXES[lang]) {
147
+ if (!trimmed.startsWith(prefix))
148
+ continue;
149
+ // `///` and `//!` are doc comments; `#!` is a shebang, not a note.
150
+ return trimmed
151
+ .slice(prefix.length)
152
+ .replace(/^[/!]+/, "")
153
+ .trim();
154
+ }
155
+ return undefined;
156
+ }
157
+ /** Openers that begin a comment mid-line, as opposed to continuing one. */
158
+ const COMMENT_OPENERS = {
159
+ js: ["//", "/*"],
160
+ go: ["//", "/*"],
161
+ rust: ["//", "/*"],
162
+ jvm: ["//", "/*"],
163
+ c: ["//", "/*"],
164
+ php: ["//", "/*", "#"],
165
+ python: ["#"],
166
+ ruby: ["#"],
167
+ shell: ["#"],
168
+ sql: ["--"],
169
+ config: ["#"],
170
+ markdown: ["<!--"],
171
+ other: [],
172
+ };
173
+ /**
174
+ * Where the comment on this line starts, if one does.
175
+ *
176
+ * This is the closest a diff gets to knowing code from commentary. With the
177
+ * whole file in hand the honest move is a mask (`@crewhaus/tool-code`'s
178
+ * `maskSource` does exactly that, which is how `TodoScan` avoids string
179
+ * literals); with one line in hand, the position of the first opener is what
180
+ * there is. It is wrong in one direction — an opener inside a string literal
181
+ * reads as a comment — and that direction is silence, which is the one to be
182
+ * wrong in.
183
+ */
184
+ function commentStart(text, lang) {
185
+ if (isCommentLine(text, lang))
186
+ return text.length - text.trimStart().length;
187
+ let best;
188
+ for (const opener of COMMENT_OPENERS[lang]) {
189
+ const at = text.indexOf(opener);
190
+ if (at !== -1 && (best === undefined || at < best))
191
+ best = at;
192
+ }
193
+ return best;
194
+ }
195
+ /** True when `index` falls inside this line's comment. */
196
+ function inComment(start, index) {
197
+ return start !== undefined && start <= index;
198
+ }
199
+ // ---------------------------------------------------------------------------
200
+ // the rules themselves
201
+ /** `it.only`, `describe.only`, `fit`, `fdescribe` — a test run that silently covers one case. */
202
+ const FOCUSED_TEST = /(?:\.only\s*(?:\(|\.\s*each\b)|\b(?:fdescribe|fit|fcontext)\s*\()/;
203
+ /** A bare `debugger` statement, not the word inside an identifier or a string of prose. */
204
+ const DEBUGGER = /(?:^|[\s;{}()])debugger\s*(?:;|$)/;
205
+ /** The console calls that are output, not diagnostics: `error` and `warn` are left alone. */
206
+ const CONSOLE_LOG = /\bconsole\s*\.\s*(?:log|debug|dir|trace)\s*\(/;
207
+ /** Merge leftovers. `<<<<<<<` and `|||||||` are unmistakable; `=======` is not — see below. */
208
+ const CONFLICT_STRONG = /^(?:<{7}|>{7}|\|{7})(?:\s|$)/;
209
+ const CONFLICT_WEAK = /^={7}\s*$/;
210
+ const TODO_MARKER = /\b(TODO|FIXME|HACK|XXX)\b/;
211
+ /**
212
+ * Suppressions worth reporting when they are NEW.
213
+ *
214
+ * `@ts-expect-error` is deliberately absent: it fails once the error it
215
+ * covers is gone, which is the behaviour we want people to reach for.
216
+ * `biome-ignore` is absent for the same kind of reason — its syntax already
217
+ * requires a stated reason, so flagging it would be noise in this repository
218
+ * and every other one that uses biome.
219
+ */
220
+ const SUPPRESSIONS = [
221
+ {
222
+ re: /@ts-ignore\b/,
223
+ what: "@ts-ignore",
224
+ advice: "use @ts-expect-error, which fails when the error it covers goes away",
225
+ },
226
+ {
227
+ re: /@ts-nocheck\b/,
228
+ what: "@ts-nocheck",
229
+ advice: "it turns off type checking for the whole file",
230
+ },
231
+ {
232
+ re: /\beslint-disable(?:-next-line|-line)?\b/,
233
+ what: "an eslint-disable",
234
+ advice: "name the rule and say why, or fix the finding",
235
+ },
236
+ {
237
+ re: /#\s*type:\s*ignore\b/,
238
+ what: "a type: ignore",
239
+ advice: "narrow it to the specific error code, or fix the annotation",
240
+ },
241
+ ];
242
+ /**
243
+ * Machine-specific absolute paths — the ones that work on the author's laptop
244
+ * and nowhere else.
245
+ *
246
+ * A home directory carries a username and is always wrong in a repository, so
247
+ * it is an error. A temp directory is usually a fixture that should have been
248
+ * built with `mkdtemp`, but it is occasionally a legitimate platform path, so
249
+ * it is a warning.
250
+ */
251
+ const MACHINE_PATHS = [
252
+ {
253
+ re: /(?:^|[^\w\\])(?:\/Users\/|\/home\/)[A-Za-z0-9._-]+\//,
254
+ severity: "error",
255
+ what: "a home directory",
256
+ },
257
+ {
258
+ re: /[A-Za-z]:\\Users\\[A-Za-z0-9._-]+\\/,
259
+ severity: "error",
260
+ what: "a Windows home directory",
261
+ },
262
+ {
263
+ re: /(?:\/private)?\/var\/folders\/[A-Za-z0-9_+-]/,
264
+ severity: "warning",
265
+ what: "a macOS temporary directory",
266
+ },
267
+ {
268
+ re: /(?:^|[^\w])\/private\/tmp\//,
269
+ severity: "warning",
270
+ what: "a temporary directory",
271
+ },
272
+ ];
273
+ /** Keywords that open a statement, for the commented-out-code heuristic. */
274
+ const CODE_KEYWORD = /^(?:const|let|var|function|class|import|export|return|if|else|elif|for|while|switch|case|def|fn|pub|func|package|public|private|protected|static|async|await|new|throw|try|catch|finally|use|impl|struct|enum|type|interface|print|println!?|echo)\b/;
275
+ /** An assignment or a bare call, the two shapes most commented-out code has. */
276
+ const CODE_ASSIGN = /^[\w$][\w$.[\]"']*\s*(?:[-+*/|&^]?=[^=]|:=)/;
277
+ const CODE_CALL = /^[\w$][\w$.]*\s*\(.*\)\s*[;,]?$/;
278
+ /** Languages where the heuristic runs at all: prose-heavy and config files are excluded. */
279
+ const COMMENTED_CODE_LANGS = new Set([
280
+ "js",
281
+ "go",
282
+ "rust",
283
+ "jvm",
284
+ "c",
285
+ "php",
286
+ "python",
287
+ "ruby",
288
+ ]);
289
+ /**
290
+ * Does this comment look like code somebody commented out rather than a note
291
+ * somebody wrote?
292
+ *
293
+ * This is the one rule here that guesses, so it guesses toward silence. A
294
+ * body qualifies only on a positive code signal — a statement keyword, an
295
+ * assignment, a bare call, or a line ending in `;`/`{`/`}` — and a body that
296
+ * reads like a sentence vetoes all of them. The prose veto is a word count
297
+ * rather than a word list because a comment in German is still prose:
298
+ * five or more plain alphabetic words in a row is writing, not code.
299
+ *
300
+ * What still gets through: a short imperative comment that ends in a brace or
301
+ * names a function, `// see runTests()` most of all. That is why the rule is
302
+ * opt-in and warns rather than errors.
303
+ */
304
+ export function looksLikeCommentedCode(body) {
305
+ if (body.length < 4)
306
+ return false;
307
+ if (TODO_MARKER.test(body))
308
+ return false; // the ticketlessTodo rule's business
309
+ if (/^[-*=_#]{3,}$/.test(body))
310
+ return false; // a section rule, not code
311
+ if (/^(?:https?:|www\.)/.test(body))
312
+ return false;
313
+ const words = body.split(/\s+/).filter((w) => /^[A-Za-z']+$/.test(w));
314
+ if (words.length >= 5)
315
+ return false;
316
+ if (CODE_KEYWORD.test(body))
317
+ return /[(={:]/.test(body) || body.endsWith(";");
318
+ if (CODE_ASSIGN.test(body))
319
+ return true;
320
+ if (CODE_CALL.test(body))
321
+ return true;
322
+ return /[;{}]$/.test(body) && /[\w$)\]]/.test(body);
323
+ }
324
+ // ---------------------------------------------------------------------------
325
+ // the engine
326
+ const snippet = (text) => {
327
+ const trimmed = text.replace(/\r$/, "").trim();
328
+ return trimmed.length > SNIPPET_CHARS ? `${trimmed.slice(0, SNIPPET_CHARS)}…` : trimmed;
329
+ };
330
+ /**
331
+ * Should this file be looked at at all, and if not, why not.
332
+ *
333
+ * Only a binary stanza is refused: there is no text in it to lint, and the
334
+ * base85 payload of a `GIT binary patch` would read as content. A deletion, a
335
+ * pure rename and a mode change carry no added lines, so they cost nothing
336
+ * and are not worth reporting as skipped.
337
+ *
338
+ * A rename WITH edits IS scanned, which is a deliberate departure from the
339
+ * obvious "skip renames" rule: git reports a move-plus-edit as a rename whose
340
+ * hunks contain only the lines that really changed, and those lines are new
341
+ * code. Skipping them would make a `debugger` added while moving a file the
342
+ * one finding a review never sees.
343
+ */
344
+ function skipReason(file) {
345
+ return file.binary ? "binary file — no text to lint" : undefined;
346
+ }
347
+ function lineHits(text, lang, active, opts, fileHasStrongConflict) {
348
+ const hits = [];
349
+ const comment = commentStart(text, lang);
350
+ const maxLineChars = opts.maxLineChars ?? DEFAULT_MAX_LINE_CHARS;
351
+ if (active.has("conflictMarker")) {
352
+ // `=======` is a markdown heading underline, a section divider and half
353
+ // the ASCII art in the world, so it only counts as a conflict marker in a
354
+ // file that also gained an unmistakable one.
355
+ if (CONFLICT_STRONG.test(text) || (fileHasStrongConflict && CONFLICT_WEAK.test(text))) {
356
+ hits.push({
357
+ rule: "conflictMarker",
358
+ message: "a merge conflict marker was committed — resolve the conflict and remove it",
359
+ });
360
+ }
361
+ }
362
+ if (lang === "js") {
363
+ // Each of these is a STATEMENT, so anything from the comment opener
364
+ // rightwards cannot be one. That covers the trailing `// debugger;` and,
365
+ // usefully, the `"// debugger;"` in a test fixture: a line-local rule
366
+ // cannot tell a string from code, and this is the reading that stays
367
+ // quiet rather than the one that cries wolf.
368
+ const statement = (re) => {
369
+ const m = re.exec(text);
370
+ return m !== null && !inComment(comment, m.index);
371
+ };
372
+ if (active.has("debugger") && statement(DEBUGGER)) {
373
+ hits.push({
374
+ rule: "debugger",
375
+ message: "a `debugger` statement stops every browser that runs it",
376
+ });
377
+ }
378
+ if (active.has("focusedTest") && statement(FOCUSED_TEST)) {
379
+ hits.push({
380
+ rule: "focusedTest",
381
+ message: "a focused test (`.only` / `fit` / `fdescribe`) makes the suite pass while running almost nothing",
382
+ });
383
+ }
384
+ if (active.has("consoleLog") && statement(CONSOLE_LOG)) {
385
+ hits.push({
386
+ rule: "consoleLog",
387
+ message: "a console.log/debug/dir/trace call — use the logger, or delete it",
388
+ });
389
+ }
390
+ }
391
+ if (active.has("suppression")) {
392
+ for (const suppression of SUPPRESSIONS) {
393
+ const match = suppression.re.exec(text);
394
+ // A suppression directive only does anything inside a comment. The word
395
+ // in a rule table, a string or a test name is talk ABOUT one.
396
+ if (match === null || !inComment(comment, match.index))
397
+ continue;
398
+ hits.push({
399
+ rule: "suppression",
400
+ message: `${suppression.what} was added — ${suppression.advice}`,
401
+ });
402
+ }
403
+ }
404
+ if (active.has("ticketlessTodo")) {
405
+ const marker = TODO_MARKER.exec(text);
406
+ // The marker must OPEN the comment: `// TODO: x` is a note to a
407
+ // maintainer, and "a TODO with no ticket" in the middle of a sentence is
408
+ // prose about todos. With the whole file a mask would decide this; with
409
+ // one line, where the marker sits is the signal there is.
410
+ if (marker !== null && inComment(comment, marker.index)) {
411
+ const between = text.slice(comment ?? 0, marker.index);
412
+ if (/^(?:\/\/+|\/\*+|#+|\*+|--|<!--)?[\s\-*>]*$/.test(between)) {
413
+ const body = text.slice(marker.index).replace(/\*\/\s*$/, "");
414
+ const ticket = opts.ticketPattern ?? DEFAULT_TICKET;
415
+ if (!ticket.test(body)) {
416
+ hits.push({
417
+ rule: "ticketlessTodo",
418
+ message: "a TODO/FIXME/HACK with no ticket or issue reference — nobody will ever find it",
419
+ });
420
+ }
421
+ }
422
+ }
423
+ }
424
+ if (active.has("machinePath")) {
425
+ for (const pattern of MACHINE_PATHS) {
426
+ if (!pattern.re.test(text))
427
+ continue;
428
+ hits.push({
429
+ rule: "machinePath",
430
+ severity: pattern.severity,
431
+ message: `${pattern.what} is hard-coded here — it resolves on one machine and nowhere else`,
432
+ });
433
+ break; // one path finding per line is enough to act on
434
+ }
435
+ for (const extra of opts.machinePathPatterns ?? []) {
436
+ if (!extra.test(text))
437
+ continue;
438
+ hits.push({
439
+ rule: "machinePath",
440
+ message: `matches the operator's machine-path pattern /${extra.source}/`,
441
+ });
442
+ break;
443
+ }
444
+ }
445
+ if (active.has("longLine") && text.replace(/\r$/, "").length > maxLineChars) {
446
+ hits.push({
447
+ rule: "longLine",
448
+ message: `an added line of ${text.replace(/\r$/, "").length} characters (over ${maxLineChars}) — usually generated, minified or vendored content`,
449
+ });
450
+ }
451
+ if (active.has("commentedCode") && COMMENTED_CODE_LANGS.has(lang) && isCommentLine(text, lang)) {
452
+ const body = commentBody(text, lang);
453
+ if (body !== undefined && looksLikeCommentedCode(body)) {
454
+ hits.push({
455
+ rule: "commentedCode",
456
+ message: "this comment looks like commented-out code — delete it, the history keeps it (heuristic: prose that reads like code is reported too)",
457
+ });
458
+ }
459
+ }
460
+ return hits;
461
+ }
462
+ /**
463
+ * Run the policy over a parsed diff.
464
+ *
465
+ * Findings come back in diff order and then line order, which is stable for a
466
+ * stable diff — this is a deterministic tool and two runs over the same patch
467
+ * return the same bytes.
468
+ */
469
+ export function lintParsedDiff(parsed, options = {}) {
470
+ const active = activeRules(options);
471
+ const maxFindings = options.maxFindings ?? DEFAULT_MAX_FINDINGS;
472
+ const maxAdded = options.maxAddedLinesPerFile ?? DEFAULT_MAX_ADDED_LINES;
473
+ const findings = [];
474
+ const byRule = {};
475
+ const bySeverity = { error: 0, warning: 0 };
476
+ const skipped = [];
477
+ let filesScanned = 0;
478
+ let addedLinesScanned = 0;
479
+ let total = 0;
480
+ const record = (finding) => {
481
+ total++;
482
+ byRule[finding.rule] = (byRule[finding.rule] ?? 0) + 1;
483
+ bySeverity[finding.severity]++;
484
+ if (findings.length < maxFindings)
485
+ findings.push(finding);
486
+ };
487
+ for (const file of parsed.files) {
488
+ const path = file.newPath ?? file.oldPath ?? "(unknown path)";
489
+ const why = skipReason(file);
490
+ if (why !== undefined) {
491
+ skipped.push({ file: path, why });
492
+ continue;
493
+ }
494
+ if (file.hunks.length === 0)
495
+ continue;
496
+ filesScanned++;
497
+ const lang = languageOf(path);
498
+ // Two passes over the file's added lines: the first decides whether a
499
+ // bare `=======` in this file can be a conflict marker at all.
500
+ const added = [];
501
+ for (const hunk of file.hunks) {
502
+ for (const parsedLine of hunk.lines) {
503
+ if (parsedLine.kind !== "added" || parsedLine.newLine === null)
504
+ continue;
505
+ added.push({ text: parsedLine.text, line: parsedLine.newLine });
506
+ }
507
+ }
508
+ addedLinesScanned += added.length;
509
+ const strongConflict = added.some((l) => CONFLICT_STRONG.test(l.text));
510
+ if (active.has("oversizedFile") && file.added > maxAdded) {
511
+ record({
512
+ rule: "oversizedFile",
513
+ severity: DEFAULT_SEVERITY.oversizedFile,
514
+ file: path,
515
+ line: null,
516
+ message: `${file.added} added lines in one file (over ${maxAdded}) — if it is generated or vendored, say so in the PR or ignore the path`,
517
+ snippet: "",
518
+ });
519
+ }
520
+ // CRLF is a property of the file, not of a line: reporting 400 of them
521
+ // buries every other finding in the change set.
522
+ let crlfSeen = 0;
523
+ let crlfFirst = 0;
524
+ for (const line of added) {
525
+ if (line.text.endsWith("\r")) {
526
+ crlfSeen++;
527
+ if (crlfSeen === 1)
528
+ crlfFirst = line.line;
529
+ }
530
+ for (const hit of lineHits(line.text, lang, active, options, strongConflict)) {
531
+ record({
532
+ rule: hit.rule,
533
+ severity: hit.severity ?? DEFAULT_SEVERITY[hit.rule],
534
+ file: path,
535
+ line: line.line,
536
+ message: hit.message,
537
+ snippet: snippet(line.text),
538
+ });
539
+ }
540
+ }
541
+ if (active.has("crlf") && crlfSeen > 0) {
542
+ record({
543
+ rule: "crlf",
544
+ severity: DEFAULT_SEVERITY.crlf,
545
+ file: path,
546
+ line: crlfFirst,
547
+ message: `${crlfSeen} added line${crlfSeen === 1 ? "" : "s"} end${crlfSeen === 1 ? "s" : ""} with CRLF — normalise the line endings or set .gitattributes`,
548
+ snippet: "",
549
+ });
550
+ }
551
+ }
552
+ return {
553
+ findings,
554
+ filesScanned,
555
+ addedLinesScanned,
556
+ counts: { byRule, bySeverity },
557
+ skipped,
558
+ truncated: total > findings.length,
559
+ };
560
+ }
@@ -0,0 +1,42 @@
1
+ import { CrewhausError } from "@crewhaus/errors";
2
+ /** Raised when a caller-supplied path resolves outside the workspace root. */
3
+ export declare class ToolPermissionError extends CrewhausError {
4
+ readonly name = "ToolPermissionError";
5
+ readonly toolName: string;
6
+ readonly path: string;
7
+ constructor(toolName: string, attemptedPath: string);
8
+ }
9
+ /**
10
+ * A validated path, in both forms the tools need.
11
+ *
12
+ * `real` has every in-workspace symlink already resolved and is what I/O
13
+ * should use — operating on it closes most of the check-to-use window.
14
+ * `abs` is the lexical resolution, which is what a tool must use when the
15
+ * question is about the link ITSELF (`Stat` reporting a symlink target,
16
+ * `RemovePath` deleting a link rather than its destination).
17
+ */
18
+ export type SafePath = {
19
+ readonly abs: string;
20
+ readonly real: string;
21
+ /** The path as the caller wrote it, for echoing back in results. */
22
+ readonly given: string;
23
+ /** Slash-separated path relative to the workspace root. */
24
+ readonly rel: string;
25
+ };
26
+ /** The workspace root, resolved. Every path is contained within it. */
27
+ export declare function workspaceRoot(): string;
28
+ export declare function resolveSafe(toolName: string, rel: string, root?: string): SafePath;
29
+ /** A path relative to the workspace root, with `/` separators on every OS. */
30
+ export declare function toPosix(p: string): string;
31
+ /**
32
+ * True when `candidate` is `parent` or lives underneath it. Both must already
33
+ * be absolute. Used to keep an archive entry, or a symlink inside an
34
+ * extracted tree, from reaching outside its destination.
35
+ */
36
+ export declare function isInside(parent: string, candidate: string): boolean;
37
+ /**
38
+ * Reject an archive member name that would escape its destination: an
39
+ * absolute path, a Windows drive prefix, or any `..` segment. Checked on the
40
+ * NAME, before extraction, because after extraction the damage is done.
41
+ */
42
+ export declare function archiveEntryEscapes(name: string): boolean;