@descent-vtt/spec-brief 0.4.0 → 0.5.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 (51) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -0
  3. package/dist/archive.js +31 -18
  4. package/dist/archive.js.map +1 -1
  5. package/dist/brief.js +8 -5
  6. package/dist/brief.js.map +1 -1
  7. package/dist/cli.js +21 -13
  8. package/dist/cli.js.map +1 -1
  9. package/dist/collisions.d.ts +9 -0
  10. package/dist/collisions.js +50 -40
  11. package/dist/collisions.js.map +1 -1
  12. package/dist/config.d.ts +6 -0
  13. package/dist/config.js +17 -6
  14. package/dist/config.js.map +1 -1
  15. package/dist/corpus.js +21 -15
  16. package/dist/corpus.js.map +1 -1
  17. package/dist/engine.d.ts +2 -1
  18. package/dist/engine.js +24 -15
  19. package/dist/engine.js.map +1 -1
  20. package/dist/frontmatter.js +1 -1
  21. package/dist/frontmatter.js.map +1 -1
  22. package/dist/fs.js +9 -5
  23. package/dist/fs.js.map +1 -1
  24. package/dist/git.js +7 -4
  25. package/dist/git.js.map +1 -1
  26. package/dist/glob.d.ts +8 -0
  27. package/dist/glob.js +74 -0
  28. package/dist/glob.js.map +1 -1
  29. package/dist/links.js +2 -1
  30. package/dist/links.js.map +1 -1
  31. package/dist/lint.js +3 -4
  32. package/dist/lint.js.map +1 -1
  33. package/dist/plugins.js +10 -6
  34. package/dist/plugins.js.map +1 -1
  35. package/dist/report.d.ts +8 -1
  36. package/dist/report.js +22 -20
  37. package/dist/report.js.map +1 -1
  38. package/dist/rules.js +10 -6
  39. package/dist/rules.js.map +1 -1
  40. package/dist/scaffold.js +2 -2
  41. package/dist/scaffold.js.map +1 -1
  42. package/dist/schedule.js +10 -20
  43. package/dist/schedule.js.map +1 -1
  44. package/dist/schema.js +9 -13
  45. package/dist/schema.js.map +1 -1
  46. package/dist/scope.js +2 -2
  47. package/dist/scope.js.map +1 -1
  48. package/dist/text.d.ts +4 -1
  49. package/dist/text.js +10 -6
  50. package/dist/text.js.map +1 -1
  51. package/package.json +1 -1
package/dist/glob.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"glob.js","sourceRoot":"","sources":["../src/glob.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EACL,gBAAgB,EAChB,UAAU,IAAI,UAAU,EACxB,WAAW,IAAI,WAAW,EAC1B,YAAY,EACZ,SAAS,IAAI,SAAS,EAGtB,cAAc,GAEf,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAuB,cAAc,EAAgB,CAAC;AA+B3E,qDAAqD;AACrD,MAAM,UAAU,SAAS,CAAC,MAAc,EAAE,OAAO,GAAiB,EAAE;IAClE,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,iEAAiE,EAAE,CAAC;IAC5H,2EAA2E;IAC3E,0EAA0E;IAC1E,2EAA2E;IAC3E,4EAA4E;IAC5E,oCAAoC;IACpC,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IACvC,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IACtD,IAAI,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,wEAAwE,EAAE,CAAC;IACvH,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,IAAI,MAAM,CAAC;IACxC,MAAM,QAAQ,GAAc,EAAE,CAAC;IAC/B,MAAM,OAAO,GAAG,CAAC,IAAY,EAAkB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AAC,EAAE,KAAK,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,GAAG,CAAC,CAAC;YAAE,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;IAChI,CAAC;IACD,MAAM,IAAI,GAAG,EAAE,KAAK,EAAE,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,WAAW,EAAE,CAAC;IACpD,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACvB,OAAO,IAAI,CAAC;AACd,CAAC;AAED,sEAAsE;AACtE,MAAM,UAAU,IAAI,CAAC,IAAU,EAAE,IAAY;IAC3C,IAAI,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;QAAE,OAAO,MAAM,CAAC;IACxC,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAA+B;IACvD,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC;IACxC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["/**\n * Scopes as globs: spec-core's `path` dialect, read the way spec-brief reads a\n * brief.\n *\n * The syntax, the automaton and the witness search are spec-core's, copied\n * into `src/vendor/` and verified by hash, so the family's tools read one\n * pattern the same way (spec-core ADR-0003). What is decided here is what\n * spec-brief adds around it:\n *\n * - A pattern is relative to the repository root, so a leading `/` is refused\n * rather than rooted at the filesystem: on the pattern, and on a text its\n * braces give, since spec-core reads `{/docs,x}` as `/docs` or `x`, and\n * `docs` would fall out of the scope unsaid. A leading `./` goes with the\n * slashes after it, as POSIX reads them: `.//docs` is `docs`, and\n * `./{/docs,x}` is `docs` or `x`. A list entry's `!` has no list to belong\n * to in a scope, so it is refused rather than read.\n * - Paths compare case-sensitively on every host, as git's do.\n * - A path with no glob syntax is read as the tree reads it: a file the tree\n * holds is that file, a directory it holds is everything beneath it, and a\n * path it does not hold is a file, unless it is written with a trailing `/`.\n * The tree, not the spelling, knows that `Dockerfile` is a file and\n * `docs/v1.2` a directory (ADR-0005, amended 2026-09-26).\n * - A trailing `/**` is at least one segment, so `docs/**` is the directory's\n * contents and a collision witness is always a file. A trailing `/` means\n * the same on a brace alternative as on the whole pattern: `{src/,lib}` is\n * `src/` or `lib`, and the tree is asked about `lib` alone.\n *\n * Nothing here compiles to a `RegExp`. Matching costs at most the pattern's\n * size times the path's length, and a question about two scopes that cannot be\n * answered within the search's budget answers `undecided`, never a guess.\n */\n\nimport {\n globAlternatives,\n globCovers as coreCovers,\n globWitness as coreWitness,\n isGlobSyntax,\n parseGlob as coreParse,\n type Glob as CoreGlob,\n type LiteralReading,\n WITNESS_BUDGET,\n type Witness,\n} from './vendor/spec-core/pattern/index.js';\nimport { segments } from './vendor/spec-core/path/index.js';\n\nexport { isGlobSyntax, type LiteralReading, WITNESS_BUDGET, type Witness };\n\n/** A literal path a pattern names, and how it was read. */\nexport interface Literal {\n readonly path: string;\n readonly reading: LiteralReading;\n}\n\nexport interface Glob {\n readonly source: string;\n /** The compiled pattern: spec-core's `path` dialect, case-sensitive. */\n readonly compiled: CoreGlob;\n /**\n * Each path the pattern names with no glob syntax and no trailing `/`, one\n * per brace alternative; empty when it has none.\n */\n readonly literals: readonly Literal[];\n}\n\nexport type GlobParse = { readonly ok: true; readonly glob: Glob } | { readonly ok: false; readonly error: string };\n\nexport interface ParseOptions {\n /**\n * How a path with no glob syntax is read: `file`, that path alone;\n * `directory`, everything beneath it; `either`, both. A function is asked\n * per literal path, as {@link readingIn} answers for a tree. `file` when\n * unset: a path nothing says is a directory is not read as one.\n */\n readonly literal?: LiteralReading | ((path: string) => LiteralReading) | undefined;\n}\n\n/** Parses a scope pattern, or says why it cannot. */\nexport function parseGlob(source: string, options: ParseOptions = {}): GlobParse {\n const pattern = source.trim();\n if (pattern.startsWith('!')) return { ok: false, error: 'negated patterns are not supported; narrow the positive pattern' };\n // spec-core's own reading of where each alternative starts, a leading `./`\n // and `/` included (spec-core ADR-0003). A pattern it refuses, the core's\n // parse refuses in the same words, so either may say so. It comes first so\n // that a pattern led by `/`, which the core roots at the filesystem's root,\n // is refused in spec-brief's words.\n const read = globAlternatives(pattern);\n if (!read.ok) return { ok: false, error: read.error };\n if (read.rooted) return { ok: false, error: 'a pattern is relative to the repository root and cannot start with \"/\"' };\n const given = options.literal ?? 'file';\n const literals: Literal[] = [];\n const literal = (path: string): LiteralReading => {\n const reading = typeof given === 'function' ? given(path) : given;\n literals.push({ path, reading });\n return reading;\n };\n // A pattern too large to compile is refused by the core, with its reason,\n // as a malformed one is; what the reading throws is a defect, and passes on.\n const parsed = coreParse(pattern, { dialect: 'path', caseSensitive: true, literal });\n if (!parsed.ok) return parsed;\n // Once the core has parsed the pattern, so that an alternative naming no\n // path, `{/,x}`, is refused in the core's words. The text is named behind\n // the `/` that roots it, as spec-core gives it: it reads the same written\n // alone, so a `}` or `,` no group took is written as a class, `[}]`.\n const rooted = read.alternatives.find((alternative) => alternative.rooted);\n if (rooted !== undefined) {\n return { ok: false, error: `a pattern is relative to the repository root, and the braces expand to \"/${rooted.text}\", which starts with \"/\"` };\n }\n return { ok: true, glob: { source, compiled: parsed.glob, literals } };\n}\n\n/**\n * Whether a path matches. The path is read as a repository path: empty and\n * `.` segments are dropped, so `./src//a.ts` is `src/a.ts`.\n */\nexport function matchGlob(glob: Glob, path: string): boolean {\n const canonical = segments(path).join('/');\n return canonical !== '' && glob.compiled.match(canonical);\n}\n\n/**\n * A shortest path every glob in `include` matches and none in `exclude` does,\n * `none` as a proof that there is no such path, or `undecided` when the search\n * met its budget first.\n */\nexport function globWitness(include: readonly Glob[], exclude: readonly Glob[] = [], budget: number = WITNESS_BUDGET): Witness {\n return coreWitness(\n include.map((g) => g.compiled),\n exclude.map((g) => g.compiled),\n budget,\n );\n}\n\n/** Whether every path `inner` matches is matched by one of `outer`, or `undecided`. */\nexport function globCovers(outer: readonly Glob[], inner: Glob, budget: number = WITNESS_BUDGET): boolean | 'undecided' {\n return coreCovers(\n outer.map((g) => g.compiled),\n inner.compiled,\n budget,\n );\n}\n\n/**\n * A path both globs match, or `null` when there is none: the 0.1 interface,\n * kept for the library's callers. It cannot say `undecided`, so a search that\n * meets its budget throws; {@link globWitness} answers in three ways.\n */\nexport function intersectGlobs(a: Glob, b: Glob, budget: number = WITNESS_BUDGET): string | null {\n const witness = globWitness([a, b], [], budget);\n if (witness.kind === 'undecided') {\n throw new Error(`whether \"${a.source}\" and \"${b.source}\" meet is undecided within the search's budget`);\n }\n return witness.kind === 'found' ? witness.path : null;\n}\n\n/**\n * The directories a walk must enter to find every match, one per brace\n * alternative: the leading literal segments, or a literal file's directory.\n * `''` for an alternative that can match at the root.\n */\nexport function globBases(glob: Glob): readonly string[] {\n return glob.compiled.bases;\n}\n\n/** The first of {@link globBases}: the 0.1 interface, kept for the library's callers. */\nexport function globBase(glob: Glob): string {\n // One base per alternative, and a pattern has at least one.\n return glob.compiled.bases[0] as string;\n}\n\n/** A brace alternative as its pattern writes it, and the index in the pattern where it ends. */\nexport interface WrittenAlternative {\n readonly written: string;\n readonly end: number;\n}\n\n/**\n * Each alternative of a pattern as written, in the order the core expands\n * them, and where each ends, when a `/` written there ends that alternative\n * and no other: the pattern itself when it has no braces, or the alternatives\n * of braces that end the pattern and whose own braces end theirs -\n * `lib/{util,new}`, `{a,b/{c,d}}`. `null` when more of the pattern follows\n * braces, `{a,b}/new`, since every alternative they give ends where the\n * pattern does; and for a pattern with a class, which may hold a brace or a\n * comma of its own and which this does not read.\n *\n * spec-core expands braces and keeps nothing of where an alternative was\n * written, and a note's advice is built from what was written, as the core\n * builds its own. So this reads braces as the expansion does, for a pattern\n * that parses: a `\\` escapes the next character, and a `}` with no `{` open\n * is a literal.\n */\nexport function writtenAlternatives(pattern: string): WrittenAlternative[] | null {\n let depth = 0;\n let open = 0;\n const stops: number[] = [];\n for (let i = 0; i < pattern.length; i += 1) {\n const ch = pattern.charAt(i);\n if (ch === '\\\\') {\n i += 1;\n } else if (ch === '[') {\n return null;\n } else if (ch === '{') {\n if (depth === 0) open = i;\n depth += 1;\n } else if (ch === ',' && depth === 1) {\n stops.push(i);\n } else if (ch === '}' && depth > 0) {\n depth -= 1;\n if (depth === 0) return i === pattern.length - 1 ? optionsOf(pattern, open, [...stops, i]) : null;\n }\n }\n return [{ written: pattern, end: pattern.length }];\n}\n\n/** The alternatives of the braces opened at `open`, each option ending at one of `stops`. */\nfunction optionsOf(pattern: string, open: number, stops: readonly number[]): WrittenAlternative[] | null {\n const prefix = pattern.slice(0, open);\n const alternatives: WrittenAlternative[] = [];\n let start = open + 1;\n for (const stop of stops) {\n const inner = writtenAlternatives(pattern.slice(start, stop));\n if (inner === null) return null;\n for (const { written, end } of inner) alternatives.push({ written: prefix + written, end: start + end });\n start = stop + 1;\n }\n return alternatives;\n}\n\n/** A name with an extension, `login.ts` or `.eslintrc.json`, and not a dot-name such as `.github`. */\nexport function hasExtension(name: string): boolean {\n return /.\\.[^.]+$/.test(name);\n}\n\n/** The files a tree holds, and every directory above one. */\nexport interface Tree {\n readonly files: ReadonlySet<string>;\n readonly directories: ReadonlySet<string>;\n}\n\nconst trees = new WeakMap<readonly string[], Tree>();\n\n/** The tree a list of files describes. Built once per list, which every brief of a run shares. */\nexport function treeOf(files: readonly string[]): Tree {\n const known = trees.get(files);\n if (known !== undefined) return known;\n const directories = new Set<string>();\n for (const file of files) {\n for (let slash = file.indexOf('/'); slash !== -1; slash = file.indexOf('/', slash + 1)) directories.add(file.slice(0, slash));\n }\n const tree = { files: new Set(files), directories };\n trees.set(files, tree);\n return tree;\n}\n\n/** What the tree holds at a path: a file, a directory, or nothing. */\nexport function held(tree: Tree, path: string): 'file' | 'directory' | null {\n if (tree.files.has(path)) return 'file';\n return tree.directories.has(path) ? 'directory' : null;\n}\n\n/**\n * How a tree reads a literal path: a directory it holds is a directory, and\n * anything else is a file. Without a tree nothing is known to be a directory,\n * so every literal is a file; a trailing `/` says otherwise, and never reaches\n * this question.\n */\nexport function readingIn(files: readonly string[] | null): (path: string) => LiteralReading {\n if (files === null) return () => 'file';\n const tree = treeOf(files);\n return (path) => (held(tree, path) === 'directory' ? 'directory' : 'file');\n}\n"]}
1
+ {"version":3,"file":"glob.js","sourceRoot":"","sources":["../src/glob.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,EACL,gBAAgB,EAChB,UAAU,IAAI,UAAU,EACxB,WAAW,IAAI,WAAW,EAC1B,YAAY,EACZ,SAAS,IAAI,SAAS,EAGtB,cAAc,GAEf,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAuB,cAAc,EAAgB,CAAC;AA+B3E,qDAAqD;AACrD,MAAM,UAAU,SAAS,CAAC,MAAc,EAAE,OAAO,GAAiB,EAAE;IAClE,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,iEAAiE,EAAE,CAAC;IAC5H,2EAA2E;IAC3E,0EAA0E;IAC1E,2EAA2E;IAC3E,4EAA4E;IAC5E,oCAAoC;IACpC,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IACvC,IAAI,C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CAAC,IAAI,CAAC;QAAE,OAAO,MAAM,CAAC;IACxC,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAA+B;IACvD,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,GAAG,EAAE,CAAC,MAAM,CAAC;IACxC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["/**\n * Scopes as globs: spec-core's `path` dialect, read the way spec-brief reads a\n * brief.\n *\n * The syntax, the automaton and the witness search are spec-core's, copied\n * into `src/vendor/` and verified by hash, so the family's tools read one\n * pattern the same way (spec-core ADR-0003). What is decided here is what\n * spec-brief adds around it:\n *\n * - A pattern is relative to the repository root, so a leading `/` is refused\n * rather than rooted at the filesystem: on the pattern, and on a text its\n * braces give, since spec-core reads `{/docs,x}` as `/docs` or `x`, and\n * `docs` would fall out of the scope unsaid. A leading `./` goes with the\n * slashes after it, as POSIX reads them: `.//docs` is `docs`, and\n * `./{/docs,x}` is `docs` or `x`. A list entry's `!` has no list to belong\n * to in a scope, so it is refused rather than read.\n * - Paths compare case-sensitively on every host, as git's do.\n * - A path with no glob syntax is read as the tree reads it: a file the tree\n * holds is that file, a directory it holds is everything beneath it, and a\n * path it does not hold is a file, unless it is written with a trailing `/`.\n * The tree, not the spelling, knows that `Dockerfile` is a file and\n * `docs/v1.2` a directory (ADR-0005, amended 2026-09-26).\n * - A trailing `/**` is at least one segment, so `docs/**` is the directory's\n * contents and a collision witness is always a file. A trailing `/` means\n * the same on a brace alternative as on the whole pattern: `{src/,lib}` is\n * `src/` or `lib`, and the tree is asked about `lib` alone.\n *\n * Nothing here compiles to a `RegExp`. Matching costs at most the pattern's\n * size times the path's length, and a question about two scopes that cannot be\n * answered within the search's budget answers `undecided`, never a guess.\n */\n\nimport {\n globAlternatives,\n globCovers as coreCovers,\n globWitness as coreWitness,\n isGlobSyntax,\n parseGlob as coreParse,\n type Glob as CoreGlob,\n type LiteralReading,\n WITNESS_BUDGET,\n type Witness,\n} from './vendor/spec-core/pattern/index.js';\nimport { segments } from './vendor/spec-core/path/index.js';\n\nexport { isGlobSyntax, type LiteralReading, WITNESS_BUDGET, type Witness };\n\n/** A literal path a pattern names, and how it was read. */\nexport interface Literal {\n readonly path: string;\n readonly reading: LiteralReading;\n}\n\nexport interface Glob {\n readonly source: string;\n /** The compiled pattern: spec-core's `path` dialect, case-sensitive. */\n readonly compiled: CoreGlob;\n /**\n * Each path the pattern names with no glob syntax and no trailing `/`, one\n * per brace alternative; empty when it has none.\n */\n readonly literals: readonly Literal[];\n}\n\nexport type GlobParse = { readonly ok: true; readonly glob: Glob } | { readonly ok: false; readonly error: string };\n\nexport interface ParseOptions {\n /**\n * How a path with no glob syntax is read: `file`, that path alone;\n * `directory`, everything beneath it; `either`, both. A function is asked\n * per literal path, as {@link readingIn} answers for a tree. `file` when\n * unset: a path nothing says is a directory is not read as one.\n */\n readonly literal?: LiteralReading | ((path: string) => LiteralReading) | undefined;\n}\n\n/** Parses a scope pattern, or says why it cannot. */\nexport function parseGlob(source: string, options: ParseOptions = {}): GlobParse {\n const pattern = source.trim();\n if (pattern.startsWith('!')) return { ok: false, error: 'negated patterns are not supported; narrow the positive pattern' };\n // spec-core's own reading of where each alternative starts, a leading `./`\n // and `/` included (spec-core ADR-0003). A pattern it refuses, the core's\n // parse refuses in the same words, so either may say so. It comes first so\n // that a pattern led by `/`, which the core roots at the filesystem's root,\n // is refused in spec-brief's words.\n const read = globAlternatives(pattern);\n if (!read.ok) return { ok: false, error: read.error };\n if (read.rooted) return { ok: false, error: 'a pattern is relative to the repository root and cannot start with \"/\"' };\n const given = options.literal ?? 'file';\n const literals: Literal[] = [];\n const literal = (path: string): LiteralReading => {\n const reading = typeof given === 'function' ? given(path) : given;\n literals.push({ path, reading });\n return reading;\n };\n // A pattern too large to compile is refused by the core, with its reason,\n // as a malformed one is; what the reading throws is a defect, and passes on.\n const parsed = coreParse(pattern, { dialect: 'path', caseSensitive: true, literal });\n if (!parsed.ok) return parsed;\n // Once the core has parsed the pattern, so that an alternative naming no\n // path, `{/,x}`, is refused in the core's words. The text is named behind\n // the `/` that roots it, as spec-core gives it: it reads the same written\n // alone, so a `}` or `,` no group took is written as a class, `[}]`.\n const rooted = read.alternatives.find((alternative) => alternative.rooted);\n if (rooted !== undefined) {\n return { ok: false, error: `a pattern is relative to the repository root, and the braces expand to \"/${rooted.text}\", which starts with \"/\"` };\n }\n return { ok: true, glob: { source, compiled: parsed.glob, literals } };\n}\n\n/**\n * Whether a path matches. The path is read as a repository path: empty and\n * `.` segments are dropped, so `./src//a.ts` is `src/a.ts`.\n */\nexport function matchGlob(glob: Glob, path: string): boolean {\n const canonical = segments(path).join('/');\n return canonical !== '' && glob.compiled.match(canonical);\n}\n\n/** A list of files by path, so the files below a directory are one run of it. */\ninterface FileIndex {\n /** Each path the list holds, as {@link matchGlob} reads it, once, in code-unit order. */\n readonly paths: readonly string[];\n /** The positions in the list of each path's files. */\n readonly positions: ReadonlyMap<string, readonly number[]>;\n}\n\nconst indexes = new WeakMap<readonly string[], FileIndex>();\n\n/** The index of a list. Built once per list, which every pattern of a run shares, as {@link treeOf} is. */\nfunction indexOf(files: readonly string[]): FileIndex {\n const known = indexes.get(files);\n // Only time is kept here: an index built again is the same index.\n if (known !== undefined) return known;\n const positions = new Map<string, number[]>();\n files.forEach((file, position) => {\n const path = segments(file).join('/');\n const others = positions.get(path);\n if (others === undefined) positions.set(path, [position]);\n else others.push(position);\n });\n const index = { paths: [...positions.keys()].sort(), positions };\n indexes.set(files, index);\n return index;\n}\n\n/**\n * The positions of the files a glob can match: the run of the index below\n * each of its bases. spec-core names, for each brace alternative, the\n * directory every match of it lies below, or `''` where a match can lie\n * anywhere, so a file below none of them cannot match. Asking every pattern\n * about every file made `lint`, `matrix` and `schedule` grow with patterns\n * times files: over 240 briefs and 93,000 files a lint took 35 s, nine tenths\n * of it matching.\n */\nfunction* candidates(index: FileIndex, glob: Glob): Generator<number> {\n const { paths, positions } = index;\n for (const base of glob.compiled.bases) {\n const prefix = base === '' ? '' : `${base}/`;\n // The first path that sorts at or after the prefix. `<=` finds the same\n // one, an equivalent mutant: no path read so ends with `/`, so none\n // equals a prefix but `''`, which no glob matches.\n let low = 0;\n let high = paths.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if ((paths[middle] as string) < prefix) low = middle + 1;\n else high = middle;\n }\n for (let place = low; place < paths.length && (paths[place] as string).startsWith(prefix); place += 1) {\n yield* positions.get(paths[place] as string) as readonly number[];\n }\n }\n}\n\n/**\n * The files of a list a glob matches, in the list's order: those\n * {@link matchGlob} matches, asked only of the files below one of the glob's\n * bases.\n */\nexport function filesMatching(glob: Glob, files: readonly string[]): string[] {\n const index = indexOf(files);\n const matched = new Set<number>();\n for (const position of candidates(index, glob)) {\n if (matchGlob(glob, files[position] as string)) matched.add(position);\n }\n return [...matched].sort((a, b) => a - b).map((position) => files[position] as string);\n}\n\n/** Whether a glob matches any file of a list, asked only of the files below one of its bases. */\nexport function matchesAny(glob: Glob, files: readonly string[]): boolean {\n const index = indexOf(files);\n for (const position of candidates(index, glob)) {\n if (matchGlob(glob, files[position] as string)) return true;\n }\n return false;\n}\n\n/**\n * A shortest path every glob in `include` matches and none in `exclude` does,\n * `none` as a proof that there is no such path, or `undecided` when the search\n * met its budget first.\n */\nexport function globWitness(include: readonly Glob[], exclude: readonly Glob[] = [], budget: number = WITNESS_BUDGET): Witness {\n return coreWitness(\n include.map((g) => g.compiled),\n exclude.map((g) => g.compiled),\n budget,\n );\n}\n\n/** Whether every path `inner` matches is matched by one of `outer`, or `undecided`. */\nexport function globCovers(outer: readonly Glob[], inner: Glob, budget: number = WITNESS_BUDGET): boolean | 'undecided' {\n return coreCovers(\n outer.map((g) => g.compiled),\n inner.compiled,\n budget,\n );\n}\n\n/**\n * A path both globs match, or `null` when there is none: the 0.1 interface,\n * kept for the library's callers. It cannot say `undecided`, so a search that\n * meets its budget throws; {@link globWitness} answers in three ways.\n */\nexport function intersectGlobs(a: Glob, b: Glob, budget: number = WITNESS_BUDGET): string | null {\n const witness = globWitness([a, b], [], budget);\n if (witness.kind === 'undecided') {\n throw new Error(`whether \"${a.source}\" and \"${b.source}\" meet is undecided within the search's budget`);\n }\n return witness.kind === 'found' ? witness.path : null;\n}\n\n/**\n * The directories a walk must enter to find every match, one per brace\n * alternative: the leading literal segments, or a literal file's directory.\n * `''` for an alternative that can match at the root.\n */\nexport function globBases(glob: Glob): readonly string[] {\n return glob.compiled.bases;\n}\n\n/** The first of {@link globBases}: the 0.1 interface, kept for the library's callers. */\nexport function globBase(glob: Glob): string {\n // One base per alternative, and a pattern has at least one.\n return glob.compiled.bases[0] as string;\n}\n\n/** A brace alternative as its pattern writes it, and the index in the pattern where it ends. */\nexport interface WrittenAlternative {\n readonly written: string;\n readonly end: number;\n}\n\n/**\n * Each alternative of a pattern as written, in the order the core expands\n * them, and where each ends, when a `/` written there ends that alternative\n * and no other: the pattern itself when it has no braces, or the alternatives\n * of braces that end the pattern and whose own braces end theirs -\n * `lib/{util,new}`, `{a,b/{c,d}}`. `null` when more of the pattern follows\n * braces, `{a,b}/new`, since every alternative they give ends where the\n * pattern does; and for a pattern with a class, which may hold a brace or a\n * comma of its own and which this does not read.\n *\n * spec-core expands braces and keeps nothing of where an alternative was\n * written, and a note's advice is built from what was written, as the core\n * builds its own. So this reads braces as the expansion does, for a pattern\n * that parses: a `\\` escapes the next character, and a `}` with no `{` open\n * is a literal.\n */\nexport function writtenAlternatives(pattern: string): WrittenAlternative[] | null {\n let depth = 0;\n let open = 0;\n const stops: number[] = [];\n // A step past the end reads `''`, which no branch acts on, so the bound could be one further.\n for (let i = 0; i < pattern.length; i += 1) {\n const ch = pattern.charAt(i);\n if (ch === '\\\\') {\n i += 1;\n } else if (ch === '[') {\n return null;\n } else if (ch === '{') {\n if (depth === 0) open = i;\n depth += 1;\n } else if (ch === ',' && depth === 1) {\n stops.push(i);\n } else if (ch === '}' && depth > 0) {\n depth -= 1;\n if (depth === 0) return i === pattern.length - 1 ? optionsOf(pattern, open, [...stops, i]) : null;\n }\n }\n return [{ written: pattern, end: pattern.length }];\n}\n\n/** The alternatives of the braces opened at `open`, each option ending at one of `stops`. */\nfunction optionsOf(pattern: string, open: number, stops: readonly number[]): WrittenAlternative[] | null {\n const prefix = pattern.slice(0, open);\n const alternatives: WrittenAlternative[] = [];\n let start = open + 1;\n for (const stop of stops) {\n const inner = writtenAlternatives(pattern.slice(start, stop));\n if (inner === null) return null;\n for (const { written, end } of inner) alternatives.push({ written: prefix + written, end: start + end });\n start = stop + 1;\n }\n return alternatives;\n}\n\n/** A name with an extension, `login.ts` or `.eslintrc.json`, and not a dot-name such as `.github`. */\nexport function hasExtension(name: string): boolean {\n return /.\\.[^.]+$/.test(name);\n}\n\n/** The files a tree holds, and every directory above one. */\nexport interface Tree {\n readonly files: ReadonlySet<string>;\n readonly directories: ReadonlySet<string>;\n}\n\nconst trees = new WeakMap<readonly string[], Tree>();\n\n/** The tree a list of files describes. Built once per list, which every brief of a run shares. */\nexport function treeOf(files: readonly string[]): Tree {\n const known = trees.get(files);\n if (known !== undefined) return known;\n const directories = new Set<string>();\n for (const file of files) {\n for (let slash = file.indexOf('/'); slash !== -1; slash = file.indexOf('/', slash + 1)) directories.add(file.slice(0, slash));\n }\n const tree = { files: new Set(files), directories };\n trees.set(files, tree);\n return tree;\n}\n\n/** What the tree holds at a path: a file, a directory, or nothing. */\nexport function held(tree: Tree, path: string): 'file' | 'directory' | null {\n if (tree.files.has(path)) return 'file';\n return tree.directories.has(path) ? 'directory' : null;\n}\n\n/**\n * How a tree reads a literal path: a directory it holds is a directory, and\n * anything else is a file. Without a tree nothing is known to be a directory,\n * so every literal is a file; a trailing `/` says otherwise, and never reaches\n * this question.\n */\nexport function readingIn(files: readonly string[] | null): (path: string) => LiteralReading {\n if (files === null) return () => 'file';\n const tree = treeOf(files);\n return (path) => (held(tree, path) === 'directory' ? 'directory' : 'file');\n}\n"]}
package/dist/links.js CHANGED
@@ -40,7 +40,7 @@ export function isInside(path, directory) {
40
40
  }
41
41
  export function dirOf(path) {
42
42
  const slash = path.lastIndexOf('/');
43
- return slash < 0 ? '' : path.slice(0, slash);
43
+ return slash === -1 ? '' : path.slice(0, slash);
44
44
  }
45
45
  function parts(path) {
46
46
  return path.split('/').filter((p) => p !== '' && p !== '.');
@@ -65,6 +65,7 @@ export function relativePath(fromDirectory, to) {
65
65
  const from = parts(fromDirectory);
66
66
  const target = parts(to);
67
67
  let common = 0;
68
+ // One step past the end compares nothing with what is left of the target, and the slices below come out the same.
68
69
  while (common < from.length && from[common] === target[common])
69
70
  common += 1;
70
71
  const up = from.slice(common).map(() => '..');
package/dist/links.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"links.js","sourceRoot":"","sources":["../src/links.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,oEAAoE;AACpE,MAAM,UAAU,gBAAgB,CAAC,MAAc;IAC7C,IAAI,MAAM,KAAK,EAAE,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/G,OAAO,CAAC,2BAA2B,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnD,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAClC,OAAO,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AAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7E,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrB,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1B,CAAC;AAED,+FAA+F;AAC/F,MAAM,UAAU,cAAc,CAAC,OAAa,EAAE,SAAiB,EAAE,MAAc;IAC7E,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACjC,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC;YAAE,SAAS;QAC7C,MAAM,EAAE,IAAI,EAAE,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC1C,IAAI,IAAI,KAAK,EAAE,IAAI,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,MAAM;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3F,CAAC;IACD,2EAA2E;IAC3E,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AACpB,CAAC","sourcesContent":["/**\n * Relative links, and keeping them true when a file moves.\n *\n * Both repositories this tool was measured against archive a brief by moving\n * it one directory down and then adding `../` to its links by hand. A move\n * that breaks links is a defect the move introduced, so the move repairs them:\n * the file's own relative links, and the links other live briefs hold to it.\n */\n\nimport type { Scan } from './markdown.js';\n\n/** A destination that is a path relative to the file holding it. */\nexport function isRelativeTarget(target: string): boolean {\n if (target === '' || target.startsWith('#') || target.startsWith('/') || target.startsWith('\\\\')) return false;\n return !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(target);\n}\n\n/** The path part of a destination and whatever follows it: `?query` or `#fragment`. */\nexport function splitTarget(target: string): { readonly path: string; readonly suffix: string } {\n const cut = target.search(/[?#]/);\n return cut < 0 ? { path: target, suffix: '' } : { path: target.slice(0, cut), suffix: target.slice(cut) };\n}\n\n/** Normalises a repository-relative path and refuses one that leaves the repository. */\nexport function normalisePath(path: string): string {\n const out: string[] = [];\n for (const part of path.replace(/\\\\/g, '/').split('/')) {\n if (part === '' || part === '.') continue;\n if (part === '..') {\n if (out.length === 0) throw new Error(`\"${path}\" is outside the repository`);\n out.pop();\n continue;\n }\n out.push(part);\n }\n return out.join('/');\n}\n\n/** Whether a repository path lies inside a directory. */\nexport function isInside(path: string, directory: string): boolean {\n const dir = normalisePath(directory);\n return dir === '' || path === dir || path.startsWith(`${dir}/`);\n}\n\nexport function dirOf(path: string): string {\n const slash = path.lastIndexOf('/');\n return slash < 0 ? '' : path.slice(0, slash);\n}\n\nfunction parts(path: string): string[] {\n return path.split('/').filter((p) => p !== '' && p !== '.');\n}\n\n/** A relative path resolved against a directory, or `null` when it climbs out of the repository. */\nexport function resolveFrom(directory: string, relative: string): string | null {\n const out = parts(directory);\n for (const part of parts(relative)) {\n if (part === '..') {\n if (out.length === 0) return null;\n out.pop();\n } else {\n out.push(part);\n }\n }\n return out.join('/');\n}\n\n/** The relative path from a directory to a repository path. */\nexport function relativePath(fromDirectory: string, to: string): string {\n const from = parts(fromDirectory);\n const target = parts(to);\n let common = 0;\n while (common < from.length && from[common] === target[common]) common += 1;\n const up = from.slice(common).map(() => '..');\n const rest = target.slice(common);\n const joined = [...up, ...rest].join('/');\n return joined === '' ? '.' : joined;\n}\n\nfunction decode(path: string): string {\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\n/** Writes a path back in the encoding its original destination used. */\nfunction encodeLike(original: string, path: string): string {\n if (!original.includes('%')) return path;\n // encodeURIComponent leaves \".\" and \"..\" as they are.\n return path.split('/').map(encodeURIComponent).join('/');\n}\n\nexport interface LinkRewrite {\n readonly lines: string[];\n readonly count: number;\n}\n\n/**\n * Rewrites relative destinations for a file read from `directory` that will\n * be read from `newDirectory`. `retarget` maps the repository path a\n * destination resolves to now onto the one it should resolve to afterwards,\n * which differs only for a file that is itself moving.\n */\nexport function rewriteLinks(\n scanned: Scan,\n directory: string,\n newDirectory: string,\n retarget: (resolved: string) => string,\n): LinkRewrite {\n const lines = [...scanned.lines];\n let count = 0;\n const byLine = new Map<number, { start: number; end: number; replacement: string }[]>();\n for (const link of scanned.links) {\n if (!isRelativeTarget(link.target)) continue;\n const { path, suffix } = splitTarget(link.target);\n if (path === '') continue;\n const resolved = resolveFrom(directory, decode(path));\n if (resolved === null) continue;\n const destination = retarget(resolved);\n // A destination that still resolves where it should keeps its spelling.\n if (resolveFrom(newDirectory, decode(path)) === destination) continue;\n const relative = relativePath(newDirectory, destination);\n const trailing = path.endsWith('/') && relative !== '.' ? '/' : '';\n const replacement = `${encodeLike(path, relative)}${trailing}${suffix}`;\n byLine.set(link.line, [...(byLine.get(link.line) ?? []), { start: link.start, end: link.end, replacement }]);\n count += 1;\n }\n for (const [line, edits] of byLine) {\n let text = lines[line] as string;\n for (const edit of [...edits].sort((a, b) => b.start - a.start)) {\n text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);\n }\n lines[line] = text;\n }\n return { lines, count };\n}\n\n/** Lines of `scanned` holding a relative link that resolves, from `directory`, to `target`. */\nexport function linesLinkingTo(scanned: Scan, directory: string, target: string): number[] {\n const found = new Set<number>();\n for (const link of scanned.links) {\n if (!isRelativeTarget(link.target)) continue;\n const { path } = splitTarget(link.target);\n if (path !== '' && resolveFrom(directory, decode(path)) === target) found.add(link.line);\n }\n // Links come in the order of their lines, so the set is already ascending.\n return [...found];\n}\n"]}
1
+ {"version":3,"file":"links.js","sourceRoot":"","sources":["../src/links.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,oEAAoE;AACpE,MAAM,UAAU,gBAAgB,CAAC,MAAc;IAC7C,IAAI,MAAM,KAAK,EAAE,IAAI,MAAM,CAAC,UAAU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ves.\n *\n * Both repositories this tool was measured against archive a brief by moving\n * it one directory down and then adding `../` to its links by hand. A move\n * that breaks links is a defect the move introduced, so the move repairs them:\n * the file's own relative links, and the links other live briefs hold to it.\n */\n\nimport type { Scan } from './markdown.js';\n\n/** A destination that is a path relative to the file holding it. */\nexport function isRelativeTarget(target: string): boolean {\n if (target === '' || target.startsWith('#') || target.startsWith('/') || target.startsWith('\\\\')) return false;\n return !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(target);\n}\n\n/** The path part of a destination and whatever follows it: `?query` or `#fragment`. */\nexport function splitTarget(target: string): { readonly path: string; readonly suffix: string } {\n const cut = target.search(/[?#]/);\n return cut < 0 ? { path: target, suffix: '' } : { path: target.slice(0, cut), suffix: target.slice(cut) };\n}\n\n/** Normalises a repository-relative path and refuses one that leaves the repository. */\nexport function normalisePath(path: string): string {\n const out: string[] = [];\n for (const part of path.replace(/\\\\/g, '/').split('/')) {\n if (part === '' || part === '.') continue;\n if (part === '..') {\n if (out.length === 0) throw new Error(`\"${path}\" is outside the repository`);\n out.pop();\n continue;\n }\n out.push(part);\n }\n return out.join('/');\n}\n\n/** Whether a repository path lies inside a directory. */\nexport function isInside(path: string, directory: string): boolean {\n const dir = normalisePath(directory);\n return dir === '' || path === dir || path.startsWith(`${dir}/`);\n}\n\nexport function dirOf(path: string): string {\n const slash = path.lastIndexOf('/');\n return slash === -1 ? '' : path.slice(0, slash);\n}\n\nfunction parts(path: string): string[] {\n return path.split('/').filter((p) => p !== '' && p !== '.');\n}\n\n/** A relative path resolved against a directory, or `null` when it climbs out of the repository. */\nexport function resolveFrom(directory: string, relative: string): string | null {\n const out = parts(directory);\n for (const part of parts(relative)) {\n if (part === '..') {\n if (out.length === 0) return null;\n out.pop();\n } else {\n out.push(part);\n }\n }\n return out.join('/');\n}\n\n/** The relative path from a directory to a repository path. */\nexport function relativePath(fromDirectory: string, to: string): string {\n const from = parts(fromDirectory);\n const target = parts(to);\n let common = 0;\n // One step past the end compares nothing with what is left of the target, and the slices below come out the same.\n while (common < from.length && from[common] === target[common]) common += 1;\n const up = from.slice(common).map(() => '..');\n const rest = target.slice(common);\n const joined = [...up, ...rest].join('/');\n return joined === '' ? '.' : joined;\n}\n\nfunction decode(path: string): string {\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\n/** Writes a path back in the encoding its original destination used. */\nfunction encodeLike(original: string, path: string): string {\n if (!original.includes('%')) return path;\n // encodeURIComponent leaves \".\" and \"..\" as they are.\n return path.split('/').map(encodeURIComponent).join('/');\n}\n\nexport interface LinkRewrite {\n readonly lines: string[];\n readonly count: number;\n}\n\n/**\n * Rewrites relative destinations for a file read from `directory` that will\n * be read from `newDirectory`. `retarget` maps the repository path a\n * destination resolves to now onto the one it should resolve to afterwards,\n * which differs only for a file that is itself moving.\n */\nexport function rewriteLinks(\n scanned: Scan,\n directory: string,\n newDirectory: string,\n retarget: (resolved: string) => string,\n): LinkRewrite {\n const lines = [...scanned.lines];\n let count = 0;\n const byLine = new Map<number, { start: number; end: number; replacement: string }[]>();\n for (const link of scanned.links) {\n if (!isRelativeTarget(link.target)) continue;\n const { path, suffix } = splitTarget(link.target);\n if (path === '') continue;\n const resolved = resolveFrom(directory, decode(path));\n if (resolved === null) continue;\n const destination = retarget(resolved);\n // A destination that still resolves where it should keeps its spelling.\n if (resolveFrom(newDirectory, decode(path)) === destination) continue;\n const relative = relativePath(newDirectory, destination);\n const trailing = path.endsWith('/') && relative !== '.' ? '/' : '';\n const replacement = `${encodeLike(path, relative)}${trailing}${suffix}`;\n byLine.set(link.line, [...(byLine.get(link.line) ?? []), { start: link.start, end: link.end, replacement }]);\n count += 1;\n }\n for (const [line, edits] of byLine) {\n let text = lines[line] as string;\n for (const edit of [...edits].sort((a, b) => b.start - a.start)) {\n text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);\n }\n lines[line] = text;\n }\n return { lines, count };\n}\n\n/** Lines of `scanned` holding a relative link that resolves, from `directory`, to `target`. */\nexport function linesLinkingTo(scanned: Scan, directory: string, target: string): number[] {\n const found = new Set<number>();\n for (const link of scanned.links) {\n if (!isRelativeTarget(link.target)) continue;\n const { path } = splitTarget(link.target);\n if (path !== '' && resolveFrom(directory, decode(path)) === target) found.add(link.line);\n }\n // Links come in the order of their lines, so the set is already ascending.\n return [...found];\n}\n"]}
package/dist/lint.js CHANGED
@@ -6,6 +6,7 @@ import { ConfigError } from './config.js';
6
6
  import { analyse, ARCHIVE_RULES, COLLISION_RULES, RULES } from './rules.js';
7
7
  const RANK = { note: 0, warning: 1, error: 2 };
8
8
  function lower(a, b) {
9
+ // Equal ranks are one severity, so either is the answer.
9
10
  return RANK[a] <= RANK[b] ? a : b;
10
11
  }
11
12
  /** Every rule id a run knows: built-in, collision, archive and plugin. */
@@ -62,7 +63,7 @@ export async function lint(corpus, options = {}) {
62
63
  const configured = severity;
63
64
  findings.push({
64
65
  rule: id,
65
- severity: result.severity === undefined ? configured : lower(result.severity, configured),
66
+ severity: lower(result.severity ?? configured, configured),
66
67
  message: result.message,
67
68
  file: brief.file,
68
69
  line: Math.max(1, Math.trunc(result.line)),
@@ -77,9 +78,7 @@ export async function lint(corpus, options = {}) {
77
78
  }
78
79
  /** Strings by code unit, which is the same order on every host and in every locale. */
79
80
  function order(a, b) {
80
- if (a === b)
81
- return 0;
82
- return a < b ? -1 : 1;
81
+ return a < b ? -1 : a > b ? 1 : 0;
83
82
  }
84
83
  export function sortFindings(findings) {
85
84
  return [...findings].sort((a, b) => order(a.file, b.file) || a.line - b.line || order(a.rule, b.rule) || order(a.message, b.message));
package/dist/lint.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lint.js","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,eAAe,EAA4B,KAAK,EAAE,MAAM,YAAY,CAAC;AA4CtG,MAAM,IAAI,G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C,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,MAAM;QAC7D,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,MAAM;QACjE,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,MAAM;KAC5D,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,OAAO,CAAC,QAA4B,EAAE,MAAe;IACnE,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * Running rules: severities from the configuration, plugins beside the\n * built-in rules, findings in a stable order.\n */\n\nimport type { Waiver } from './archive.js';\nimport type { Brief } from './brief.js';\nimport { ConfigError } from './config.js';\nimport type { Corpus } from './corpus.js';\nimport { analyse, ARCHIVE_RULES, COLLISION_RULES, type Rule, type RuleInfo, RULES } from './rules.js';\nimport type { Finding, Severity, SeveritySetting } from './types.js';\n\n/** What a plugin's `waive` hook is asked about: one archival, refused. */\nexport interface WaiveContext {\n /** The absolute root: the directory holding the configuration. */\n readonly root: string;\n readonly brief: { readonly id: string | null; readonly file: string; readonly text: string };\n /**\n * Every finding that refuses the archival, as a frozen copy: writing to it\n * throws, and the waivers are matched against the plan's own. A\n * `protected-file` finding names its `path`; an `out-of-scope` one lists its\n * `paths`. Only those two can be waived.\n */\n readonly findings: readonly Finding[];\n /** The base the round is measured from, as it was given; `null` when none was. */\n readonly base: string | null;\n /** The commit the round landed as; `null` when none was read. */\n readonly commit: string | null;\n}\n\nexport interface Plugin {\n /** Prefixes the plugin's rule ids: `<name>/<rule>`. */\n readonly name: string;\n readonly rules: readonly Rule[];\n /** The plugin's entry in the configuration, handed to each rule. */\n readonly options?: unknown;\n /**\n * Lifts refusals of an archival that the plugin's own check allows - a\n * protected file a verified ruling covers - by rule and path. Asked only\n * when the plan has a refusal it could lift. Returning nothing waives\n * nothing.\n */\n readonly waive?: ((context: WaiveContext) => readonly Waiver[] | void | Promise<readonly Waiver[] | void>) | undefined;\n}\n\nexport interface LintOptions {\n readonly plugins?: readonly Plugin[];\n /** Tracked files, for the rules that read the tree. */\n readonly repoFiles?: readonly string[] | null;\n /** Limit the findings to these briefs. The whole corpus is still read. */\n readonly only?: readonly Brief[];\n}\n\nconst RANK: Readonly<Record<Severity, number>> = { note: 0, warning: 1, error: 2 };\n\nfunction lower(a: Severity, b: Severity): Severity {\n return RANK[a] <= RANK[b] ? a : b;\n}\n\ninterface ActiveRule {\n readonly id: string;\n readonly rule: Rule;\n readonly severity: SeveritySetting;\n readonly options: unknown;\n}\n\n/** Every rule id a run knows: built-in, collision, archive and plugin. */\nexport function ruleIds(plugins: readonly Plugin[] = []): string[] {\n return [\n ...RULES.map((r) => r.id),\n ...COLLISION_RULES.map((r) => r.id),\n ...ARCHIVE_RULES.map((r) => r.id),\n ...plugins.flatMap((p) => p.rules.map((r) => `${p.name}/${r.id}`)),\n ];\n}\n\n/** The severity configuration assigns a rule, or its own. */\nexport function severityOf(corpus: Corpus, id: string, fallback: SeveritySetting): SeveritySetting {\n return corpus.config.rules[id] ?? fallback;\n}\n\n/** The severity of a built-in rule as configured, or `null` when it is off. */\nexport function configuredSeverity(corpus: Corpus, id: string): Severity | null {\n const rule = [...RULES, ...COLLISION_RULES, ...ARCHIVE_RULES].find((r) => r.id === id) as RuleInfo;\n const setting = severityOf(corpus, id, rule.severity);\n return setting === 'off' ? null : setting;\n}\n\n/** Refuses a configuration that names a rule nobody defines: a typo there silences nothing. */\nexport function checkRuleIds(corpus: Corpus, plugins: readonly Plugin[] = []): void {\n const known = new Set(ruleIds(plugins));\n const unknown = Object.keys(corpus.config.rules).filter((id) => !known.has(id));\n if (unknown.length > 0) {\n throw new ConfigError('configuration', unknown.map((id) => `\"rules.${id}\" names no rule`));\n }\n}\n\nexport async function lint(corpus: Corpus, options: LintOptions = {}): Promise<Finding[]> {\n const plugins = options.plugins ?? [];\n checkRuleIds(corpus, plugins);\n const active: ActiveRule[] = [\n ...RULES.map((rule) => ({ id: rule.id, rule, severity: severityOf(corpus, rule.id, rule.severity), options: undefined })),\n ...plugins.flatMap((plugin) =>\n plugin.rules.map((rule) => {\n const id = `${plugin.name}/${rule.id}`;\n return { id, rule, severity: severityOf(corpus, id, rule.severity), options: plugin.options };\n }),\n ),\n ].filter((r) => r.severity !== 'off');\n\n const shared = analyse(corpus);\n const targets = options.only ?? corpus.briefs;\n const findings: Finding[] = [];\n for (const brief of targets) {\n for (const { id, rule, severity, options: ruleOptions } of active) {\n const results = await rule.check({\n brief,\n corpus,\n config: corpus.config,\n repoFiles: options.repoFiles ?? null,\n shared,\n options: ruleOptions,\n });\n for (const result of results) {\n const configured = severity as Severity;\n findings.push({\n rule: id,\n severity: result.severity === undefined ? configured : lower(result.severity, configured),\n message: result.message,\n file: brief.file,\n line: Math.max(1, Math.trunc(result.line)),\n brief: brief.id ?? undefined,\n hint: result.hint,\n subject: result.subject,\n });\n }\n }\n }\n return sortFindings(findings);\n}\n\n/** Strings by code unit, which is the same order on every host and in every locale. */\nfunction order(a: string, b: string): number {\n if (a === b) return 0;\n return a < b ? -1 : 1;\n}\n\nexport function sortFindings(findings: readonly Finding[]): Finding[] {\n return [...findings].sort(\n (a, b) => order(a.file, b.file) || a.line - b.line || order(a.rule, b.rule) || order(a.message, b.message),\n );\n}\n\nexport interface Summary {\n readonly errors: number;\n readonly warnings: number;\n readonly notes: number;\n}\n\nexport function summarise(findings: readonly Finding[]): Summary {\n return {\n errors: findings.filter((f) => f.severity === 'error').length,\n warnings: findings.filter((f) => f.severity === 'warning').length,\n notes: findings.filter((f) => f.severity === 'note').length,\n };\n}\n\n/** Whether findings fail a run: any error, or any warning under `--strict`. */\nexport function failing(findings: readonly Finding[], strict: boolean): boolean {\n return findings.some((f) => f.severity === 'error' || (strict && f.severity === 'warning'));\n}\n"]}
1
+ {"version":3,"file":"lint.js","sourceRoot":"","sources":["../src/lint.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,eAAe,EAA4B,KAAK,EAAE,MAAM,YAAY,CAAC;AA4CtG,MAAM,IAAI,GAAuC,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAEnF,SAAS,KAAK,CAAC,CAAW,EAAE,CAAW;IACrC,yDAAyD;IACzD,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACpC,CAAC;AASD,0EAA0E;AAC1E,MAAM,UAAU,OAAO,CAAC,OAAO,GAAsB,EAAE;IACrD,OAAO;QACL,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzB,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACnC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,6DAA6D;AA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AC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,CAC3G,CAAC;AACJ,CAAC;AAQD,MAAM,UAAU,SAAS,CAAC,QAA4B;IACpD,OAAO;QACL,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,MAAM;QAC7D,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,MAAM;QACjE,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,MAAM;KAC5D,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,OAAO,CAAC,QAA4B,EAAE,MAAe;IACnE,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * Running rules: severities from the configuration, plugins beside the\n * built-in rules, findings in a stable order.\n */\n\nimport type { Waiver } from './archive.js';\nimport type { Brief } from './brief.js';\nimport { ConfigError } from './config.js';\nimport type { Corpus } from './corpus.js';\nimport { analyse, ARCHIVE_RULES, COLLISION_RULES, type Rule, type RuleInfo, RULES } from './rules.js';\nimport type { Finding, Severity, SeveritySetting } from './types.js';\n\n/** What a plugin's `waive` hook is asked about: one archival, refused. */\nexport interface WaiveContext {\n /** The absolute root: the directory holding the configuration. */\n readonly root: string;\n readonly brief: { readonly id: string | null; readonly file: string; readonly text: string };\n /**\n * Every finding that refuses the archival, as a frozen copy: writing to it\n * throws, and the waivers are matched against the plan's own. A\n * `protected-file` finding names its `path`; an `out-of-scope` one lists its\n * `paths`. Only those two can be waived.\n */\n readonly findings: readonly Finding[];\n /** The base the round is measured from, as it was given; `null` when none was. */\n readonly base: string | null;\n /** The commit the round landed as; `null` when none was read. */\n readonly commit: string | null;\n}\n\nexport interface Plugin {\n /** Prefixes the plugin's rule ids: `<name>/<rule>`. */\n readonly name: string;\n readonly rules: readonly Rule[];\n /** The plugin's entry in the configuration, handed to each rule. */\n readonly options?: unknown;\n /**\n * Lifts refusals of an archival that the plugin's own check allows - a\n * protected file a verified ruling covers - by rule and path. Asked only\n * when the plan has a refusal it could lift. Returning nothing waives\n * nothing.\n */\n readonly waive?: ((context: WaiveContext) => readonly Waiver[] | void | Promise<readonly Waiver[] | void>) | undefined;\n}\n\nexport interface LintOptions {\n readonly plugins?: readonly Plugin[];\n /** Tracked files, for the rules that read the tree. */\n readonly repoFiles?: readonly string[] | null;\n /** Limit the findings to these briefs. The whole corpus is still read. */\n readonly only?: readonly Brief[];\n}\n\nconst RANK: Readonly<Record<Severity, number>> = { note: 0, warning: 1, error: 2 };\n\nfunction lower(a: Severity, b: Severity): Severity {\n // Equal ranks are one severity, so either is the answer.\n return RANK[a] <= RANK[b] ? a : b;\n}\n\ninterface ActiveRule {\n readonly id: string;\n readonly rule: Rule;\n readonly severity: SeveritySetting;\n readonly options: unknown;\n}\n\n/** Every rule id a run knows: built-in, collision, archive and plugin. */\nexport function ruleIds(plugins: readonly Plugin[] = []): string[] {\n return [\n ...RULES.map((r) => r.id),\n ...COLLISION_RULES.map((r) => r.id),\n ...ARCHIVE_RULES.map((r) => r.id),\n ...plugins.flatMap((p) => p.rules.map((r) => `${p.name}/${r.id}`)),\n ];\n}\n\n/** The severity configuration assigns a rule, or its own. */\nexport function severityOf(corpus: Corpus, id: string, fallback: SeveritySetting): SeveritySetting {\n return corpus.config.rules[id] ?? fallback;\n}\n\n/** The severity of a built-in rule as configured, or `null` when it is off. */\nexport function configuredSeverity(corpus: Corpus, id: string): Severity | null {\n const rule = [...RULES, ...COLLISION_RULES, ...ARCHIVE_RULES].find((r) => r.id === id) as RuleInfo;\n const setting = severityOf(corpus, id, rule.severity);\n return setting === 'off' ? null : setting;\n}\n\n/** Refuses a configuration that names a rule nobody defines: a typo there silences nothing. */\nexport function checkRuleIds(corpus: Corpus, plugins: readonly Plugin[] = []): void {\n const known = new Set(ruleIds(plugins));\n const unknown = Object.keys(corpus.config.rules).filter((id) => !known.has(id));\n if (unknown.length > 0) {\n throw new ConfigError('configuration', unknown.map((id) => `\"rules.${id}\" names no rule`));\n }\n}\n\nexport async function lint(corpus: Corpus, options: LintOptions = {}): Promise<Finding[]> {\n const plugins = options.plugins ?? [];\n checkRuleIds(corpus, plugins);\n const active: ActiveRule[] = [\n ...RULES.map((rule) => ({ id: rule.id, rule, severity: severityOf(corpus, rule.id, rule.severity), options: undefined })),\n ...plugins.flatMap((plugin) =>\n plugin.rules.map((rule) => {\n const id = `${plugin.name}/${rule.id}`;\n return { id, rule, severity: severityOf(corpus, id, rule.severity), options: plugin.options };\n }),\n ),\n ].filter((r) => r.severity !== 'off');\n\n const shared = analyse(corpus);\n const targets = options.only ?? corpus.briefs;\n const findings: Finding[] = [];\n for (const brief of targets) {\n for (const { id, rule, severity, options: ruleOptions } of active) {\n const results = await rule.check({\n brief,\n corpus,\n config: corpus.config,\n repoFiles: options.repoFiles ?? null,\n shared,\n options: ruleOptions,\n });\n for (const result of results) {\n const configured = severity as Severity;\n findings.push({\n rule: id,\n severity: lower(result.severity ?? configured, configured),\n message: result.message,\n file: brief.file,\n line: Math.max(1, Math.trunc(result.line)),\n brief: brief.id ?? undefined,\n hint: result.hint,\n subject: result.subject,\n });\n }\n }\n }\n return sortFindings(findings);\n}\n\n/** Strings by code unit, which is the same order on every host and in every locale. */\nfunction order(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nexport function sortFindings(findings: readonly Finding[]): Finding[] {\n return [...findings].sort(\n (a, b) => order(a.file, b.file) || a.line - b.line || order(a.rule, b.rule) || order(a.message, b.message),\n );\n}\n\nexport interface Summary {\n readonly errors: number;\n readonly warnings: number;\n readonly notes: number;\n}\n\nexport function summarise(findings: readonly Finding[]): Summary {\n return {\n errors: findings.filter((f) => f.severity === 'error').length,\n warnings: findings.filter((f) => f.severity === 'warning').length,\n notes: findings.filter((f) => f.severity === 'note').length,\n };\n}\n\n/** Whether findings fail a run: any error, or any warning under `--strict`. */\nexport function failing(findings: readonly Finding[], strict: boolean): boolean {\n return findings.some((f) => f.severity === 'error' || (strict && f.severity === 'warning'));\n}\n"]}
package/dist/plugins.js CHANGED
@@ -60,7 +60,8 @@ function exportTarget(value, match) {
60
60
  * longest prefix, and of those the longest key.
61
61
  */
62
62
  export function exportsTarget(exports, subpath) {
63
- const keys = typeof exports === 'object' && exports !== null && !Array.isArray(exports) ? Object.keys(exports) : [];
63
+ // Only a map of subpaths has a key that starts with a dot: a path's and a list's keys are their indices.
64
+ const keys = Object.keys(Object(exports));
64
65
  const dotted = keys.filter((key) => key.startsWith('.'));
65
66
  if (dotted.length === 0)
66
67
  return subpath === '.' ? (exportTarget(exports, null) ?? null) : null;
@@ -73,11 +74,12 @@ export function exportsTarget(exports, subpath) {
73
74
  let best;
74
75
  for (const key of dotted) {
75
76
  const star = key.indexOf('*');
76
- if (star < 0 || key.includes('*', star + 1))
77
+ if (star === -1 || key.includes('*', star + 1))
77
78
  continue;
78
79
  const suffix = key.slice(star + 1);
79
80
  if (subpath.length < key.length || !subpath.startsWith(key.slice(0, star)) || !subpath.endsWith(suffix))
80
81
  continue;
82
+ // Two keys of one prefix and one length that both match are one key, so the lengths never tie.
81
83
  if (best === undefined || star > best.prefix || (star === best.prefix && key.length > best.key.length)) {
82
84
  best = { key, prefix: star, match: subpath.slice(star, subpath.length - suffix.length) };
83
85
  }
@@ -106,10 +108,12 @@ async function manifest(path) {
106
108
  */
107
109
  async function resolvePackage(specifier, root) {
108
110
  const slash = specifier.indexOf('/', specifier.startsWith('@') ? specifier.indexOf('/') + 1 : 0);
109
- const name = slash < 0 ? specifier : specifier.slice(0, slash);
110
- const subpath = slash < 0 ? '.' : `.${specifier.slice(slash)}`;
111
+ const name = slash === -1 ? specifier : specifier.slice(0, slash);
112
+ const subpath = slash === -1 ? '.' : `.${specifier.slice(slash)}`;
111
113
  let directory = root;
112
- // Bounded by the depth of the path: each pass moves one directory up.
114
+ // Bounded by the depth of the path: each pass moves one directory up, and
115
+ // the search stops at the top, so no path reaches the bound and one pass
116
+ // more or fewer of it is the same search.
113
117
  for (let depth = 0; depth < 256; depth += 1) {
114
118
  const packageDirectory = join(directory, 'node_modules', name);
115
119
  const found = await manifest(join(packageDirectory, 'package.json'));
@@ -122,6 +126,7 @@ async function resolvePackage(specifier, root) {
122
126
  return join(packageDirectory, target);
123
127
  }
124
128
  const parent = dirname(directory);
129
+ // Stopping at the top saves asking it again until the bound: the answer is the same.
125
130
  if (parent === directory)
126
131
  break;
127
132
  directory = parent;
@@ -140,7 +145,6 @@ function isRule(value) {
140
145
  return (typeof rule['id'] === 'string' &&
141
146
  /^[a-z0-9][a-z0-9-]*$/.test(rule['id']) &&
142
147
  typeof rule['description'] === 'string' &&
143
- typeof rule['severity'] === 'string' &&
144
148
  SEVERITIES.has(rule['severity']) &&
145
149
  typeof rule['check'] === 'function');
146
150
  }
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.js","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAA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AAC,SAAS,EAAE,CAAC,0BAA0B,QAAQ,CAAC,CAAC,CAAW,GAAG,CAAC,CAAC,CAAC;IAChH,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * Loading rule plugins named by the configuration.\n *\n * spec-brief does not know how another tool signs a departure, records a\n * reproducer or measures a blast radius, and should not: the tool that\n * defines a format is the one that can check it. A plugin is a module whose\n * default export is a plugin object, or a function of the configured options\n * that returns one. Loading one runs its code, exactly as loading an ESLint\n * configuration does; the configuration belongs to the repository, and so\n * does that trust.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport type { Waiver } from './archive.js';\nimport type { PluginReference } from './config.js';\nimport { ConfigError } from './config.js';\nimport type { Plugin } from './lint.js';\nimport type { Rule } from './rules.js';\n\nconst SEVERITIES = new Set(['off', 'note', 'warning', 'error']);\n\n/** The conditions Node matches in \"exports\" when it imports a module. */\nconst IMPORT_CONDITIONS = new Set(['node', 'import', 'module-sync', 'default']);\n\n/**\n * A target of \"exports\": a path inside the package, `null` where the package\n * refuses the subpath, `undefined` where no condition matched and a fallback\n * may still. A target that is not a \"./\" path, or that climbs out of the\n * package or into another, is refused, as Node refuses it: its segments are\n * split on a backslash too, since `join` reads one as a separator on Windows,\n * where \"pkg/..\\..\\outside\" would otherwise climb out of node_modules.\n */\nfunction exportTarget(value: unknown, match: string | null): string | null | undefined {\n if (typeof value === 'string') {\n if (!value.startsWith('./')) return null;\n const path = match === null ? value : value.replaceAll('*', match);\n const parts = path.slice(2).split(/[\\\\/]/);\n return parts.some((part) => part === '..' || part === '.' || part.toLowerCase() === 'node_modules') ? null : path;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n const path = exportTarget(item, match);\n if (typeof path === 'string') return path;\n }\n return null;\n }\n if (typeof value === 'object' && value !== null) {\n for (const [condition, item] of Object.entries(value)) {\n if (!IMPORT_CONDITIONS.has(condition)) continue;\n const path = exportTarget(item, match);\n if (path !== undefined) return path;\n }\n return undefined;\n }\n return null;\n}\n\n/**\n * The file a package's \"exports\" gives a subpath (`.` or `./x`) under the\n * conditions of an import, or `null` when it gives none: Node's\n * PACKAGE_EXPORTS_RESOLVE. An exact key wins; then the \"*\" pattern with the\n * longest prefix, and of those the longest key.\n */\nexport function exportsTarget(exports: unknown, subpath: string): string | null {\n const keys = typeof exports === 'object' && exports !== null && !Array.isArray(exports) ? Object.keys(exports) : [];\n const dotted = keys.filter((key) => key.startsWith('.'));\n if (dotted.length === 0) return subpath === '.' ? (exportTarget(exports, null) ?? null) : null;\n // Subpaths beside conditions is a package Node refuses to read.\n if (dotted.length !== keys.length) return null;\n const map = exports as Record<string, unknown>;\n if (!subpath.includes('*') && Object.hasOwn(map, subpath)) return exportTarget(map[subpath], null) ?? null;\n let best: { readonly key: string; readonly prefix: number; readonly match: string } | undefined;\n for (const key of dotted) {\n const star = key.indexOf('*');\n if (star < 0 || key.includes('*', star + 1)) continue;\n const suffix = key.slice(star + 1);\n if (subpath.length < key.length || !subpath.startsWith(key.slice(0, star)) || !subpath.endsWith(suffix)) continue;\n if (best === undefined || star > best.prefix || (star === best.prefix && key.length > best.key.length)) {\n best = { key, prefix: star, match: subpath.slice(star, subpath.length - suffix.length) };\n }\n }\n return best === undefined ? null : (exportTarget(map[best.key], best.match) ?? null);\n}\n\n/** A package.json, `undefined` when there is none to read. */\nasync function manifest(path: string): Promise<Record<string, unknown> | undefined> {\n try {\n return JSON.parse(await readFile(path, 'utf8')) as Record<string, unknown>;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return undefined;\n throw error;\n }\n}\n\n/**\n * The file a package specifier names, found from the root the way an import\n * there would find it. `require.resolve` reads \"exports\" under the require\n * conditions, so a package that exports only for \"import\" - an ESM-only\n * plugin - could not be found; Node's `import.meta.resolve` resolves only\n * from the module calling it, not from the root. So the nearest\n * node_modules/<name> is found here and its \"exports\" read under the import\n * conditions; a package with no \"exports\" resolves as it always has.\n */\nasync function resolvePackage(specifier: string, root: string): Promise<string> {\n const slash = specifier.indexOf('/', specifier.startsWith('@') ? specifier.indexOf('/') + 1 : 0);\n const name = slash < 0 ? specifier : specifier.slice(0, slash);\n const subpath = slash < 0 ? '.' : `.${specifier.slice(slash)}`;\n let directory = root;\n // Bounded by the depth of the path: each pass moves one directory up.\n for (let depth = 0; depth < 256; depth += 1) {\n const packageDirectory = join(directory, 'node_modules', name);\n const found = await manifest(join(packageDirectory, 'package.json'));\n if (found !== undefined) {\n if (found['exports'] === undefined || found['exports'] === null) break;\n const target = exportsTarget(found['exports'], subpath);\n if (target === null) throw new Error(`${name} exports no \"${subpath}\" for import`);\n return join(packageDirectory, target);\n }\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n return createRequire(join(root, 'package.json')).resolve(specifier);\n}\n\nasync function specifierUrl(specifier: string, root: string): Promise<string> {\n if (specifier.startsWith('.') || isAbsolute(specifier)) return pathToFileURL(resolve(root, specifier)).href;\n return pathToFileURL(await resolvePackage(specifier, root)).href;\n}\n\nfunction isRule(value: unknown): value is Rule {\n if (typeof value !== 'object' || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule['id'] === 'string' &&\n /^[a-z0-9][a-z0-9-]*$/.test(rule['id']) &&\n typeof rule['description'] === 'string' &&\n typeof rule['severity'] === 'string' &&\n SEVERITIES.has(rule['severity']) &&\n typeof rule['check'] === 'function'\n );\n}\n\n/** Checks the shape a module exported, since nothing typed it on the way in. */\nexport function asPlugin(value: unknown, module: string, options: unknown): Plugin {\n const problems: string[] = [];\n if (typeof value !== 'object' || value === null) {\n throw new ConfigError(module, ['does not export a plugin: expected an object with \"name\" and \"rules\"']);\n }\n const candidate = value as Record<string, unknown>;\n const name = candidate['name'];\n const rules = candidate['rules'];\n const waive = candidate['waive'];\n if (typeof name !== 'string' || !/^[a-z0-9@][a-z0-9@/._-]*$/i.test(name)) problems.push('\"name\" must be a plain identifier');\n if (!Array.isArray(rules)) problems.push('\"rules\" must be a list');\n else {\n rules.forEach((rule, i) => {\n if (!isRule(rule)) problems.push(`rules[${i}] needs a lower-case \"id\", a \"description\", a \"severity\" and a \"check\" function`);\n });\n }\n if (waive !== undefined && typeof waive !== 'function') problems.push('\"waive\" must be a function');\n if (problems.length > 0) throw new ConfigError(module, problems);\n const plugin: Plugin = { name: name as string, rules: rules as Rule[], options };\n return waive === undefined ? plugin : { ...plugin, waive: waive as NonNullable<Plugin['waive']> };\n}\n\n/**\n * Checks what a `waive` hook returned: a list of `{ rule, path, reason }`,\n * each a string. A hook that returns nothing waives nothing: a function that\n * found no ruling and fell off its end has answered, not failed.\n */\nexport function asWaivers(value: unknown, plugin: string): Waiver[] {\n const isWaiver = (item: unknown): item is Waiver => {\n if (typeof item !== 'object' || item === null) return false;\n const w = item as Record<string, unknown>;\n return typeof w['rule'] === 'string' && typeof w['path'] === 'string' && typeof w['reason'] === 'string';\n };\n if (value === undefined) return [];\n if (!Array.isArray(value) || !value.every(isWaiver)) {\n throw new ConfigError(`plugin \"${plugin}\"`, ['\"waive\" must return a list of { rule, path, reason }, each a string']);\n }\n return value.map((w) => ({ rule: w.rule, path: w.path, reason: w.reason }));\n}\n\nexport async function loadPlugins(references: readonly PluginReference[], root: string): Promise<Plugin[]> {\n const plugins: Plugin[] = [];\n for (const reference of references) {\n let loaded: Record<string, unknown>;\n try {\n loaded = (await import(await specifierUrl(reference.module, root))) as Record<string, unknown>;\n } catch (error) {\n throw new ConfigError(reference.module, [`could not be loaded: ${(error as Error).message}`]);\n }\n const exported = loaded['default'] ?? loaded['plugin'];\n const value = typeof exported === 'function' ? await (exported as (o: unknown) => unknown)(reference.options) : exported;\n plugins.push(asPlugin(value, reference.module, reference.options));\n }\n const names = plugins.map((p) => p.name);\n const repeated = names.filter((n, i) => names.indexOf(n) !== i);\n if (repeated.length > 0) throw new ConfigError('plugins', [`two plugins are named \"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,CAAC,CAAC,IAAI,CAAC,CAAC;IACzC,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAChE,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,WAAW,CAAC,SAAS,EAAE,CAAC,0BAA0B,QAAQ,CAAC,CAAC,CAAW,GAAG,CAAC,CAAC,CAAC;IAChH,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/**\n * Loading rule plugins named by the configuration.\n *\n * spec-brief does not know how another tool signs a departure, records a\n * reproducer or measures a blast radius, and should not: the tool that\n * defines a format is the one that can check it. A plugin is a module whose\n * default export is a plugin object, or a function of the configured options\n * that returns one. Loading one runs its code, exactly as loading an ESLint\n * configuration does; the configuration belongs to the repository, and so\n * does that trust.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport type { Waiver } from './archive.js';\nimport type { PluginReference } from './config.js';\nimport { ConfigError } from './config.js';\nimport type { Plugin } from './lint.js';\nimport type { Rule } from './rules.js';\n\nconst SEVERITIES = new Set(['off', 'note', 'warning', 'error']);\n\n/** The conditions Node matches in \"exports\" when it imports a module. */\nconst IMPORT_CONDITIONS = new Set(['node', 'import', 'module-sync', 'default']);\n\n/**\n * A target of \"exports\": a path inside the package, `null` where the package\n * refuses the subpath, `undefined` where no condition matched and a fallback\n * may still. A target that is not a \"./\" path, or that climbs out of the\n * package or into another, is refused, as Node refuses it: its segments are\n * split on a backslash too, since `join` reads one as a separator on Windows,\n * where \"pkg/..\\..\\outside\" would otherwise climb out of node_modules.\n */\nfunction exportTarget(value: unknown, match: string | null): string | null | undefined {\n if (typeof value === 'string') {\n if (!value.startsWith('./')) return null;\n const path = match === null ? value : value.replaceAll('*', match);\n const parts = path.slice(2).split(/[\\\\/]/);\n return parts.some((part) => part === '..' || part === '.' || part.toLowerCase() === 'node_modules') ? null : path;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n const path = exportTarget(item, match);\n if (typeof path === 'string') return path;\n }\n return null;\n }\n if (typeof value === 'object' && value !== null) {\n for (const [condition, item] of Object.entries(value)) {\n if (!IMPORT_CONDITIONS.has(condition)) continue;\n const path = exportTarget(item, match);\n if (path !== undefined) return path;\n }\n return undefined;\n }\n return null;\n}\n\n/**\n * The file a package's \"exports\" gives a subpath (`.` or `./x`) under the\n * conditions of an import, or `null` when it gives none: Node's\n * PACKAGE_EXPORTS_RESOLVE. An exact key wins; then the \"*\" pattern with the\n * longest prefix, and of those the longest key.\n */\nexport function exportsTarget(exports: unknown, subpath: string): string | null {\n // Only a map of subpaths has a key that starts with a dot: a path's and a list's keys are their indices.\n const keys = Object.keys(Object(exports) as object);\n const dotted = keys.filter((key) => key.startsWith('.'));\n if (dotted.length === 0) return subpath === '.' ? (exportTarget(exports, null) ?? null) : null;\n // Subpaths beside conditions is a package Node refuses to read.\n if (dotted.length !== keys.length) return null;\n const map = exports as Record<string, unknown>;\n if (!subpath.includes('*') && Object.hasOwn(map, subpath)) return exportTarget(map[subpath], null) ?? null;\n let best: { readonly key: string; readonly prefix: number; readonly match: string } | undefined;\n for (const key of dotted) {\n const star = key.indexOf('*');\n if (star === -1 || key.includes('*', star + 1)) continue;\n const suffix = key.slice(star + 1);\n if (subpath.length < key.length || !subpath.startsWith(key.slice(0, star)) || !subpath.endsWith(suffix)) continue;\n // Two keys of one prefix and one length that both match are one key, so the lengths never tie.\n if (best === undefined || star > best.prefix || (star === best.prefix && key.length > best.key.length)) {\n best = { key, prefix: star, match: subpath.slice(star, subpath.length - suffix.length) };\n }\n }\n return best === undefined ? null : (exportTarget(map[best.key], best.match) ?? null);\n}\n\n/** A package.json, `undefined` when there is none to read. */\nasync function manifest(path: string): Promise<Record<string, unknown> | undefined> {\n try {\n return JSON.parse(await readFile(path, 'utf8')) as Record<string, unknown>;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT' || (error as NodeJS.ErrnoException).code === 'ENOTDIR') return undefined;\n throw error;\n }\n}\n\n/**\n * The file a package specifier names, found from the root the way an import\n * there would find it. `require.resolve` reads \"exports\" under the require\n * conditions, so a package that exports only for \"import\" - an ESM-only\n * plugin - could not be found; Node's `import.meta.resolve` resolves only\n * from the module calling it, not from the root. So the nearest\n * node_modules/<name> is found here and its \"exports\" read under the import\n * conditions; a package with no \"exports\" resolves as it always has.\n */\nasync function resolvePackage(specifier: string, root: string): Promise<string> {\n const slash = specifier.indexOf('/', specifier.startsWith('@') ? specifier.indexOf('/') + 1 : 0);\n const name = slash === -1 ? specifier : specifier.slice(0, slash);\n const subpath = slash === -1 ? '.' : `.${specifier.slice(slash)}`;\n let directory = root;\n // Bounded by the depth of the path: each pass moves one directory up, and\n // the search stops at the top, so no path reaches the bound and one pass\n // more or fewer of it is the same search.\n for (let depth = 0; depth < 256; depth += 1) {\n const packageDirectory = join(directory, 'node_modules', name);\n const found = await manifest(join(packageDirectory, 'package.json'));\n if (found !== undefined) {\n if (found['exports'] === undefined || found['exports'] === null) break;\n const target = exportsTarget(found['exports'], subpath);\n if (target === null) throw new Error(`${name} exports no \"${subpath}\" for import`);\n return join(packageDirectory, target);\n }\n const parent = dirname(directory);\n // Stopping at the top saves asking it again until the bound: the answer is the same.\n if (parent === directory) break;\n directory = parent;\n }\n return createRequire(join(root, 'package.json')).resolve(specifier);\n}\n\nasync function specifierUrl(specifier: string, root: string): Promise<string> {\n if (specifier.startsWith('.') || isAbsolute(specifier)) return pathToFileURL(resolve(root, specifier)).href;\n return pathToFileURL(await resolvePackage(specifier, root)).href;\n}\n\nfunction isRule(value: unknown): value is Rule {\n if (typeof value !== 'object' || value === null) return false;\n const rule = value as Record<string, unknown>;\n return (\n typeof rule['id'] === 'string' &&\n /^[a-z0-9][a-z0-9-]*$/.test(rule['id']) &&\n typeof rule['description'] === 'string' &&\n SEVERITIES.has(rule['severity'] as string) &&\n typeof rule['check'] === 'function'\n );\n}\n\n/** Checks the shape a module exported, since nothing typed it on the way in. */\nexport function asPlugin(value: unknown, module: string, options: unknown): Plugin {\n const problems: string[] = [];\n if (typeof value !== 'object' || value === null) {\n throw new ConfigError(module, ['does not export a plugin: expected an object with \"name\" and \"rules\"']);\n }\n const candidate = value as Record<string, unknown>;\n const name = candidate['name'];\n const rules = candidate['rules'];\n const waive = candidate['waive'];\n if (typeof name !== 'string' || !/^[a-z0-9@][a-z0-9@/._-]*$/i.test(name)) problems.push('\"name\" must be a plain identifier');\n if (!Array.isArray(rules)) problems.push('\"rules\" must be a list');\n else {\n rules.forEach((rule, i) => {\n if (!isRule(rule)) problems.push(`rules[${i}] needs a lower-case \"id\", a \"description\", a \"severity\" and a \"check\" function`);\n });\n }\n if (waive !== undefined && typeof waive !== 'function') problems.push('\"waive\" must be a function');\n if (problems.length > 0) throw new ConfigError(module, problems);\n const plugin: Plugin = { name: name as string, rules: rules as Rule[], options };\n return waive === undefined ? plugin : { ...plugin, waive: waive as NonNullable<Plugin['waive']> };\n}\n\n/**\n * Checks what a `waive` hook returned: a list of `{ rule, path, reason }`,\n * each a string. A hook that returns nothing waives nothing: a function that\n * found no ruling and fell off its end has answered, not failed.\n */\nexport function asWaivers(value: unknown, plugin: string): Waiver[] {\n const isWaiver = (item: unknown): item is Waiver => {\n if (typeof item !== 'object' || item === null) return false;\n const w = item as Record<string, unknown>;\n return typeof w['rule'] === 'string' && typeof w['path'] === 'string' && typeof w['reason'] === 'string';\n };\n if (value === undefined) return [];\n if (!Array.isArray(value) || !value.every(isWaiver)) {\n throw new ConfigError(`plugin \"${plugin}\"`, ['\"waive\" must return a list of { rule, path, reason }, each a string']);\n }\n return value.map((w) => ({ rule: w.rule, path: w.path, reason: w.reason }));\n}\n\nexport async function loadPlugins(references: readonly PluginReference[], root: string): Promise<Plugin[]> {\n const plugins: Plugin[] = [];\n for (const reference of references) {\n let loaded: Record<string, unknown>;\n try {\n loaded = (await import(await specifierUrl(reference.module, root))) as Record<string, unknown>;\n } catch (error) {\n throw new ConfigError(reference.module, [`could not be loaded: ${(error as Error).message}`]);\n }\n const exported = loaded['default'] ?? loaded['plugin'];\n const value = typeof exported === 'function' ? await (exported as (o: unknown) => unknown)(reference.options) : exported;\n plugins.push(asPlugin(value, reference.module, reference.options));\n }\n const names = plugins.map((p) => p.name);\n const repeated = names.filter((n, i) => names.indexOf(n) !== i);\n if (repeated.length > 0) throw new ConfigError('plugins', [`two plugins are named \"${repeated[0] as string}\"`]);\n return plugins;\n}\n"]}
package/dist/report.d.ts CHANGED
@@ -28,7 +28,14 @@ export declare const JSON_SCHEMA_VERSION = 2;
28
28
  export interface Style {
29
29
  readonly color: boolean;
30
30
  }
31
- declare const CODES: Readonly<Record<string, readonly [number, number]>>;
31
+ /** The SGR code that turns each colour on, and the one that turns it off again. */
32
+ declare const CODES: {
33
+ readonly red: readonly [31, 39];
34
+ readonly yellow: readonly [33, 39];
35
+ readonly cyan: readonly [36, 39];
36
+ readonly dim: readonly [2, 22];
37
+ readonly bold: readonly [1, 22];
38
+ };
32
39
  export declare function paint(style: Style, color: keyof typeof CODES, text: string): string;
33
40
  export declare function summaryLine(findings: readonly Finding[]): string;
34
41
  export declare function prettyFindings(findings: readonly Finding[], style: Style): string;
package/dist/report.js CHANGED
@@ -26,17 +26,17 @@ export const FORMATS = ['pretty', 'json', 'sarif', 'github', 'gitlab'];
26
26
  * `waiting`.
27
27
  */
28
28
  export const JSON_SCHEMA_VERSION = 2;
29
+ /** The SGR code that turns each colour on, and the one that turns it off again. */
29
30
  const CODES = {
30
31
  red: [31, 39],
31
32
  yellow: [33, 39],
32
33
  cyan: [36, 39],
33
- green: [32, 39],
34
34
  dim: [2, 22],
35
35
  bold: [1, 22],
36
36
  };
37
37
  export function paint(style, color, text) {
38
- const code = CODES[color];
39
- return style.color && code !== undefined ? `\u001b[${code[0]}m${text}\u001b[${code[1]}m` : text;
38
+ const [on, off] = CODES[color];
39
+ return style.color ? `\u001b[${on}m${text}\u001b[${off}m` : text;
40
40
  }
41
41
  const SEVERITY_COLOR = { error: 'red', warning: 'yellow', note: 'cyan' };
42
42
  function plural(count, word) {
@@ -243,7 +243,8 @@ export function titleWithoutId(title, id) {
243
243
  const text = title.trimStart();
244
244
  // An id of digits is compared by value, so the title's own leading digits
245
245
  // are the candidate. A title with none has `''`, which no id's key equals;
246
- // any other text in its place fails `startsWith` and answers the same.
246
+ // any other text in its place, digits found further in included, fails
247
+ // `startsWith` and answers the same.
247
248
  const lead = /^\d+$/.test(id) ? (/^\d+/.exec(text)?.[0] ?? '') : id;
248
249
  if (!text.startsWith(lead) || idKey(lead) !== idKey(id))
249
250
  return title;
@@ -270,9 +271,8 @@ function padStart(text, width) {
270
271
  function table(header, rows) {
271
272
  const all = [header, ...rows];
272
273
  const widths = header.map((_, c) => Math.max(...all.map((r) => displayWidth(r[c]))));
273
- // Padding the last cell would change nothing: trimEnd takes it off again.
274
274
  return all.map((r) => r
275
- .map((cell, c) => (c === r.length - 1 ? cell : padEnd(cell, widths[c])))
275
+ .map((cell, c) => padEnd(cell, widths[c]))
276
276
  .join(' ')
277
277
  .trimEnd());
278
278
  }
@@ -297,26 +297,28 @@ export function prettyMatrix(report, style) {
297
297
  out.push(paint(style, 'bold', `${title} \u00b7 ${plural(wave.briefs.length, 'brief')}`));
298
298
  const names = wave.briefs.map(label);
299
299
  const width = Math.max(3, ...names.map(displayWidth));
300
- const pairs = (list) => new Set(list.flatMap((p) => [`${label(p.a)}\u0000${label(p.b)}`, `${label(p.b)}\u0000${label(p.a)}`]));
300
+ // A pair is marked by where its briefs stand in the wave, not by their
301
+ // labels: two briefs that share an id are two rows, and may collide. No
302
+ // pair is of a brief with itself, so the diagonal needs no rule of its own.
303
+ const place = new Map(wave.briefs.map((b, i) => [b, i]));
304
+ const pairs = (list) => new Set(list.flatMap((p) => [`${place.get(p.a)},${place.get(p.b)}`, `${place.get(p.b)},${place.get(p.a)}`]));
301
305
  const hits = pairs(wave.collisions);
302
306
  const unknown = pairs(wave.undecided);
303
307
  const near = pairs(wave.shared);
304
308
  out.push(` ${' '.repeat(width)} ${names.map((n) => padStart(n, width)).join(' ')}`);
305
- for (const row of names) {
306
- const cells = names.map((col) => {
307
- const key = `${row}\u0000${col}`;
308
- const mark = row === col
309
- ? '\u00b7'
310
- : hits.has(key)
311
- ? paint(style, 'red', 'X')
312
- : unknown.has(key)
313
- ? paint(style, 'yellow', '?')
314
- : near.has(key)
315
- ? paint(style, 'yellow', '~')
316
- : '\u00b7';
309
+ for (const [row, name] of names.entries()) {
310
+ const cells = names.map((_, col) => {
311
+ const key = `${row},${col}`;
312
+ const mark = hits.has(key)
313
+ ? paint(style, 'red', 'X')
314
+ : unknown.has(key)
315
+ ? paint(style, 'yellow', '?')
316
+ : near.has(key)
317
+ ? paint(style, 'yellow', '~')
318
+ : '\u00b7';
317
319
  return `${' '.repeat(width - 1)}${mark}`;
318
320
  });
319
- out.push(` ${padEnd(row, width)} ${cells.join(' ')}`);
321
+ out.push(` ${padEnd(name, width)} ${cells.join(' ')}`);
320
322
  }
321
323
  // One mark per pair of briefs; each further pair of patterns on a line beneath it.
322
324
  for (const c of wave.collisions) {