From b5f4d17800c0e2af710142de3794bc85a86cb1a8 Mon Sep 17 00:00:00 2001 From: Paolo Rondot <47555486+PaoloRondot@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:34:48 +0100 Subject: [PATCH 1/4] Read refs in YAML values of the files that the config names In a YAML file that the new `yaml-values` key of the config file names, a value that is one ref counts as a ref, plain or quoted, on one line, also as an item of a `[...]` or `{...}` collection: spec: sync:/docs/auth.md#token-lifetime - "iref:/docs/auth.md" specs: [sync:/docs/auth.md, sync:/docs/api.md] A ref inside a longer value, in a `|` or `>` block, or in a plain value that goes on in the next line is still not a ref. `,`, `[`, `{`, `]` and `}` end a value only inside a collection, so the ref in `note: Tokens, sync:/docs/auth.md` is not a value. Comments count as before, in every file. - The lexer can also return the string tokens of a file, so that a quoted value that holds only the ref is told from a longer string. - `findRefs` takes `values`, and `checkText` sets it from the config, so the CLI and the extension both read the values. - The README, the guide and the extension's README describe the key. Co-Authored-By: Claude Opus 5.5 --- README.md | 20 +++- packages/core/src/check.ts | 7 +- packages/core/src/comments.ts | 152 +++++++++++++++++++++++++--- packages/core/src/config.ts | 19 ++-- packages/core/src/repo.ts | 9 +- packages/core/test/check.test.ts | 43 ++++++++ packages/core/test/comments.test.ts | 43 ++++++++ packages/core/test/config.test.ts | 15 ++- packages/vscode/README.md | 6 +- skills/iref/SKILL.md | 17 +++- 10 files changed, 293 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index ae9de56..5c46136 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ iref:#heading-in-this-file ### Where a ref counts -A ref counts only in a comment. interref ignores the same text in a string, in code, in Markdown -text and in a code block. Thus an example in a test string or in a README is not a link: +A ref counts only in a comment, or in a YAML value that the config file asks for (see below). +interref ignores the same text in a string, in code, in Markdown text and in a code block. Thus an +example in a test string or in a README is not a link: ```python # iref:/docs/auth.md <- a ref @@ -87,6 +88,12 @@ url = "iref:/docs/auth.md" # not a ref: it is in a string first line of a `def` or `class` body. An f-string is not a docstring. - In GraphQL, a `"""` description is a comment. - In JSON, a ref counts in a `//` or `/* */` comment (as in `tsconfig.json`). +- In the YAML files that the `yaml-values` key of the [config file](#config-file) names, a value + that is one ref also counts, plain or quoted, for example `spec: sync:/docs/auth.md#token-lifetime` + or `- "iref:/docs/auth.md"`. So does an item of a `[...]` or `{...}` collection, as in + `specs: [sync:/docs/auth.md, sync:/docs/api.md]`. The ref must be the whole value, on one line: in + `note: see sync:/docs/auth.md`, in `note: sync:/docs/auth.md, and more`, in a `|` block, or in a + plain value that goes on in the next line, it is not a ref. interref finds the language from the file extension or the file name (for example `Dockerfile`, `Makefile`, `CMakeLists.txt`). A file with no extension can name its language in a `#!` line. A file @@ -255,13 +262,15 @@ source of the guide is [skills/iref/SKILL.md](skills/iref/SKILL.md). ### Config file -The config file at the repo root sets which files are not scanned, which protocols start a ref, and -the rule levels. It can have one of these names: `interref.toml`, `.interref.toml`, `interref.json` -or `.interref.json`. Use only one of them; two or more config files is an error. +The config file at the repo root sets which files are not scanned, which protocols start a ref, in +which YAML files a value can be a ref, and the rule levels. It can have one of these names: +`interref.toml`, `.interref.toml`, `interref.json` or `.interref.json`. Use only one of them; two or +more config files is an error. ```toml exclude = ["vendor/**", "**/*.min.js"] protocols = ["iref", "sync"] # the default +yaml-values = ["config/**/*.yaml"] # a value that is one ref counts in these files [rules] target-ignored = "off" # "off", "warn" or "error" @@ -273,6 +282,7 @@ The same config as JSON: { "exclude": ["vendor/**", "**/*.min.js"], "protocols": ["iref", "sync"], + "yaml-values": ["config/**/*.yaml"], "rules": { "target-ignored": "off" } } ``` diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 567fc93..90dff35 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -178,12 +178,13 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin } /** - * Scans and checks every ref in the comments of one file. A file that the config excludes, or - * whose language is not known, has none. + * Scans and checks every ref in the comments of one file, and in its values if it is a YAML file + * that the config names in `yaml-values`. A file that the config excludes, or whose language is not + * known, has none. */ export function checkText(repo: Repo, source: string, text: string): RefRecord[] { if (repo.isExcluded(source)) return []; - const matches = findRefs(source, text, repo.config.protocols); + const matches = findRefs(source, text, repo.config.protocols, repo.readsYamlValues(source)); if (matches.length === 0) return []; const lines = new LineIndex(text); return matches.map((match) => checkRef(repo, source, match, lines)); diff --git a/packages/core/src/comments.ts b/packages/core/src/comments.ts index 6077c35..e360885 100644 --- a/packages/core/src/comments.ts +++ b/packages/core/src/comments.ts @@ -6,7 +6,8 @@ * marker does not start a comment. The lexer is not a parser. It knows enough of each language to * tell a comment from a string, which is the only question that it has to answer. The language comes * from the file name, or from the `#!` line of a file that has no known extension. A file of an - * unknown language has no comments, so it has no refs. + * unknown language has no comments, so it has no refs. In the YAML files that the config names, a + * value that is one ref also counts. */ import { posix } from "node:path"; @@ -302,16 +303,22 @@ const TEX = language( PERCENT_LINE, ); +/** + * The column of the key of a YAML value, or of its `-` when the value is a list item (`- x`), from + * the text of the line before the value. The lines of the value are more indented than that. + */ +function yamlIndent(before: string): number { + return /^[ \t]*(?:-[ \t]+)+$/u.test(before) + ? before.lastIndexOf("-") + : (/^[ \t]*(?:-[ \t]+)*/u.exec(before)?.[0].length ?? 0); +} + const YAML_BLOCK_SCALAR: RuleSpec = { open: String.raw`(?<=(?:^|[:?-])[ \t]*)[|>][-+1-9]{0,2}(?=[ \t]*(?:#.*)?$)`, // The scalar ends at the first line that is not more indented than its key, or than its `-` when // the scalar is a list item (`- |`). close: (open, text) => { - const lineStart = text.lastIndexOf("\n", open.index - 1) + 1; - const before = text.slice(lineStart, open.index); - const indent = /^[ \t]*(?:-[ \t]+)+$/u.test(before) - ? before.lastIndexOf("-") - : (/^[ \t]*(?:-[ \t]+)*/u.exec(before)?.[0].length ?? 0); + const indent = yamlIndent(text.slice(text.lastIndexOf("\n", open.index - 1) + 1, open.index)); return new RegExp(`\\n(?=[ ]{0,${indent}}[^ \\r\\n])`, "gu"); }, }; @@ -615,11 +622,19 @@ function bracketBalance(code: string): number { const BRACKETS: Readonly> = { "{": /[{}]/gu, "(": /[()]/gu }; /** - * Adds the comments between `from` and `to` to `comments`. With `until` (`{` or `(`), it stops - * after the closing bracket that has no opening one: the end of an interpolation. Returns where it - * stopped. + * Adds the comments between `from` and `to` to `comments`, and the other tokens (strings) to + * `tokens` if it is given. With `until` (`{` or `(`), it stops after the closing bracket that has no + * opening one: the end of an interpolation. Returns where it stopped. */ -function lex(text: string, lang: Language, from: number, to: number, comments: Span[], until?: string): number { +function lex( + text: string, + lang: Language, + from: number, + to: number, + comments: Span[], + until?: string, + tokens?: Span[], +): number { const brackets = until === undefined ? undefined : BRACKETS[until]; let i = from; // The last character of code (not of a comment) before `i`, and the open brackets, for docstrings. @@ -660,6 +675,7 @@ function lex(text: string, lang: Language, from: number, to: number, comments: S comments.push({ start: at, end: end.end }); } else { if (rule.embed !== undefined) lex(text, rule.embed(open), openEnd, end.contentEnd, comments); + tokens?.push({ start: at, end: end.end }); lastCode = text.charAt(end.end - 1); } next = Math.max(end.end, at + 1); @@ -682,8 +698,117 @@ export function commentSpans(path: string, text: string): Span[] | undefined { return comments; } -/** Returns every ref in the comments of `text`, in order. `path` selects the language. */ -export function findRefs(path: string, text: string, protocols: readonly string[] = DEFAULT_PROTOCOLS): RefMatch[] { +/** Before a value in block context: `- ` items at the start of the line, or `key: `. */ +const YAML_BLOCK_VALUE = /(?:^[ \t]*(?:-[ \t]+)+|[^\s:]:[ \t]+)$/u; +/** After a value in block context: nothing, or spaces and a comment. */ +const YAML_BLOCK_END = /^(?:[ \t]+#.*|[ \t]*)\r?$/u; +/** Before a value in a flow collection (`[...]` or `{...}`): `[`, `{`, `,` or `key: `. */ +const YAML_FLOW_VALUE = /(?:[[{,][ \t]*|[^\s:]:[ \t]+)$/u; +/** After a value in a flow collection: `,`, `]`, `}` or a comment. */ +const YAML_FLOW_END = /^(?:[ \t]*[,\]}]|[ \t]+#)/u; +/** Skips blank lines, then takes the indentation of the next line and its first character, unless it is a comment. */ +const YAML_NEXT_LINE = /(?:\n[ \t]*\r?(?=\n))*\n( *)([^\s#]?)/uy; + +/** Finds the span that holds an offset, for offsets that never decrease: one walk of the spans, in order. */ +function spanFinder(spans: readonly Span[]): (at: number) => Span | undefined { + let index = 0; + return (at) => { + while ((spans[index]?.end ?? Number.POSITIVE_INFINITY) <= at) index++; + const span = spans[index]; + return span !== undefined && span.start <= at ? span : undefined; + }; +} + +/** + * The flow collections (`[...]` and `{...}`) of a YAML text, outermost only, and the text with the + * commas between their items made spaces, so that `[a,b]` holds two values. A collection starts + * where a block value does, so the bracket in `key: a[0]` starts none. A bracket or a comma in a + * string or a comment (the `skipped` spans, in order) does not count. + */ +function flowCollections(text: string, skipped: readonly Span[]): { flows: Span[]; items: string } { + const flows: Span[] = []; + const skippedAt = spanFinder(skipped); + let items = ""; + let copied = 0; + let depth = 0; + let start = 0; + for (const match of text.matchAll(/[[\]{},]/gu)) { + const at = match.index; + if (skippedAt(at) !== undefined) continue; + if (match[0] === ",") { + if (depth === 0) continue; + items += `${text.slice(copied, at)} `; + copied = at + 1; + } else if (match[0] === "[" || match[0] === "{") { + if (depth > 0) depth++; + else if (YAML_BLOCK_VALUE.test(text.slice(text.lastIndexOf("\n", at - 1) + 1, at))) { + depth = 1; + start = at; + } + } else if (depth > 0) { + depth--; + if (depth === 0) flows.push({ start, end: at + 1 }); + } + } + if (depth > 0) flows.push({ start, end: text.length }); + return { flows, items: items + text.slice(copied) }; +} + +/** + * Whether the plain value that ends the line at `lineEnd` goes on in the next lines, as a YAML + * plain scalar does: the next line that is not blank or a comment is more indented than the key or + * the `-` of the value. `before` is the text of the line before the value. + */ +function continues(text: string, lineEnd: number, before: string): boolean { + YAML_NEXT_LINE.lastIndex = lineEnd; + const next = YAML_NEXT_LINE.exec(text); + return (next?.[2] ?? "") !== "" && (next?.[1]?.length ?? 0) > yamlIndent(before); +} + +/** + * The refs of a YAML file that are the whole value of a scalar, plain or quoted, on one line. In a + * flow collection, `,`, `[`, `{` and `]`, `}` also end a value; outside one, only a comment may + * follow it. + */ +function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { + const comments: Span[] = []; + const tokens: Span[] = []; + lex(text, YAML, 0, text.length, comments, undefined, tokens); + const { flows, items } = flowCollections(text, [...comments, ...tokens].sort((a, b) => a.start - b.start)); + const commentAt = spanFinder(comments); + const tokenAt = spanFinder(tokens); + const flowAt = spanFinder(flows); + return scanRefs(items, protocols).filter((ref) => { + if (commentAt(ref.start) !== undefined) return false; + const token = tokenAt(ref.start); + // A quoted string that holds only the ref. A block scalar (`|` or `>`) is not one. + const quoted = + token !== undefined && /["']/u.test(text.charAt(token.start)) && token.start + 1 === ref.start && token.end - 1 === ref.end; + if (token !== undefined && !quoted) return false; + const start = token?.start ?? ref.start; + const end = token?.end ?? ref.end; + const lineStart = text.lastIndexOf("\n", start - 1) + 1; + const newline = text.indexOf("\n", end); + const lineEnd = newline < 0 ? text.length : newline; + const before = text.slice(lineStart, start); + const after = text.slice(end, lineEnd); + if (flowAt(ref.start) !== undefined) return YAML_FLOW_VALUE.test(before) && YAML_FLOW_END.test(after); + if (!YAML_BLOCK_VALUE.test(before) || !YAML_BLOCK_END.test(after)) return false; + // A plain value can go on in the next lines, unless a comment ends it. + return quoted || after.includes("#") || !continues(text, lineEnd, before); + }); +} + +/** + * Returns every ref in the comments of `text`, in order. `path` selects the language. With + * `values`, a YAML file also has the refs that are the whole value of a scalar, plain or quoted. + */ +export function findRefs( + path: string, + text: string, + protocols: readonly string[] = DEFAULT_PROTOCOLS, + values = false, +): RefMatch[] { if (!protocols.some((name) => text.includes(`${name}:`))) return []; const refs: RefMatch[] = []; for (const span of commentSpans(path, text) ?? []) { @@ -691,5 +816,6 @@ export function findRefs(path: string, text: string, protocols: readonly string[ refs.push({ ...ref, start: ref.start + span.start, end: ref.end + span.start }); } } - return refs; + if (!values || languageOf(path, text) !== YAML) return refs; + return [...refs, ...yamlValueRefs(text, protocols)].sort((a, b) => a.start - b.start); } diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 7bb9e5e..8fd7835 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -3,11 +3,12 @@ * * exclude = ["vendor/**", "**\/*.min.js"] * protocols = ["iref", "sync"] + * yaml-values = ["model/**\/*.yaml"] * * [rules] * target-ignored = "warn" * - * A `.json` file holds the same keys: `{ "exclude": [...], "protocols": [...], "rules": {...} }`. + * A `.json` file holds the same keys: `{ "exclude": [...], "protocols": [...], "yaml-values": [...], "rules": {...} }`. */ import { join } from "node:path"; @@ -24,10 +25,12 @@ export interface Config { readonly exclude: readonly string[]; /** The names before `:` that start a ref, for example `iref` in `iref:/a.md`. */ readonly protocols: readonly string[]; + /** Globs of YAML files in which a value that is one ref counts as a ref, not only a comment. */ + readonly yamlValues: readonly string[]; readonly rules: Readonly>>; } -export const DEFAULT_CONFIG: Config = { exclude: [], protocols: DEFAULT_PROTOCOLS, rules: {} }; +export const DEFAULT_CONFIG: Config = { exclude: [], protocols: DEFAULT_PROTOCOLS, yamlValues: [], rules: {} }; export class ConfigError extends Error {} @@ -75,6 +78,7 @@ export function parseConfig(text: string, file = "interref.toml"): Config { function parseTomlConfig(text: string, file: string): Config { const exclude: string[] = []; let protocols: string[] | undefined; + const yamlValues: string[] = []; const rules: Partial> = {}; let table = ""; const lines = text.split(/\r?\n/u); @@ -93,7 +97,7 @@ function parseTomlConfig(text: string, file: string): Config { const key = pair[1]; let value = pair[2]; - if (table === "" && (key === "exclude" || key === "protocols")) { + if (table === "" && (key === "exclude" || key === "protocols" || key === "yaml-values")) { // Arrays may span lines: keep reading until the closing bracket. while (!value.trimEnd().endsWith("]") && i + 1 < lines.length) { i++; @@ -104,6 +108,7 @@ function parseTomlConfig(text: string, file: string): Config { if (array?.[1] === undefined) throw new ConfigError(`${where}: ${key} must be an array of strings`); const items = (array[1].match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^,\s]+/gu) ?? []).map((item) => parseString(item, where)); if (key === "exclude") exclude.push(...items); + else if (key === "yaml-values") yamlValues.push(...items); else { checkProtocols(items, where); protocols = items; @@ -117,7 +122,7 @@ function parseTomlConfig(text: string, file: string): Config { throw new ConfigError(`${where}: unknown key ${key}`); } } - return { exclude, protocols: protocols ?? DEFAULT_PROTOCOLS, rules }; + return { exclude, protocols: protocols ?? DEFAULT_PROTOCOLS, yamlValues, rules }; } const isStringArray = (value: unknown): value is string[] => @@ -135,11 +140,13 @@ function parseJsonConfig(text: string, file: string): Config { if (!isObject(data)) throw new ConfigError(`${file}: expected an object`); const exclude: string[] = []; let protocols: readonly string[] = DEFAULT_PROTOCOLS; + const yamlValues: string[] = []; const rules: Partial> = {}; for (const [key, value] of Object.entries(data)) { - if (key === "exclude" || key === "protocols") { + if (key === "exclude" || key === "protocols" || key === "yaml-values") { if (!isStringArray(value)) throw new ConfigError(`${file}: ${key} must be an array of strings`); if (key === "exclude") exclude.push(...value); + else if (key === "yaml-values") yamlValues.push(...value); else { checkProtocols(value, file); protocols = value; @@ -157,7 +164,7 @@ function parseJsonConfig(text: string, file: string): Config { throw new ConfigError(`${file}: unknown key ${key}`); } } - return { exclude, protocols, rules }; + return { exclude, protocols, yamlValues, rules }; } /** diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index f2c12f7..fbf488b 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -4,7 +4,7 @@ import { execFile } from "node:child_process"; import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import { dirname, isAbsolute, join, relative, sep } from "node:path"; import { promisify } from "node:util"; -import { DEFAULT_CONFIG, excluder, loadConfig, type Config } from "./config.js"; +import { DEFAULT_CONFIG, excluder, globToRegExp, loadConfig, type Config } from "./config.js"; import { extractHeadings, isMarkdownPath, type Heading } from "./markdown.js"; const run = promisify(execFile); @@ -64,6 +64,7 @@ export class Repo { private readonly children = new Map>(); private readonly headingCache = new Map(); private readonly excluded: (path: string) => boolean; + private readonly yamlValues: readonly RegExp[]; /** * @param root absolute path of the repo top level @@ -78,6 +79,7 @@ export class Repo { readonly config: Config = DEFAULT_CONFIG, ) { this.excluded = excluder(config); + this.yamlValues = config.yamlValues.map(globToRegExp); this.trackedSet = new Set(tracked); this.fileSet = new Set([...tracked, ...untracked]); for (const file of this.fileSet) { @@ -129,6 +131,11 @@ export class Repo { return this.excluded(path); } + /** Whether the config names `path` in `yaml-values`, so that a YAML value that is one ref counts. */ + readsYamlValues(path: string): boolean { + return this.yamlValues.some((pattern) => pattern.test(path)); + } + private addLowerCase(path: string): void { const key = path.toLowerCase(); const list = this.byLowerCase.get(key); diff --git a/packages/core/test/check.test.ts b/packages/core/test/check.test.ts index 73ff042..5974d85 100644 --- a/packages/core/test/check.test.ts +++ b/packages/core/test/check.test.ts @@ -129,6 +129,49 @@ describe("checkText", () => { }); }); +describe("refs in YAML values", () => { + let fixture: ReturnType; + + before(() => { + const yaml = [ + "# iref:/docs/spec.md", + "tokens:", + " spec: sync:/docs/spec.md#tokens", + ' quoted: "sync:/docs/spec.md#sessions"', + " list: [sync:/docs/spec.md, 'iref:/docs/spec.md#tokens']", + " items:", + " - sync:/docs/spec.md#sessions # a comment", + " text: see sync:/no/such/file", + ' partial: "sync:/no/such/file and more"', + " block: |", + " sync:/no/such/file", + "", + ].join("\n"); + fixture = makeRepo({ + ".interref.toml": 'yaml-values = ["model/**"]\n', + "docs/spec.md": "# Spec\n\n## Tokens\n\n## Sessions\n", + "model/limits.yaml": yaml, + "other.yaml": yaml, + }); + }); + after(() => fixture.dispose()); + + it("count when the value is one ref, in the YAML files that the config names", async () => { + const repo = await Repo.open(fixture.root); + const refs = (path: string): string[] => + scanRepo(repo, (candidate) => candidate === path).records.map((record) => `${record.source.line} ${record.raw} ${record.status}`); + assert.deepEqual(refs("model/limits.yaml"), [ + "1 iref:/docs/spec.md ok", + "3 sync:/docs/spec.md#tokens ok", + "4 sync:/docs/spec.md#sessions ok", + "5 sync:/docs/spec.md ok", + "5 iref:/docs/spec.md#tokens ok", + "7 sync:/docs/spec.md#sessions ok", + ]); + assert.deepEqual(refs("other.yaml"), ["1 iref:/docs/spec.md ok"]); + }); +}); + describe("a file moved without git", () => { let fixture: ReturnType; diff --git a/packages/core/test/comments.test.ts b/packages/core/test/comments.test.ts index 35f6916..274440e 100644 --- a/packages/core/test/comments.test.ts +++ b/packages/core/test/comments.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; import { commentSpans, findRefs } from "../src/comments.js"; +import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; // In each text, refs that must be found point at /yes…, and refs that must not be found point at /no. const raws = (path: string, ...lines: string[]): string[] => findRefs(path, lines.join("\n")).map((ref) => ref.raw); @@ -31,6 +32,48 @@ describe("findRefs", () => { }); }); +describe("findRefs in YAML values", () => { + const values = (...lines: string[]): string[] => + findRefs("a.yaml", lines.join("\n"), DEFAULT_PROTOCOLS, true).map((ref) => ref.raw); + + it("finds a ref that is a whole value, also an item of a flow collection", () => { + assert.deepEqual( + values( + "a: iref:/yes1", + '- - "iref:/yes2" # a comment', + "b: [iref:/yes3,iref:/yes4, 'iref:/yes5']", + "c: {d: iref:/yes6, e: [x,", + " y, iref:/yes7]}", + "f: iref:/yes8", + "", + " # a comment", + "g:", + " - iref:/yes9", + " - x", + ), + ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5", "iref:/yes6", "iref:/yes7", "iref:/yes8", "iref:/yes9"], + ); + }); + + it("does not find a ref in a longer value", () => { + for (const line of [ + "key: sync:/docs/a.md, see also the model", + "note: Tokens, sync:/docs/a.md", + "note: foo {sync:/docs/a.md}", + 'note: a, "sync:/docs/a.md"', + 'key: foo - "sync:/docs/a.md"', + "key: a[sync:/docs/a.md]", + "key: [sync:/docs/a.md and more]", + ]) { + assert.deepEqual(values(line), [], line); + } + }); + + it("does not find a plain ref that the next lines continue", () => { + assert.deepEqual(values("a: iref:/no", " goes on", "b:", " - iref:/no", "", " goes on", "c: iref:/yes"), ["iref:/yes"]); + }); +}); + describe("comments by language", () => { it("JavaScript and TypeScript", () => { assert.deepEqual( diff --git a/packages/core/test/config.test.ts b/packages/core/test/config.test.ts index 5db7034..fcca4c3 100644 --- a/packages/core/test/config.test.ts +++ b/packages/core/test/config.test.ts @@ -27,6 +27,12 @@ describe("parseConfig", () => { assert.deepEqual(parseConfig('protocols = ["ref", "nref"]').protocols, ["ref", "nref"]); }); + it("reads yaml-values", () => { + assert.deepEqual(parseConfig('yaml-values = ["model/**",\n "config/*.yaml"]').yamlValues, ["model/**", "config/*.yaml"]); + assert.deepEqual(parseConfig("").yamlValues, []); + assert.throws(() => parseConfig('yaml-values = "model/**"'), ConfigError); + }); + it("rejects unknown keys, rules and settings", () => { assert.throws(() => parseConfig("include = []"), ConfigError); assert.throws(() => parseConfig('[rules]\nline-reff = "off"'), ConfigError); @@ -39,10 +45,15 @@ describe("parseConfig", () => { it("reads JSON when the file name ends in .json", () => { const config = parseConfig( - JSON.stringify({ exclude: ["vendor/**"], protocols: ["sync"], rules: { "target-ignored": "off" } }), + JSON.stringify({ exclude: ["vendor/**"], protocols: ["sync"], "yaml-values": ["model/**"], rules: { "target-ignored": "off" } }), ".interref.json", ); - assert.deepEqual(config, { exclude: ["vendor/**"], protocols: ["sync"], rules: { "target-ignored": "off" } }); + assert.deepEqual(config, { + exclude: ["vendor/**"], + protocols: ["sync"], + yamlValues: ["model/**"], + rules: { "target-ignored": "off" }, + }); assert.deepEqual(parseConfig("{}", "interref.json"), DEFAULT_CONFIG); }); diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 2e74259..62023d9 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -14,9 +14,9 @@ This extension makes `iref:` links in comments clickable, and it shows broken li Preview (`vstirbu.vscode-mermaid-preview`). If the viewer is missing, the command offers to install it. -A ref counts only in a comment, not in a string or in Markdown text. Only heading fragments are -supported for now. For the full syntax and the `interref` CLI, see the -`README.md` of the interref repo. +A ref counts only in a comment, not in a string or in Markdown text, except in a YAML value that the +config file asks for. Only heading fragments are supported for now. For the full syntax and the +`interref` CLI, see the `README.md` of the interref repo. ## Settings diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 76c4e6f..721654e 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -55,8 +55,9 @@ only to the page. ## Put the ref in a comment -A ref counts only in a comment. The same text in a string, in code or in -Markdown body text is not a ref. +A ref counts only in a comment, or in a YAML value that the config asks for +(see below). The same text in a string, in code or in Markdown body text is +not a ref. | File | Where to put the ref | |---|---| @@ -69,6 +70,11 @@ Markdown body text is not a ref. Do not put a ref in a docstring that the program shows to users, for example an `argparse` description that uses `__doc__`. +In the YAML files that the `yaml-values` key of the config file names, a value +that is one ref also counts, plain or quoted, for example +`spec: sync:/docs/auth.md#token-lifetime`, and so does an item of a `[...]` or +`{...}` collection. The ref must be the whole value, on one line. + A file type that interref does not know (for example `.txt`) has no refs. ## Choose the protocol @@ -130,9 +136,10 @@ lines around each ref), `-T N` (show the first N lines of the target), ### Add refs -1. Read the config file at the repo root for `protocols` and `exclude`. Its - name is `interref.toml`, `.interref.toml`, `interref.json` or - `.interref.json`. It is an error to have two config files. +1. Read the config file at the repo root for `protocols`, `exclude` and + `yaml-values`. Its name is `interref.toml`, `.interref.toml`, + `interref.json` or `.interref.json`. It is an error to have two config + files. 2. For each link, find the downstream file and the most specific target heading. 3. Write the ref in a comment in the downstream file. Match the comment style From e5d1b01d14863f3410db335a708aa54cf08a6181 Mon Sep 17 00:00:00 2001 From: mondaychen Date: Tue, 1 Dec 2026 14:15:10 -0500 Subject: [PATCH 2/4] Rewrite the comments and docs for YAML values so that they are easier to read Co-Authored-By: Claude Opus 5.5 --- README.md | 29 ++++++++------ packages/core/src/check.ts | 6 +-- packages/core/src/comments.ts | 74 +++++++++++++++++++++++------------ packages/core/src/config.ts | 5 ++- packages/core/src/repo.ts | 5 ++- packages/vscode/README.md | 7 ++-- skills/iref/SKILL.md | 21 +++++----- 7 files changed, 91 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 5c46136..d9dfc79 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,9 @@ iref:#heading-in-this-file ### Where a ref counts -A ref counts only in a comment, or in a YAML value that the config file asks for (see below). -interref ignores the same text in a string, in code, in Markdown text and in a code block. Thus an -example in a test string or in a README is not a link: +A ref counts only in a comment, with one exception: in the YAML files that the config file names, a +value can also be a ref (see below). interref ignores the same text in a string, in code, in +Markdown text and in a code block. Thus an example in a test string or in a README is not a link: ```python # iref:/docs/auth.md <- a ref @@ -88,12 +88,16 @@ url = "iref:/docs/auth.md" # not a ref: it is in a string first line of a `def` or `class` body. An f-string is not a docstring. - In GraphQL, a `"""` description is a comment. - In JSON, a ref counts in a `//` or `/* */` comment (as in `tsconfig.json`). -- In the YAML files that the `yaml-values` key of the [config file](#config-file) names, a value - that is one ref also counts, plain or quoted, for example `spec: sync:/docs/auth.md#token-lifetime` - or `- "iref:/docs/auth.md"`. So does an item of a `[...]` or `{...}` collection, as in - `specs: [sync:/docs/auth.md, sync:/docs/api.md]`. The ref must be the whole value, on one line: in - `note: see sync:/docs/auth.md`, in `note: sync:/docs/auth.md, and more`, in a `|` block, or in a - plain value that goes on in the next line, it is not a ref. +- In YAML, a value can also be a ref, but only in the files that the `yaml-values` key of the + [config file](#config-file) names. The value must be exactly one ref, and it can be plain or in + quotes. Examples are `spec: sync:/docs/auth.md#token-lifetime` and `- "iref:/docs/auth.md"`. An + item of a `[...]` or `{...}` collection also counts, as in + `specs: [sync:/docs/auth.md, sync:/docs/api.md]`. The ref must be the whole value, and the value + must be on one line. In these cases, the text is not a ref: + - `note: see sync:/docs/auth.md`, because the value has other text before the ref. + - `note: sync:/docs/auth.md, and more`, because the value has other text after the ref. + - A `|` block. + - A plain value that continues on the next line. interref finds the language from the file extension or the file name (for example `Dockerfile`, `Makefile`, `CMakeLists.txt`). A file with no extension can name its language in a `#!` line. A file @@ -262,15 +266,16 @@ source of the guide is [skills/iref/SKILL.md](skills/iref/SKILL.md). ### Config file -The config file at the repo root sets which files are not scanned, which protocols start a ref, in -which YAML files a value can be a ref, and the rule levels. It can have one of these names: +The config file at the repo root sets four things: the files that interref does not scan, the +protocols that start a ref, the YAML files in which a value can be a ref, and the rule levels. The +config file can have one of these names: `interref.toml`, `.interref.toml`, `interref.json` or `.interref.json`. Use only one of them; two or more config files is an error. ```toml exclude = ["vendor/**", "**/*.min.js"] protocols = ["iref", "sync"] # the default -yaml-values = ["config/**/*.yaml"] # a value that is one ref counts in these files +yaml-values = ["config/**/*.yaml"] # in these YAML files, a value can be a ref [rules] target-ignored = "off" # "off", "warn" or "error" diff --git a/packages/core/src/check.ts b/packages/core/src/check.ts index 90dff35..6d953d5 100644 --- a/packages/core/src/check.ts +++ b/packages/core/src/check.ts @@ -178,9 +178,9 @@ export function checkRef(repo: Repo, source: string, match: RefMatch, lines: Lin } /** - * Scans and checks every ref in the comments of one file, and in its values if it is a YAML file - * that the config names in `yaml-values`. A file that the config excludes, or whose language is not - * known, has none. + * Scans and checks every ref in the comments of one file. If the file is a YAML file that the + * config names in `yaml-values`, it also scans and checks the refs in the YAML values. A file has + * no refs if the config excludes it or if its language is not known. */ export function checkText(repo: Repo, source: string, text: string): RefRecord[] { if (repo.isExcluded(source)) return []; diff --git a/packages/core/src/comments.ts b/packages/core/src/comments.ts index e360885..bbf2098 100644 --- a/packages/core/src/comments.ts +++ b/packages/core/src/comments.ts @@ -7,7 +7,7 @@ * tell a comment from a string, which is the only question that it has to answer. The language comes * from the file name, or from the `#!` line of a file that has no known extension. A file of an * unknown language has no comments, so it has no refs. In the YAML files that the config names, a - * value that is one ref also counts. + * value can also be a ref, if the whole value is one ref. */ import { posix } from "node:path"; @@ -304,8 +304,9 @@ const TEX = language( ); /** - * The column of the key of a YAML value, or of its `-` when the value is a list item (`- x`), from - * the text of the line before the value. The lines of the value are more indented than that. + * Returns the column of the key of a YAML value. If the value is a list item (`- x`), it returns + * the column of the `-` instead. `before` is the text on the line of the value, from the start of + * the line to the value. Each line of the value has more indentation than this column. */ function yamlIndent(before: string): number { return /^[ \t]*(?:-[ \t]+)+$/u.test(before) @@ -622,9 +623,9 @@ function bracketBalance(code: string): number { const BRACKETS: Readonly> = { "{": /[{}]/gu, "(": /[()]/gu }; /** - * Adds the comments between `from` and `to` to `comments`, and the other tokens (strings) to - * `tokens` if it is given. With `until` (`{` or `(`), it stops after the closing bracket that has no - * opening one: the end of an interpolation. Returns where it stopped. + * Adds the comments between `from` and `to` to `comments`. If `tokens` is given, it also adds the + * other tokens (strings) to `tokens`. With `until` (`{` or `(`), it stops after the closing bracket + * that has no opening one: the end of an interpolation. Returns where it stopped. */ function lex( text: string, @@ -698,18 +699,33 @@ export function commentSpans(path: string, text: string): Span[] | undefined { return comments; } -/** Before a value in block context: `- ` items at the start of the line, or `key: `. */ +/** + * Matches the text before a value in block context: one or more `- ` at the start of the line, or + * `key: `. + */ const YAML_BLOCK_VALUE = /(?:^[ \t]*(?:-[ \t]+)+|[^\s:]:[ \t]+)$/u; -/** After a value in block context: nothing, or spaces and a comment. */ +/** + * Matches the text after a value in block context: nothing, only spaces, or spaces and then a + * comment. + */ const YAML_BLOCK_END = /^(?:[ \t]+#.*|[ \t]*)\r?$/u; -/** Before a value in a flow collection (`[...]` or `{...}`): `[`, `{`, `,` or `key: `. */ +/** + * Matches the text before a value in a flow collection (`[...]` or `{...}`): `[`, `{`, `,` or + * `key: `. + */ const YAML_FLOW_VALUE = /(?:[[{,][ \t]*|[^\s:]:[ \t]+)$/u; -/** After a value in a flow collection: `,`, `]`, `}` or a comment. */ +/** Matches the text after a value in a flow collection: `,`, `]`, `}` or a comment. */ const YAML_FLOW_END = /^(?:[ \t]*[,\]}]|[ \t]+#)/u; -/** Skips blank lines, then takes the indentation of the next line and its first character, unless it is a comment. */ +/** + * Skips blank lines. Then it captures the indentation of the next line, and the first character of + * that line. If that line is a comment, the second group is empty. + */ const YAML_NEXT_LINE = /(?:\n[ \t]*\r?(?=\n))*\n( *)([^\s#]?)/uy; -/** Finds the span that holds an offset, for offsets that never decrease: one walk of the spans, in order. */ +/** + * Returns a function that finds the span that contains an offset. Call the function with offsets + * that never decrease, so that it walks through the spans only once, in order. + */ function spanFinder(spans: readonly Span[]): (at: number) => Span | undefined { let index = 0; return (at) => { @@ -720,10 +736,12 @@ function spanFinder(spans: readonly Span[]): (at: number) => Span | undefined { } /** - * The flow collections (`[...]` and `{...}`) of a YAML text, outermost only, and the text with the - * commas between their items made spaces, so that `[a,b]` holds two values. A collection starts - * where a block value does, so the bracket in `key: a[0]` starts none. A bracket or a comma in a - * string or a comment (the `skipped` spans, in order) does not count. + * Finds the flow collections (`[...]` and `{...}`) of a YAML text. It returns only the outermost + * collections. It also returns a copy of the text in which each comma between the items of a + * collection is changed to a space, so that `[a,b]` holds two separate values. A collection can + * start only where a block value can start, so the bracket in `key: a[0]` does not start a + * collection. A bracket or a comma in a string or in a comment does not count. The `skipped` spans + * mark these strings and comments, in order. */ function flowCollections(text: string, skipped: readonly Span[]): { flows: Span[]; items: string } { const flows: Span[] = []; @@ -755,9 +773,10 @@ function flowCollections(text: string, skipped: readonly Span[]): { flows: Span[ } /** - * Whether the plain value that ends the line at `lineEnd` goes on in the next lines, as a YAML - * plain scalar does: the next line that is not blank or a comment is more indented than the key or - * the `-` of the value. `before` is the text of the line before the value. + * Returns whether a plain value continues on the next lines, as a YAML plain scalar can. The value + * is at the end of the line that ends at `lineEnd`. The value continues if the next line that is + * not blank is not a comment, and has more indentation than the key of the value (or than its `-`). + * `before` is the text on the line of the value, from the start of the line to the value. */ function continues(text: string, lineEnd: number, before: string): boolean { YAML_NEXT_LINE.lastIndex = lineEnd; @@ -766,9 +785,10 @@ function continues(text: string, lineEnd: number, before: string): boolean { } /** - * The refs of a YAML file that are the whole value of a scalar, plain or quoted, on one line. In a - * flow collection, `,`, `[`, `{` and `]`, `}` also end a value; outside one, only a comment may - * follow it. + * Returns the refs of a YAML file that are the whole value of a scalar. The scalar can be plain or + * in quotes, and it must be on one line. In a flow collection, a value can also start after `[`, + * `{` or `,`, and it can end before `,`, `]` or `}`. Outside a flow collection, only a comment can + * follow the value. */ function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { const comments: Span[] = []; @@ -781,7 +801,8 @@ function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { return scanRefs(items, protocols).filter((ref) => { if (commentAt(ref.start) !== undefined) return false; const token = tokenAt(ref.start); - // A quoted string that holds only the ref. A block scalar (`|` or `>`) is not one. + // `quoted` is true if the token is a quoted string that contains only the ref. A block scalar + // (`|` or `>`) is not a quoted string. const quoted = token !== undefined && /["']/u.test(text.charAt(token.start)) && token.start + 1 === ref.start && token.end - 1 === ref.end; if (token !== undefined && !quoted) return false; @@ -794,14 +815,15 @@ function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { const after = text.slice(end, lineEnd); if (flowAt(ref.start) !== undefined) return YAML_FLOW_VALUE.test(before) && YAML_FLOW_END.test(after); if (!YAML_BLOCK_VALUE.test(before) || !YAML_BLOCK_END.test(after)) return false; - // A plain value can go on in the next lines, unless a comment ends it. + // A plain value can continue on the next lines. A comment at the end of the line stops it. return quoted || after.includes("#") || !continues(text, lineEnd, before); }); } /** - * Returns every ref in the comments of `text`, in order. `path` selects the language. With - * `values`, a YAML file also has the refs that are the whole value of a scalar, plain or quoted. + * Returns every ref in the comments of `text`, in order. `path` selects the language. If `values` + * is true and the file is YAML, it also returns the refs that are the whole value of a scalar, + * plain or in quotes. */ export function findRefs( path: string, diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 8fd7835..6e97a36 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -25,7 +25,10 @@ export interface Config { readonly exclude: readonly string[]; /** The names before `:` that start a ref, for example `iref` in `iref:/a.md`. */ readonly protocols: readonly string[]; - /** Globs of YAML files in which a value that is one ref counts as a ref, not only a comment. */ + /** + * Globs of the YAML files in which a value can be a ref, not only a comment. The whole value must + * be one ref. + */ readonly yamlValues: readonly string[]; readonly rules: Readonly>>; } diff --git a/packages/core/src/repo.ts b/packages/core/src/repo.ts index fbf488b..6bbdcd5 100644 --- a/packages/core/src/repo.ts +++ b/packages/core/src/repo.ts @@ -131,7 +131,10 @@ export class Repo { return this.excluded(path); } - /** Whether the config names `path` in `yaml-values`, so that a YAML value that is one ref counts. */ + /** + * Returns whether the config names `path` in `yaml-values`. If it does, a YAML value in that file + * can be a ref, if the whole value is one ref. + */ readsYamlValues(path: string): boolean { return this.yamlValues.some((pattern) => pattern.test(path)); } diff --git a/packages/vscode/README.md b/packages/vscode/README.md index 62023d9..ba7519e 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -14,9 +14,10 @@ This extension makes `iref:` links in comments clickable, and it shows broken li Preview (`vstirbu.vscode-mermaid-preview`). If the viewer is missing, the command offers to install it. -A ref counts only in a comment, not in a string or in Markdown text, except in a YAML value that the -config file asks for. Only heading fragments are supported for now. For the full syntax and the -`interref` CLI, see the `README.md` of the interref repo. +A ref counts only in a comment, not in a string or in Markdown text. There is one exception: in the +YAML files that the `yaml-values` key of the config file names, a value can also be a ref. Only +heading fragments are supported for now. For the full syntax and the `interref` CLI, see the +`README.md` of the interref repo. ## Settings diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index 721654e..cd30c11 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -55,9 +55,9 @@ only to the page. ## Put the ref in a comment -A ref counts only in a comment, or in a YAML value that the config asks for -(see below). The same text in a string, in code or in Markdown body text is -not a ref. +A ref counts only in a comment, with one exception: in the YAML files that +the config names, a value can also be a ref (see below). The same text in a +string, in code or in Markdown body text is not a ref. | File | Where to put the ref | |---|---| @@ -71,9 +71,10 @@ Do not put a ref in a docstring that the program shows to users, for example an `argparse` description that uses `__doc__`. In the YAML files that the `yaml-values` key of the config file names, a value -that is one ref also counts, plain or quoted, for example -`spec: sync:/docs/auth.md#token-lifetime`, and so does an item of a `[...]` or -`{...}` collection. The ref must be the whole value, on one line. +can also be a ref. The value must be exactly one ref, and it can be plain or in +quotes, for example `spec: sync:/docs/auth.md#token-lifetime`. An item of a +`[...]` or `{...}` collection also counts. The ref must be the whole value, and +the value must be on one line. A file type that interref does not know (for example `.txt`) has no refs. @@ -136,10 +137,10 @@ lines around each ref), `-T N` (show the first N lines of the target), ### Add refs -1. Read the config file at the repo root for `protocols`, `exclude` and - `yaml-values`. Its name is `interref.toml`, `.interref.toml`, - `interref.json` or `.interref.json`. It is an error to have two config - files. +1. Read the config file at the repo root, and find the values of + `protocols`, `exclude` and `yaml-values`. Its name is `interref.toml`, + `.interref.toml`, `interref.json` or `.interref.json`. It is an error to + have two config files. 2. For each link, find the downstream file and the most specific target heading. 3. Write the ref in a comment in the downstream file. Match the comment style From afd3e77ece91aec6315de2fb08cb4e36af76e6bd Mon Sep 17 00:00:00 2001 From: Paolo Rondot <47555486+PaoloRondot@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:40:17 +0100 Subject: [PATCH 3/4] Find the refs in YAML values with the yaml parser, and complete them in VS Code The review of the YAML values asked for a real YAML parser in place of the regex rules. These rules look at one line at a time, but a YAML value can go across lines, and the 5 problems that the review found all come from this gap. `packages/core/src/values.ts` now reads a file that `yaml-values` names with the `yaml` package. A plain or quoted scalar that is not a key, and whose text is exactly one ref, is a ref. The lexer still finds the comments, as before, and no longer returns the string tokens. - A plain value that continues the line before it, as ` - sync:/a.md` under `key: some text`, is not a ref. - A `[...]` list that goes across lines gives each of its refs. - A value on the line under its key, or after an anchor or a tag (`key: &x sync:/a.md`, `key: !!str sync:/a.md`), is a ref. An alias does not count the ref a second time. - A `[` that is not closed no longer hides the later values of the file. - In VS Code, completion also works for a ref that starts a value. A key counts too, because a ref that is still being typed, such as `- sync:`, reads as a key. `yaml` (ISC) has no dependencies of its own. esbuild bundles it into the CLI and the extension. `yaml` is CommonJS, so the ES module bundle of the CLI makes a `require` for it. Its license is in the new THIRD-PARTY-NOTICES, which the npm package and the .vsix ship next to LICENSE. The README, the guide, the extension's README and DEVELOPMENT.md describe the parser and the cases that are not refs. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + DEVELOPMENT.md | 10 +- README.md | 19 ++-- THIRD-PARTY-NOTICES | 21 ++++ packages/cli/esbuild.mjs | 3 + packages/cli/package.json | 5 +- packages/core/package.json | 3 + packages/core/src/comments.ts | 158 +++------------------------- packages/core/src/index.ts | 2 +- packages/core/src/values.ts | 68 ++++++++++++ packages/core/test/comments.test.ts | 51 ++++++--- packages/vscode/.vscodeignore | 1 + packages/vscode/README.md | 5 +- packages/vscode/package.json | 2 +- packages/vscode/src/features.ts | 13 ++- pnpm-lock.yaml | 11 ++ skills/iref/SKILL.md | 4 +- 17 files changed, 200 insertions(+), 177 deletions(-) create mode 100644 THIRD-PARTY-NOTICES create mode 100644 packages/core/src/values.ts diff --git a/.gitignore b/.gitignore index 90eb999..6e2240d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ release/ # Copied from the repo root when a package is packed. packages/*/LICENSE +packages/*/THIRD-PARTY-NOTICES # Copied from the repo README when the CLI is packed. packages/vscode/README.md is its own file. packages/cli/README.md .DS_Store diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index b35b318..75b1ad2 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -45,6 +45,12 @@ comment marker does not start a comment. To add a language, add an entry to `EXT `NAMES`, and reuse a language that has the same rules or make one with `language(...)`. Add a test to `packages/core/test/comments.test.ts` with a ref in a comment and a ref in a string. +In the YAML files that the config names in `yaml-values`, a whole value can also be a ref. To find +the values, `packages/core/src/values.ts` uses the [`yaml`](https://eemeli.org/yaml/) parser, which +has no dependencies of its own. esbuild bundles it into the CLI and the extension, so both packages +ship its license in `THIRD-PARTY-NOTICES`. When a bundle takes in another package, add its license +there too. + To check the lexer on real code, compare it with Shiki, which has the TextMate grammars of VS Code. Shiki is a dev dependency only: it is not in the CLI or the extension. @@ -66,8 +72,8 @@ the lexer, on repos that use the languages you changed. That file is the whole npm package, so it has no dependencies at run time. esbuild also writes the version from `package.json` into the bundle, for `--version` and the update check, and the agent guide `skills/iref/SKILL.md`, for `--guide`. It adds the version to the guide's frontmatter as -`metadata.interref-version`, so do not write a `metadata` key in `SKILL.md`. `prepack` copies the repo README and LICENSE into -`packages/cli`, so the npm page shows the README. +`metadata.interref-version`, so do not write a `metadata` key in `SKILL.md`. `prepack` copies the repo README, LICENSE and +THIRD-PARTY-NOTICES into `packages/cli`, so the npm page shows the README. `scripts/npm-readme.mjs` changes the relative links in the copy to GitHub URLs. `packages/cli/src/update.ts` has the network code. The update check reads the `latest` dist-tag diff --git a/README.md b/README.md index d9dfc79..8059a62 100644 --- a/README.md +++ b/README.md @@ -89,15 +89,18 @@ url = "iref:/docs/auth.md" # not a ref: it is in a string - In GraphQL, a `"""` description is a comment. - In JSON, a ref counts in a `//` or `/* */` comment (as in `tsconfig.json`). - In YAML, a value can also be a ref, but only in the files that the `yaml-values` key of the - [config file](#config-file) names. The value must be exactly one ref, and it can be plain or in - quotes. Examples are `spec: sync:/docs/auth.md#token-lifetime` and `- "iref:/docs/auth.md"`. An - item of a `[...]` or `{...}` collection also counts, as in - `specs: [sync:/docs/auth.md, sync:/docs/api.md]`. The ref must be the whole value, and the value - must be on one line. In these cases, the text is not a ref: + [config file](#config-file) names. interref reads these files with a YAML parser. The value must + be exactly one ref, and it can be plain or in quotes. Examples are + `spec: sync:/docs/auth.md#token-lifetime` and `- "iref:/docs/auth.md"`. An item of a `[...]` list + also counts, as in `specs: [sync:/docs/auth.md, sync:/docs/api.md]`, and so does a list that goes + across lines. The value can be on the line under its key, and it can have an anchor or a tag + before it. The ref must be the whole value, and the value must be on one line. In these cases, + the text is not a ref: - `note: see sync:/docs/auth.md`, because the value has other text before the ref. - `note: sync:/docs/auth.md, and more`, because the value has other text after the ref. - - A `|` block. - - A plain value that continues on the next line. + - A `|` or `>` block. + - A plain value that continues on the next line, or that continues the line before it. + - A key, as in `sync:/docs/auth.md: text`. interref finds the language from the file extension or the file name (for example `Dockerfile`, `Makefile`, `CMakeLists.txt`). A file with no extension can name its language in a `#!` line. A file @@ -307,7 +310,7 @@ an excluded file still resolve. | Problems | Broken refs get a red or yellow underline (`interref.diagnostics.enabled`). | | Quick fix | Cmd/Ctrl+. on a broken ref offers the suggested refs. | | Copy ref | Right-click in an editor or the explorer. Copies `iref:/path`, plus `#slug` of the heading above the cursor in Markdown. | -| Completion | In a comment, type `iref:/` or `iref:./` for paths, and `#` after a Markdown path for headings. | +| Completion | In a comment or a YAML value that can be a ref, type `iref:/` or `iref:./` for paths, and `#` after a Markdown path for headings. | | Graph | "interref: Show ref graph" (command palette, editor or explorer context menu). Pick 1 or 2 hops around the file, or the whole repo. | ### Graph preview diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES new file mode 100644 index 0000000..5295bca --- /dev/null +++ b/THIRD-PARTY-NOTICES @@ -0,0 +1,21 @@ +The interref CLI and the interref VS Code extension bundle the following +third-party software. Its license asks for the notice below in every copy. + +-------------------------------------------------------------------------------- + +yaml (https://github.com/eemeli/yaml) +ISC License + +Copyright Eemeli Aro + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/packages/cli/esbuild.mjs b/packages/cli/esbuild.mjs index 6976f2c..0cd4e41 100644 --- a/packages/cli/esbuild.mjs +++ b/packages/cli/esbuild.mjs @@ -25,5 +25,8 @@ await build({ INTERREF_VERSION: JSON.stringify(manifest.version), INTERREF_GUIDE: JSON.stringify(guide), }, + // The yaml package that core uses is CommonJS, and it requires Node modules such as `process`. + // An ES module has no `require`, so the bundle makes one. + banner: { js: 'import { createRequire } from "node:module";\nconst require = createRequire(import.meta.url);' }, logLevel: "warning", }); diff --git a/packages/cli/package.json b/packages/cli/package.json index 761acd8..91f4ac4 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -23,7 +23,8 @@ "iref": "./dist/interref.mjs" }, "files": [ - "dist/interref.mjs" + "dist/interref.mjs", + "THIRD-PARTY-NOTICES" ], "publishConfig": { "access": "public" @@ -33,7 +34,7 @@ }, "scripts": { "bundle": "node esbuild.mjs", - "prepack": "cp ../../LICENSE . && node ../../scripts/npm-readme.mjs", + "prepack": "cp ../../LICENSE ../../THIRD-PARTY-NOTICES . && node ../../scripts/npm-readme.mjs", "test": "node --test \"dist/test/**/*.test.js\"" }, "devDependencies": { diff --git a/packages/core/package.json b/packages/core/package.json index 6bf4063..b196a9b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -15,6 +15,9 @@ "scripts": { "test": "node --test \"dist/test/**/*.test.js\"" }, + "dependencies": { + "yaml": "^2.9.1" + }, "devDependencies": { "@types/node": "catalog:" } diff --git a/packages/core/src/comments.ts b/packages/core/src/comments.ts index bbf2098..417eb72 100644 --- a/packages/core/src/comments.ts +++ b/packages/core/src/comments.ts @@ -7,11 +7,12 @@ * tell a comment from a string, which is the only question that it has to answer. The language comes * from the file name, or from the `#!` line of a file that has no known extension. A file of an * unknown language has no comments, so it has no refs. In the YAML files that the config names, a - * value can also be a ref, if the whole value is one ref. + * value can also be a ref, if the whole value is one ref (see `values.ts`). */ import { posix } from "node:path"; import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; +import { yamlScalarSpans, yamlValueRefs } from "./values.js"; /** Offsets of one comment, its markers included (UTF-16 code units). */ export interface Span { @@ -303,23 +304,16 @@ const TEX = language( PERCENT_LINE, ); -/** - * Returns the column of the key of a YAML value. If the value is a list item (`- x`), it returns - * the column of the `-` instead. `before` is the text on the line of the value, from the start of - * the line to the value. Each line of the value has more indentation than this column. - */ -function yamlIndent(before: string): number { - return /^[ \t]*(?:-[ \t]+)+$/u.test(before) - ? before.lastIndexOf("-") - : (/^[ \t]*(?:-[ \t]+)*/u.exec(before)?.[0].length ?? 0); -} - const YAML_BLOCK_SCALAR: RuleSpec = { open: String.raw`(?<=(?:^|[:?-])[ \t]*)[|>][-+1-9]{0,2}(?=[ \t]*(?:#.*)?$)`, // The scalar ends at the first line that is not more indented than its key, or than its `-` when // the scalar is a list item (`- |`). close: (open, text) => { - const indent = yamlIndent(text.slice(text.lastIndexOf("\n", open.index - 1) + 1, open.index)); + const lineStart = text.lastIndexOf("\n", open.index - 1) + 1; + const before = text.slice(lineStart, open.index); + const indent = /^[ \t]*(?:-[ \t]+)+$/u.test(before) + ? before.lastIndexOf("-") + : (/^[ \t]*(?:-[ \t]+)*/u.exec(before)?.[0].length ?? 0); return new RegExp(`\\n(?=[ ]{0,${indent}}[^ \\r\\n])`, "gu"); }, }; @@ -623,19 +617,11 @@ function bracketBalance(code: string): number { const BRACKETS: Readonly> = { "{": /[{}]/gu, "(": /[()]/gu }; /** - * Adds the comments between `from` and `to` to `comments`. If `tokens` is given, it also adds the - * other tokens (strings) to `tokens`. With `until` (`{` or `(`), it stops after the closing bracket - * that has no opening one: the end of an interpolation. Returns where it stopped. + * Adds the comments between `from` and `to` to `comments`. With `until` (`{` or `(`), it stops + * after the closing bracket that has no opening one: the end of an interpolation. Returns where it + * stopped. */ -function lex( - text: string, - lang: Language, - from: number, - to: number, - comments: Span[], - until?: string, - tokens?: Span[], -): number { +function lex(text: string, lang: Language, from: number, to: number, comments: Span[], until?: string): number { const brackets = until === undefined ? undefined : BRACKETS[until]; let i = from; // The last character of code (not of a comment) before `i`, and the open brackets, for docstrings. @@ -676,7 +662,6 @@ function lex( comments.push({ start: at, end: end.end }); } else { if (rule.embed !== undefined) lex(text, rule.embed(open), openEnd, end.contentEnd, comments); - tokens?.push({ start: at, end: end.end }); lastCode = text.charAt(end.end - 1); } next = Math.max(end.end, at + 1); @@ -700,124 +685,11 @@ export function commentSpans(path: string, text: string): Span[] | undefined { } /** - * Matches the text before a value in block context: one or more `- ` at the start of the line, or - * `key: `. + * Returns where the plain and quoted scalars of a YAML file are written, keys too, so that the VS + * Code completion can offer paths for a ref that starts a value. Other files have none. */ -const YAML_BLOCK_VALUE = /(?:^[ \t]*(?:-[ \t]+)+|[^\s:]:[ \t]+)$/u; -/** - * Matches the text after a value in block context: nothing, only spaces, or spaces and then a - * comment. - */ -const YAML_BLOCK_END = /^(?:[ \t]+#.*|[ \t]*)\r?$/u; -/** - * Matches the text before a value in a flow collection (`[...]` or `{...}`): `[`, `{`, `,` or - * `key: `. - */ -const YAML_FLOW_VALUE = /(?:[[{,][ \t]*|[^\s:]:[ \t]+)$/u; -/** Matches the text after a value in a flow collection: `,`, `]`, `}` or a comment. */ -const YAML_FLOW_END = /^(?:[ \t]*[,\]}]|[ \t]+#)/u; -/** - * Skips blank lines. Then it captures the indentation of the next line, and the first character of - * that line. If that line is a comment, the second group is empty. - */ -const YAML_NEXT_LINE = /(?:\n[ \t]*\r?(?=\n))*\n( *)([^\s#]?)/uy; - -/** - * Returns a function that finds the span that contains an offset. Call the function with offsets - * that never decrease, so that it walks through the spans only once, in order. - */ -function spanFinder(spans: readonly Span[]): (at: number) => Span | undefined { - let index = 0; - return (at) => { - while ((spans[index]?.end ?? Number.POSITIVE_INFINITY) <= at) index++; - const span = spans[index]; - return span !== undefined && span.start <= at ? span : undefined; - }; -} - -/** - * Finds the flow collections (`[...]` and `{...}`) of a YAML text. It returns only the outermost - * collections. It also returns a copy of the text in which each comma between the items of a - * collection is changed to a space, so that `[a,b]` holds two separate values. A collection can - * start only where a block value can start, so the bracket in `key: a[0]` does not start a - * collection. A bracket or a comma in a string or in a comment does not count. The `skipped` spans - * mark these strings and comments, in order. - */ -function flowCollections(text: string, skipped: readonly Span[]): { flows: Span[]; items: string } { - const flows: Span[] = []; - const skippedAt = spanFinder(skipped); - let items = ""; - let copied = 0; - let depth = 0; - let start = 0; - for (const match of text.matchAll(/[[\]{},]/gu)) { - const at = match.index; - if (skippedAt(at) !== undefined) continue; - if (match[0] === ",") { - if (depth === 0) continue; - items += `${text.slice(copied, at)} `; - copied = at + 1; - } else if (match[0] === "[" || match[0] === "{") { - if (depth > 0) depth++; - else if (YAML_BLOCK_VALUE.test(text.slice(text.lastIndexOf("\n", at - 1) + 1, at))) { - depth = 1; - start = at; - } - } else if (depth > 0) { - depth--; - if (depth === 0) flows.push({ start, end: at + 1 }); - } - } - if (depth > 0) flows.push({ start, end: text.length }); - return { flows, items: items + text.slice(copied) }; -} - -/** - * Returns whether a plain value continues on the next lines, as a YAML plain scalar can. The value - * is at the end of the line that ends at `lineEnd`. The value continues if the next line that is - * not blank is not a comment, and has more indentation than the key of the value (or than its `-`). - * `before` is the text on the line of the value, from the start of the line to the value. - */ -function continues(text: string, lineEnd: number, before: string): boolean { - YAML_NEXT_LINE.lastIndex = lineEnd; - const next = YAML_NEXT_LINE.exec(text); - return (next?.[2] ?? "") !== "" && (next?.[1]?.length ?? 0) > yamlIndent(before); -} - -/** - * Returns the refs of a YAML file that are the whole value of a scalar. The scalar can be plain or - * in quotes, and it must be on one line. In a flow collection, a value can also start after `[`, - * `{` or `,`, and it can end before `,`, `]` or `}`. Outside a flow collection, only a comment can - * follow the value. - */ -function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { - const comments: Span[] = []; - const tokens: Span[] = []; - lex(text, YAML, 0, text.length, comments, undefined, tokens); - const { flows, items } = flowCollections(text, [...comments, ...tokens].sort((a, b) => a.start - b.start)); - const commentAt = spanFinder(comments); - const tokenAt = spanFinder(tokens); - const flowAt = spanFinder(flows); - return scanRefs(items, protocols).filter((ref) => { - if (commentAt(ref.start) !== undefined) return false; - const token = tokenAt(ref.start); - // `quoted` is true if the token is a quoted string that contains only the ref. A block scalar - // (`|` or `>`) is not a quoted string. - const quoted = - token !== undefined && /["']/u.test(text.charAt(token.start)) && token.start + 1 === ref.start && token.end - 1 === ref.end; - if (token !== undefined && !quoted) return false; - const start = token?.start ?? ref.start; - const end = token?.end ?? ref.end; - const lineStart = text.lastIndexOf("\n", start - 1) + 1; - const newline = text.indexOf("\n", end); - const lineEnd = newline < 0 ? text.length : newline; - const before = text.slice(lineStart, start); - const after = text.slice(end, lineEnd); - if (flowAt(ref.start) !== undefined) return YAML_FLOW_VALUE.test(before) && YAML_FLOW_END.test(after); - if (!YAML_BLOCK_VALUE.test(before) || !YAML_BLOCK_END.test(after)) return false; - // A plain value can continue on the next lines. A comment at the end of the line stops it. - return quoted || after.includes("#") || !continues(text, lineEnd, before); - }); +export function valueSpans(path: string, text: string): Span[] { + return languageOf(path, text) === YAML ? yamlScalarSpans(text) : []; } /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index aa8d9bc..3c457be 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,4 @@ -export { commentSpans, findRefs } from "./comments.js"; +export { commentSpans, findRefs, valueSpans } from "./comments.js"; export type { Span } from "./comments.js"; export { checkRef, checkText, editDistance, scanRepo, similarPaths } from "./check.js"; export type { RefRecord, RepoScan, ResolvedTarget, Status } from "./check.js"; diff --git a/packages/core/src/values.ts b/packages/core/src/values.ts new file mode 100644 index 0000000..13b041b --- /dev/null +++ b/packages/core/src/values.ts @@ -0,0 +1,68 @@ +/** + * Finds the refs in YAML values. In the YAML files that the config names in `yaml-values`, a value + * can also be a ref, if the whole value is one ref. To know where each value starts and ends, the + * `yaml` parser reads the file: a value can be on the line under its key, come after an anchor or a + * tag, or be an item of a `[...]` list that goes across lines. + */ + +import { parseAllDocuments, Scalar, visit } from "yaml"; +import type { Span } from "./comments.js"; +import { scanRefs, type RefMatch } from "./syntax.js"; + +interface YamlScalar { + /** Where the scalar is written, with its quotes. */ + readonly start: number; + readonly end: number; + /** The scalar is in quotes. */ + readonly quoted: boolean; + /** The scalar is the key of a pair, not a value. */ + readonly key: boolean; + readonly value: unknown; +} + +/** + * Returns the plain and quoted scalars of every document in `text`, keys too. A block scalar (`|` or + * `>`) is not one of them. A file that is not valid YAML still has the scalars that the parser can + * read. + */ +function yamlScalars(text: string): YamlScalar[] { + const scalars: YamlScalar[] = []; + for (const document of parseAllDocuments(text)) { + visit(document, { + Scalar(key, node) { + const quoted = node.type === Scalar.QUOTE_DOUBLE || node.type === Scalar.QUOTE_SINGLE; + if (node.range == null || (!quoted && node.type !== Scalar.PLAIN)) return; + scalars.push({ start: node.range[0], end: node.range[1], quoted, key: key === "key", value: node.value }); + }, + }); + } + return scalars.sort((a, b) => a.start - b.start); +} + +/** + * Returns the refs of a YAML text that are the whole value of a scalar, plain or in quotes. The key + * of a pair is not a value. The text of the value must be the value itself, so a value with an + * escape or that goes on in the next line is not a ref. + */ +export function yamlValueRefs(text: string, protocols: readonly string[]): RefMatch[] { + const refs: RefMatch[] = []; + for (const scalar of yamlScalars(text)) { + if (scalar.key || typeof scalar.value !== "string") continue; + const quote = scalar.quoted ? 1 : 0; + const start = scalar.start + quote; + if (text.slice(start, scalar.end - quote) !== scalar.value) continue; + const found = scanRefs(scalar.value, protocols); + const ref = found[0]; + if (found.length !== 1 || ref === undefined || ref.start !== 0 || ref.end !== scalar.value.length) continue; + refs.push({ ...ref, start, end: start + ref.end }); + } + return refs; +} + +/** + * Returns where the plain and quoted scalars of a YAML text are written, keys too, since a ref that + * is still being typed, such as `- sync:`, reads as a key. + */ +export function yamlScalarSpans(text: string): Span[] { + return yamlScalars(text).map(({ start, end }) => ({ start, end })); +} diff --git a/packages/core/test/comments.test.ts b/packages/core/test/comments.test.ts index 274440e..68fef57 100644 --- a/packages/core/test/comments.test.ts +++ b/packages/core/test/comments.test.ts @@ -36,27 +36,43 @@ describe("findRefs in YAML values", () => { const values = (...lines: string[]): string[] => findRefs("a.yaml", lines.join("\n"), DEFAULT_PROTOCOLS, true).map((ref) => ref.raw); - it("finds a ref that is a whole value, also an item of a flow collection", () => { + it("finds a ref that is a whole value, plain or in quotes, also an item of a flow collection", () => { assert.deepEqual( values( "a: iref:/yes1", - '- - "iref:/yes2" # a comment', - "b: [iref:/yes3,iref:/yes4, 'iref:/yes5']", - "c: {d: iref:/yes6, e: [x,", - " y, iref:/yes7]}", - "f: iref:/yes8", + 'b: "iref:/yes2" # a comment', + "c:", + " - - 'iref:/yes3'", + "d: [iref:/yes4,iref:/yes5, 'iref:/yes6']", + "e: {f: iref:/yes7, g: [x,", + " y, iref:/yes8]}", + "h: iref:/yes9", "", " # a comment", - "g:", - " - iref:/yes9", + "i:", + " - iref:/yes10", " - x", ), - ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5", "iref:/yes6", "iref:/yes7", "iref:/yes8", "iref:/yes9"], + ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5", "iref:/yes6", "iref:/yes7", "iref:/yes8", "iref:/yes9", "iref:/yes10"], ); }); - it("does not find a ref in a longer value", () => { - for (const line of [ + it("finds a value under its key, after an anchor or a tag, and in a list that goes across lines", () => { + assert.deepEqual( + values("a:", " iref:/yes1", "b: &x iref:/yes2", "c: !!str iref:/yes3", "d: *x", "e: [", " iref:/yes4,", " iref:/yes5", "]"), + ["iref:/yes1", "iref:/yes2", "iref:/yes3", "iref:/yes4", "iref:/yes5"], + ); + }); + + it("keeps the offsets of the ref, also in quotes", () => { + const text = "\uFEFFa: 'iref:/yes'\r\n"; + const [ref] = findRefs("a.yaml", text, DEFAULT_PROTOCOLS, true); + assert.equal(ref?.start, text.indexOf("iref:/yes")); + assert.equal(ref?.end, text.indexOf("'\r")); + }); + + it("does not find a ref in a longer value, a block or a key", () => { + for (const text of [ "key: sync:/docs/a.md, see also the model", "note: Tokens, sync:/docs/a.md", "note: foo {sync:/docs/a.md}", @@ -64,13 +80,22 @@ describe("findRefs in YAML values", () => { 'key: foo - "sync:/docs/a.md"', "key: a[sync:/docs/a.md]", "key: [sync:/docs/a.md and more]", + "key: |-\n sync:/docs/a.md", + "sync:/docs/a.md: x", + "{sync:/docs/a.md}", ]) { - assert.deepEqual(values(line), [], line); + assert.deepEqual(values(text), [], text); } }); - it("does not find a plain ref that the next lines continue", () => { + it("does not find a plain ref that continues an earlier line or that the next lines continue", () => { assert.deepEqual(values("a: iref:/no", " goes on", "b:", " - iref:/no", "", " goes on", "c: iref:/yes"), ["iref:/yes"]); + assert.deepEqual(values("a: some text", " - iref:/no", "b: x"), []); + assert.deepEqual(values("- some text", " - iref:/no"), []); + }); + + it("still finds the later values after a bracket that is not closed", () => { + assert.deepEqual(values("title: [draft", "k: iref:/yes"), ["iref:/yes"]); }); }); diff --git a/packages/vscode/.vscodeignore b/packages/vscode/.vscodeignore index 987cf68..9aad646 100644 --- a/packages/vscode/.vscodeignore +++ b/packages/vscode/.vscodeignore @@ -3,3 +3,4 @@ !package.json !README.md !LICENSE +!THIRD-PARTY-NOTICES diff --git a/packages/vscode/README.md b/packages/vscode/README.md index ba7519e..76867e6 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -6,8 +6,9 @@ This extension makes `iref:` links in comments clickable, and it shows broken li - Hover over a ref to see the start of its target. - Broken refs show in Problems. Cmd/Ctrl+. offers fixes. - "Copy ref" in the editor or explorer context menu copies `iref:/path#heading`. -- In a comment, type `iref:/`, `iref:./` or `#` to get completions for paths and headings. `iref:`, `sync:` and the - other protocols in the config file work the same way. +- In a comment, or in a YAML value that can be a ref, type `iref:/`, `iref:./` or `#` to get + completions for paths and headings. `iref:`, `sync:` and the other protocols in the config file + work the same way. - "interref: Show ref graph" opens the link graph around a file, or for the whole repo. You must install a viewer extension first: Draw.io Integration (`hediet.vscode-drawio`, the default), or for Mermaid the official Mermaid extension (`MermaidChart.vscode-mermaid-chart`) or Mermaid diff --git a/packages/vscode/package.json b/packages/vscode/package.json index 340d3c4..72eb577 100644 --- a/packages/vscode/package.json +++ b/packages/vscode/package.json @@ -107,7 +107,7 @@ }, "scripts": { "bundle": "node esbuild.mjs", - "package": "cp ../../LICENSE . && vsce package --no-dependencies --out interref.vsix" + "package": "cp ../../LICENSE ../../THIRD-PARTY-NOTICES . && vsce package --no-dependencies --out interref.vsix" }, "devDependencies": { "@interref/core": "workspace:*", diff --git a/packages/vscode/src/features.ts b/packages/vscode/src/features.ts index 16ffd1b..5990ec7 100644 --- a/packages/vscode/src/features.ts +++ b/packages/vscode/src/features.ts @@ -8,8 +8,10 @@ import { isMarkdownPath, protocolPattern, resolveTarget, + valueSpans, type RefRecord, type Repo, + type Span, } from "@interref/core"; import * as vscode from "vscode"; import type { Located, Repos } from "./repos.js"; @@ -265,10 +267,15 @@ export class Completion implements vscode.CompletionItemProvider { const { repo, path: source } = located; const partial = partialRef(repo.config.protocols).exec(before); if (partial === null) return undefined; - // Only a ref in a comment counts, so offer nothing in code, strings or Markdown text. + // Only a ref in a comment counts, or a ref that is a whole YAML value in a file that the config + // names, so offer nothing in code, strings or Markdown text. const offset = document.offsetAt(position); - const comments = commentSpans(source, document.getText()) ?? []; - if (!comments.some((span) => span.start < offset && offset <= span.end)) return undefined; + const text = document.getText(); + const inComment = (commentSpans(source, text) ?? []).some((span) => span.start < offset && offset <= span.end); + // A ref in a YAML value is the whole value: it starts the scalar, or comes right after its quote. + const refStart = offset - before.length + partial.index; + const startsValue = (span: Span): boolean => span.start === refStart || span.start + 1 === refStart; + if (!inComment && !(repo.readsYamlValues(source) && valueSpans(source, text).some(startsValue))) return undefined; const typedPath = partial[2] ?? ""; const typedFragment = partial[3]; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47fe4db..2dfdb4e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -204,6 +204,10 @@ importers: version: 0.28.2 packages/core: + dependencies: + yaml: + specifier: ^2.9.1 + version: 2.9.1 devDependencies: '@types/node': specifier: 'catalog:' @@ -1318,6 +1322,11 @@ packages: yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + yaml@2.9.1: + resolution: {integrity: sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==} + engines: {node: '>= 14.6'} + hasBin: true + yauzl@3.4.0: resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==} engines: {node: '>=12'} @@ -2336,6 +2345,8 @@ snapshots: yallist@4.0.0: {} + yaml@2.9.1: {} + yauzl@3.4.0: dependencies: pend: 1.2.0 diff --git a/skills/iref/SKILL.md b/skills/iref/SKILL.md index cd30c11..1fd0f21 100644 --- a/skills/iref/SKILL.md +++ b/skills/iref/SKILL.md @@ -73,8 +73,8 @@ an `argparse` description that uses `__doc__`. In the YAML files that the `yaml-values` key of the config file names, a value can also be a ref. The value must be exactly one ref, and it can be plain or in quotes, for example `spec: sync:/docs/auth.md#token-lifetime`. An item of a -`[...]` or `{...}` collection also counts. The ref must be the whole value, and -the value must be on one line. +`[...]` list also counts. The ref must be the whole value, and the value must +be on one line. A key and a `|` or `>` block are not refs. A file type that interref does not know (for example `.txt`) has no refs. From 0a040af5b102f1aa4a0576e86417654f50c14ce5 Mon Sep 17 00:00:00 2001 From: mondaychen Date: Fri, 4 Dec 2026 10:14:23 -0500 Subject: [PATCH 4/4] Fix four problems with YAML values that a review found - A completion or a quick fix that puts a path into a `[...]` list no longer breaks the list when the file name has a `,`. `encodeRefPath` now writes `,` as `%2C`. This also keeps a `,` at the end of a file name, which the scanner dropped as punctuation. - A quoted value with no closing quote at the end of the file is not a ref. Before, the parser dropped the last character of the path, so `a: 'sync:/docs/auth.md` gave the ref `sync:/docs/auth.m`. - Completion in a YAML value reads the ref from the start of the value that the cursor is in. Thus `[sync:/a.md,sync:/]` now gives paths for the second item, and `key: (sync:/` gives no paths, since the value that it makes is not a ref. `valueStartAt` replaces `valueSpans`. Co-Authored-By: Claude Opus 5.5 --- packages/core/src/comments.ts | 11 +++++----- packages/core/src/index.ts | 2 +- packages/core/src/resolve.ts | 7 ++++-- packages/core/src/values.ts | 22 ++++++++++++++----- packages/core/test/comments.test.ts | 33 ++++++++++++++++++++++++++++- packages/core/test/resolve.test.ts | 1 + packages/vscode/src/features.ts | 22 +++++++++++-------- 7 files changed, 75 insertions(+), 23 deletions(-) diff --git a/packages/core/src/comments.ts b/packages/core/src/comments.ts index 417eb72..2472750 100644 --- a/packages/core/src/comments.ts +++ b/packages/core/src/comments.ts @@ -12,7 +12,7 @@ import { posix } from "node:path"; import { DEFAULT_PROTOCOLS, scanRefs, type RefMatch } from "./syntax.js"; -import { yamlScalarSpans, yamlValueRefs } from "./values.js"; +import { yamlValueRefs, yamlValueStartAt } from "./values.js"; /** Offsets of one comment, its markers included (UTF-16 code units). */ export interface Span { @@ -685,11 +685,12 @@ export function commentSpans(path: string, text: string): Span[] | undefined { } /** - * Returns where the plain and quoted scalars of a YAML file are written, keys too, so that the VS - * Code completion can offer paths for a ref that starts a value. Other files have none. + * In a YAML file, returns where the value that the cursor at `offset` is in starts, so that the VS + * Code completion can offer paths for a ref that starts a value. See `yamlValueStartAt`. Other files + * have none. */ -export function valueSpans(path: string, text: string): Span[] { - return languageOf(path, text) === YAML ? yamlScalarSpans(text) : []; +export function valueStartAt(path: string, text: string, offset: number): number | undefined { + return languageOf(path, text) === YAML ? yamlValueStartAt(text, offset) : undefined; } /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3c457be..a6ffa72 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,4 @@ -export { commentSpans, findRefs, valueSpans } from "./comments.js"; +export { commentSpans, findRefs, valueStartAt } from "./comments.js"; export type { Span } from "./comments.js"; export { checkRef, checkText, editDistance, scanRepo, similarPaths } from "./check.js"; export type { RefRecord, RepoScan, ResolvedTarget, Status } from "./check.js"; diff --git a/packages/core/src/resolve.ts b/packages/core/src/resolve.ts index e5e0dd6..dbf1078 100644 --- a/packages/core/src/resolve.ts +++ b/packages/core/src/resolve.ts @@ -116,9 +116,12 @@ export function parseFragment(encoded: string): Result { return { ok: true, value: { kind: "heading", slug: fragment } }; } -const UNSAFE_PATH_CHAR = /[\s%#"'`<>()[\]{}]/gu; +const UNSAFE_PATH_CHAR = /[\s%#"'`<>()[\]{},]/gu; -/** Percent-encodes the characters that would end a ref or change its meaning. */ +/** + * Percent-encodes the characters that would end a ref or change its meaning. A `,` ends a ref in a + * YAML `[...]` or `{...}` value, and a `,` at the end of a ref is dropped as punctuation. + */ export function encodeRefPath(path: string): string { return path.replace(UNSAFE_PATH_CHAR, (ch) => Array.from(new TextEncoder().encode(ch), (byte) => `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join(""), diff --git a/packages/core/src/values.ts b/packages/core/src/values.ts index 13b041b..505c1f8 100644 --- a/packages/core/src/values.ts +++ b/packages/core/src/values.ts @@ -6,7 +6,6 @@ */ import { parseAllDocuments, Scalar, visit } from "yaml"; -import type { Span } from "./comments.js"; import { scanRefs, type RefMatch } from "./syntax.js"; interface YamlScalar { @@ -49,6 +48,9 @@ export function yamlValueRefs(text: string, protocols: readonly string[]): RefMa for (const scalar of yamlScalars(text)) { if (scalar.key || typeof scalar.value !== "string") continue; const quote = scalar.quoted ? 1 : 0; + // A quoted scalar with no closing quote is not a value: the parser still drops its last + // character, as if it were the quote. + if (scalar.quoted && (scalar.end - scalar.start < 2 || text[scalar.end - 1] !== text[scalar.start])) continue; const start = scalar.start + quote; if (text.slice(start, scalar.end - quote) !== scalar.value) continue; const found = scanRefs(scalar.value, protocols); @@ -60,9 +62,19 @@ export function yamlValueRefs(text: string, protocols: readonly string[]): RefMa } /** - * Returns where the plain and quoted scalars of a YAML text are written, keys too, since a ref that - * is still being typed, such as `- sync:`, reads as a key. + * Returns where the text of the last scalar that starts at or before `offset` starts, after its + * quote, if that scalar starts on the line of `offset`. Keys count too, since a ref that is still + * being typed, such as `- sync:`, reads as a key. The VS Code completion offers paths only for a ref + * that starts there, because only a ref that is the whole value counts. */ -export function yamlScalarSpans(text: string): Span[] { - return yamlScalars(text).map(({ start, end }) => ({ start, end })); +export function yamlValueStartAt(text: string, offset: number): number | undefined { + let found: number | undefined; + for (const scalar of yamlScalars(text)) { + const start = scalar.start + (scalar.quoted ? 1 : 0); + if (start > offset) break; + // Skip the empty value that the parser adds after a key, as after `- sync:`. + if (scalar.end > scalar.start) found = start; + } + if (found === undefined || /[\r\n]/u.test(text.slice(found, offset))) return undefined; + return found; } diff --git a/packages/core/test/comments.test.ts b/packages/core/test/comments.test.ts index 68fef57..b1a9779 100644 --- a/packages/core/test/comments.test.ts +++ b/packages/core/test/comments.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { commentSpans, findRefs } from "../src/comments.js"; +import { commentSpans, findRefs, valueStartAt } from "../src/comments.js"; import { DEFAULT_PROTOCOLS } from "../src/syntax.js"; // In each text, refs that must be found point at /yes…, and refs that must not be found point at /no. @@ -97,6 +97,37 @@ describe("findRefs in YAML values", () => { it("still finds the later values after a bracket that is not closed", () => { assert.deepEqual(values("title: [draft", "k: iref:/yes"), ["iref:/yes"]); }); + + it("does not find a ref in quotes that are not closed", () => { + for (const text of ["a: 'iref:/docs/no.md", 'a: "iref:/docs/no.md', "a: 'iref:/docs/no.md\n", "a: '", "a: \""]) { + assert.deepEqual(values(text), [], text); + } + }); +}); + +describe("valueStartAt", () => { + // The text before `|` is the text before the cursor. + const startAt = (path: string, marked: string): number | undefined => { + const offset = marked.indexOf("|"); + return valueStartAt(path, marked.slice(0, offset) + marked.slice(offset + 1), offset); + }; + + it("gives the start of the value that the cursor is in, after its quote", () => { + assert.equal(startAt("a.yaml", "spec: sync:/do|"), 6); + assert.equal(startAt("a.yaml", "spec: 'sync:/do|'"), 7); + assert.equal(startAt("a.yaml", 'spec: "sync:/do|'), 7); + assert.equal(startAt("a.yaml", "- sync:|"), 2); + }); + + it("gives the start of the list item that the cursor is in", () => { + assert.equal(startAt("a.yaml", "specs: [sync:/a.md,sync:/|]"), 19); + assert.equal(startAt("a.yaml", "specs: [sync:/a.md, sync:/|]"), 20); + }); + + it("gives no start for a value on an earlier line or in a file that is not YAML", () => { + assert.equal(startAt("a.yaml", "a: b\n|"), undefined); + assert.equal(startAt("a.ts", "spec: sync:/|"), undefined); + }); }); describe("comments by language", () => { diff --git a/packages/core/test/resolve.test.ts b/packages/core/test/resolve.test.ts index dd95a53..297fd0a 100644 --- a/packages/core/test/resolve.test.ts +++ b/packages/core/test/resolve.test.ts @@ -63,5 +63,6 @@ describe("formatRef", () => { it("encodes characters that would end the ref", () => { assert.equal(encodeRefPath("a b#(c).md"), "a%20b%23%28c%29.md"); + assert.equal(encodeRefPath("a,b.md"), "a%2Cb.md"); }); }); diff --git a/packages/vscode/src/features.ts b/packages/vscode/src/features.ts index 5990ec7..9f19af2 100644 --- a/packages/vscode/src/features.ts +++ b/packages/vscode/src/features.ts @@ -8,10 +8,9 @@ import { isMarkdownPath, protocolPattern, resolveTarget, - valueSpans, + valueStartAt, type RefRecord, type Repo, - type Span, } from "@interref/core"; import * as vscode from "vscode"; import type { Located, Repos } from "./repos.js"; @@ -265,17 +264,22 @@ export class Completion implements vscode.CompletionItemProvider { const located = await this.repos.locate(document.uri); if (located === undefined) return undefined; const { repo, path: source } = located; - const partial = partialRef(repo.config.protocols).exec(before); - if (partial === null) return undefined; // Only a ref in a comment counts, or a ref that is a whole YAML value in a file that the config // names, so offer nothing in code, strings or Markdown text. const offset = document.offsetAt(position); const text = document.getText(); - const inComment = (commentSpans(source, text) ?? []).some((span) => span.start < offset && offset <= span.end); - // A ref in a YAML value is the whole value: it starts the scalar, or comes right after its quote. - const refStart = offset - before.length + partial.index; - const startsValue = (span: Span): boolean => span.start === refStart || span.start + 1 === refStart; - if (!inComment && !(repo.readsYamlValues(source) && valueSpans(source, text).some(startsValue))) return undefined; + const pattern = partialRef(repo.config.protocols); + let partial: RegExpExecArray | null = null; + if ((commentSpans(source, text) ?? []).some((span) => span.start < offset && offset <= span.end)) { + partial = pattern.exec(before); + } else if (repo.readsYamlValues(source)) { + // A ref in a YAML value is the whole value: it starts the value that the cursor is in, after + // its quote. Read from that start, so that an earlier item of a `[...]` list is not part of it. + const start = valueStartAt(source, text, offset); + const match = start === undefined ? null : pattern.exec(text.slice(start, offset)); + if (match?.index === 0) partial = match; + } + if (partial === null) return undefined; const typedPath = partial[2] ?? ""; const typedFragment = partial[3];