@trackunit/repo-checks 0.0.21 → 0.0.22

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.
@@ -2,9 +2,11 @@ import type { ReferenceConstruct } from "./extract";
2
2
  /**
3
3
  * Why a reference was reported: its target doesn't exist on disk (`missing`), exists only under
4
4
  * different letter case (`caseMismatch`), or exists but its `#fragment` names no heading or anchor
5
- * in it (`missingAnchor`).
5
+ * in it (`missingAnchor`); or, from the storybook-links check, its `?path=/<type>/<id>` names an ID
6
+ * in none of the given Storybook indexes (`unknownStoryId`) or one that is there only as the other
7
+ * entry type, a `/docs/` link to a story or a `/story/` link to a docs page (`wrongStoryType`).
6
8
  */
7
- export type FindingReason = "missing" | "caseMismatch" | "missingAnchor";
9
+ export type FindingReason = "missing" | "caseMismatch" | "missingAnchor" | "unknownStoryId" | "wrongStoryType";
8
10
  /** One reported doc reference. */
9
11
  export interface Finding {
10
12
  /** The document, as a POSIX path relative to the repository root. */
@@ -17,7 +19,10 @@ export interface Finding {
17
19
  readonly target: string;
18
20
  readonly kind: ReferenceConstruct;
19
21
  readonly reason: FindingReason;
20
- /** A replacement for `target` that would resolve, when exactly one is known: the on-disk casing of a `caseMismatch`. */
22
+ /**
23
+ * A replacement for `target` that would resolve, when exactly one is known: the on-disk casing of
24
+ * a `caseMismatch`, or the link with `/docs/` and `/story/` swapped of a `wrongStoryType`.
25
+ */
21
26
  readonly suggestion?: string;
22
27
  }
23
28
  /** Order findings by file, then line, then column, so output is the same on every host. */
@@ -7,6 +7,12 @@ import { z } from "zod";
7
7
  */
8
8
  /** Conventional generated-output locations, matched against the repo-relative path. */
9
9
  export declare const DEFAULT_IGNORE: ReadonlyArray<string>;
10
+ /** A list option that has defaults, so it takes `{ extend: [...] }` or `{ replace: [...] }`, never a bare array. */
11
+ export declare const listOverrideSchema: (item: z.ZodType<string>) => z.ZodType<ListOverride, z.ZodTypeDef, ListOverride>;
12
+ export interface ListOverride {
13
+ readonly extend?: ReadonlyArray<string>;
14
+ readonly replace?: ReadonlyArray<string>;
15
+ }
10
16
  /** Which markdown constructs are checked: `links`, `images`, `definitions`, and `inlineCode` spans. */
11
17
  export interface ConstructToggles {
12
18
  readonly links: boolean;
@@ -35,42 +41,19 @@ export declare const strictObjectNamingKeys: <TShape extends z.ZodRawShape>(shap
35
41
  readonly noun: string;
36
42
  readonly expected: string;
37
43
  }) => z.ZodObject<TShape, "strict">;
44
+ /** A repo-relative glob: a leading `/` or `./` or a trailing `/` would silently match no document. */
45
+ export declare const excludeGlobSchema: z.ZodEffects<z.ZodString, string, string>;
46
+ /** A list with no defaults, so a plain array; the `{ extend }` and `{ replace }` forms are rejected as meaningless. */
47
+ export declare const plainListSchema: (item: z.ZodType<string>, { key, of }: {
48
+ readonly key: string;
49
+ readonly of: string;
50
+ }) => z.ZodArray<z.ZodType<string>>;
38
51
  /** The `docReferences` section of `repo-checks.config.json`, as written. */
39
52
  export declare const docReferencesConfigSchema: z.ZodObject<{
40
53
  rootDir: z.ZodOptional<z.ZodString>;
41
- ignore: z.ZodOptional<z.ZodEffects<z.ZodObject<{
42
- extend: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
43
- replace: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
44
- }, "strict", z.ZodTypeAny, {
45
- extend?: string[] | undefined;
46
- replace?: string[] | undefined;
47
- }, {
48
- extend?: string[] | undefined;
49
- replace?: string[] | undefined;
50
- }>, {
51
- extend?: string[] | undefined;
52
- replace?: string[] | undefined;
53
- }, {
54
- extend?: string[] | undefined;
55
- replace?: string[] | undefined;
56
- }>>;
57
- exclude: z.ZodOptional<z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">>;
58
- placeholders: z.ZodOptional<z.ZodEffects<z.ZodObject<{
59
- extend: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
60
- replace: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
61
- }, "strict", z.ZodTypeAny, {
62
- extend?: string[] | undefined;
63
- replace?: string[] | undefined;
64
- }, {
65
- extend?: string[] | undefined;
66
- replace?: string[] | undefined;
67
- }>, {
68
- extend?: string[] | undefined;
69
- replace?: string[] | undefined;
70
- }, {
71
- extend?: string[] | undefined;
72
- replace?: string[] | undefined;
73
- }>>;
54
+ ignore: z.ZodOptional<z.ZodType<ListOverride, z.ZodTypeDef, ListOverride>>;
55
+ exclude: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
56
+ placeholders: z.ZodOptional<z.ZodType<ListOverride, z.ZodTypeDef, ListOverride>>;
74
57
  constructs: z.ZodOptional<z.ZodObject<{
75
58
  links: z.ZodOptional<z.ZodBoolean>;
76
59
  images: z.ZodOptional<z.ZodBoolean>;
@@ -91,15 +74,9 @@ export declare const docReferencesConfigSchema: z.ZodObject<{
91
74
  bareFilenames: z.ZodOptional<z.ZodBoolean>;
92
75
  }, "strict", z.ZodTypeAny, {
93
76
  rootDir?: string | undefined;
94
- ignore?: {
95
- extend?: string[] | undefined;
96
- replace?: string[] | undefined;
97
- } | undefined;
77
+ ignore?: ListOverride | undefined;
98
78
  exclude?: string[] | undefined;
99
- placeholders?: {
100
- extend?: string[] | undefined;
101
- replace?: string[] | undefined;
102
- } | undefined;
79
+ placeholders?: ListOverride | undefined;
103
80
  constructs?: {
104
81
  inlineCode?: boolean | undefined;
105
82
  links?: boolean | undefined;
@@ -110,15 +87,9 @@ export declare const docReferencesConfigSchema: z.ZodObject<{
110
87
  bareFilenames?: boolean | undefined;
111
88
  }, {
112
89
  rootDir?: string | undefined;
113
- ignore?: {
114
- extend?: string[] | undefined;
115
- replace?: string[] | undefined;
116
- } | undefined;
90
+ ignore?: ListOverride | undefined;
117
91
  exclude?: string[] | undefined;
118
- placeholders?: {
119
- extend?: string[] | undefined;
120
- replace?: string[] | undefined;
121
- } | undefined;
92
+ placeholders?: ListOverride | undefined;
122
93
  constructs?: {
123
94
  inlineCode?: boolean | undefined;
124
95
  links?: boolean | undefined;
@@ -152,6 +123,8 @@ export interface DocsSettings {
152
123
  /** Check inline code without a `/`, such as `` `README.md` `` (see `classify.ts`). */
153
124
  readonly bareFilenames: boolean;
154
125
  }
126
+ /** A list option's resolved value: `replace` when given, otherwise the defaults plus any `extend`. */
127
+ export declare const applyOverride: (defaults: ReadonlyArray<string>, override: ListOverride | undefined) => ReadonlyArray<string>;
155
128
  /** The resolved settings when no config is given. */
156
129
  export declare const DEFAULT_DOCS_SETTINGS: DocsSettings;
157
130
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseDocsSettings = exports.DEFAULT_DOCS_SETTINGS = exports.formatConfigIssues = exports.docReferencesConfigSchema = exports.strictObjectNamingKeys = exports.DEFAULT_BARE_FILENAMES = exports.DEFAULT_DIRECTORIES = exports.DEFAULT_CONSTRUCTS = exports.DEFAULT_IGNORE = void 0;
3
+ exports.parseDocsSettings = exports.DEFAULT_DOCS_SETTINGS = exports.applyOverride = exports.formatConfigIssues = exports.docReferencesConfigSchema = exports.plainListSchema = exports.excludeGlobSchema = exports.strictObjectNamingKeys = exports.DEFAULT_BARE_FILENAMES = exports.DEFAULT_DIRECTORIES = exports.DEFAULT_CONSTRUCTS = exports.listOverrideSchema = exports.DEFAULT_IGNORE = void 0;
4
4
  const zod_1 = require("zod");
5
5
  const config_error_1 = require("../config-error");
6
6
  const placeholders_1 = require("./placeholders");
@@ -19,6 +19,7 @@ exports.DEFAULT_IGNORE = [
19
19
  "**/*.{zip,tgz,tar.gz,jar,whl}",
20
20
  ];
21
21
  const LIST_OVERRIDE_FORMS = "{ extend: [...] } to add to the defaults or { replace: [...] } to swap them out";
22
+ /** A list option that has defaults, so it takes `{ extend: [...] }` or `{ replace: [...] }`, never a bare array. */
22
23
  const listOverrideSchema = (item) => zod_1.z
23
24
  .object({
24
25
  extend: zod_1.z.array(item).optional(),
@@ -34,6 +35,7 @@ const listOverrideSchema = (item) => zod_1.z
34
35
  .refine(value => (value.extend === undefined) !== (value.replace === undefined), {
35
36
  message: `expected exactly one of extend or replace: ${LIST_OVERRIDE_FORMS}`,
36
37
  });
38
+ exports.listOverrideSchema = listOverrideSchema;
37
39
  /**
38
40
  * A named convention, or a custom regex whose single capture group is the placeholder name. A regex
39
41
  * that matches plain words, such as `(\w+)`, turns every segment into a wildcard and so disables
@@ -65,8 +67,8 @@ exports.DEFAULT_DIRECTORIES = false;
65
67
  exports.DEFAULT_BARE_FILENAMES = false;
66
68
  /** `'a', 'b'` for the keys of an `unrecognized_keys` issue. */
67
69
  const quoteKeys = (keys) => keys.map(key => `'${key}'`).join(", ");
68
- /** `a, b, or c`. */
69
- const orList = (items) => items.length > 1 ? `${items.slice(0, -1).join(", ")}, or ${items.at(-1)}` : items.join("");
70
+ /** `a, b, or c`, or `a or b`. */
71
+ const orList = (items) => items.length > 2 ? `${items.slice(0, -1).join(", ")}, or ${items.at(-1)}` : items.join(" or ");
70
72
  /**
71
73
  * A strict object whose unknown keys are reported as `unknown <noun> 'key'; expected <valid keys>`,
72
74
  * and whose wrong type as `expected <expected>`.
@@ -83,7 +85,7 @@ const strictObjectNamingKeys = (shape, { noun, expected }) => zod_1.z
83
85
  .strict();
84
86
  exports.strictObjectNamingKeys = strictObjectNamingKeys;
85
87
  /** A repo-relative glob: a leading `/` or `./` or a trailing `/` would silently match no document. */
86
- const excludeGlobSchema = zod_1.z.string().superRefine((glob, ctx) => {
88
+ exports.excludeGlobSchema = zod_1.z.string().superRefine((glob, ctx) => {
87
89
  if (glob.startsWith("/") || glob.startsWith("./")) {
88
90
  ctx.addIssue({
89
91
  code: zod_1.z.ZodIssueCode.custom,
@@ -97,20 +99,19 @@ const excludeGlobSchema = zod_1.z.string().superRefine((glob, ctx) => {
97
99
  });
98
100
  }
99
101
  });
102
+ /** A list with no defaults, so a plain array; the `{ extend }` and `{ replace }` forms are rejected as meaningless. */
103
+ const plainListSchema = (item, { key, of }) => zod_1.z.array(item, {
104
+ errorMap: (issue, ctx) => issue.code === "invalid_type"
105
+ ? { message: `expected an array of ${of}; ${key} has no defaults, so it takes no { extend } or { replace }` }
106
+ : { message: ctx.defaultError },
107
+ });
108
+ exports.plainListSchema = plainListSchema;
100
109
  /** The `docReferences` section of `repo-checks.config.json`, as written. */
101
110
  exports.docReferencesConfigSchema = (0, exports.strictObjectNamingKeys)({
102
111
  rootDir: zod_1.z.string().min(1).optional(),
103
- ignore: listOverrideSchema(zod_1.z.string()).optional(),
104
- exclude: zod_1.z
105
- .array(excludeGlobSchema, {
106
- errorMap: (issue, ctx) => issue.code === "invalid_type"
107
- ? {
108
- message: "expected an array of globs; exclude has no defaults, so it takes no { extend } or { replace }",
109
- }
110
- : { message: ctx.defaultError },
111
- })
112
- .optional(),
113
- placeholders: listOverrideSchema(placeholderConventionSchema).optional(),
112
+ ignore: (0, exports.listOverrideSchema)(zod_1.z.string()).optional(),
113
+ exclude: (0, exports.plainListSchema)(exports.excludeGlobSchema, { key: "exclude", of: "globs" }).optional(),
114
+ placeholders: (0, exports.listOverrideSchema)(placeholderConventionSchema).optional(),
114
115
  constructs: (0, exports.strictObjectNamingKeys)({
115
116
  links: zod_1.z.boolean().optional(),
116
117
  images: zod_1.z.boolean().optional(),
@@ -123,12 +124,14 @@ exports.docReferencesConfigSchema = (0, exports.strictObjectNamingKeys)({
123
124
  /** Every issue as `path: message`, `;`-separated, with `(root)` for the top level. */
124
125
  const formatConfigIssues = (error) => error.issues.map(issue => `${issue.path.length > 0 ? issue.path.join(".") : "(root)"}: ${issue.message}`).join("; ");
125
126
  exports.formatConfigIssues = formatConfigIssues;
127
+ /** A list option's resolved value: `replace` when given, otherwise the defaults plus any `extend`. */
126
128
  const applyOverride = (defaults, override) => {
127
129
  if (override?.replace) {
128
130
  return override.replace;
129
131
  }
130
132
  return [...defaults, ...(override?.extend ?? [])];
131
133
  };
134
+ exports.applyOverride = applyOverride;
132
135
  /** The resolved settings when no config is given. */
133
136
  exports.DEFAULT_DOCS_SETTINGS = {
134
137
  rootDir: undefined,
@@ -155,9 +158,9 @@ const parseDocsSettings = (raw) => {
155
158
  }
156
159
  return {
157
160
  rootDir: parsed.data.rootDir,
158
- ignore: applyOverride(exports.DEFAULT_IGNORE, parsed.data.ignore),
161
+ ignore: (0, exports.applyOverride)(exports.DEFAULT_IGNORE, parsed.data.ignore),
159
162
  exclude: parsed.data.exclude ?? [],
160
- placeholders: applyOverride(placeholders_1.DEFAULT_PLACEHOLDERS, parsed.data.placeholders),
163
+ placeholders: (0, exports.applyOverride)(placeholders_1.DEFAULT_PLACEHOLDERS, parsed.data.placeholders),
161
164
  constructs: { ...exports.DEFAULT_CONSTRUCTS, ...parsed.data.constructs },
162
165
  directories: parsed.data.directories ?? exports.DEFAULT_DIRECTORIES,
163
166
  bareFilenames: parsed.data.bareFilenames ?? exports.DEFAULT_BARE_FILENAMES,
@@ -1,8 +1,11 @@
1
1
  import { type MarkdownNode } from "./parse";
2
+ /** The marker of doc-references' ignore-next-line comment. */
3
+ export declare const DOC_REFERENCES_IGNORE_MARKER = "doc-references-ignore-next-line";
2
4
  /**
3
- * The 1-based line whose references an ignore-next-line comment suppresses, the line after the
4
- * comment ends, or `undefined` when `node` isn't one. In `.md` the comment is an HTML comment that
5
- * is the whole `html` node; in `.mdx`, which has no HTML comments (one fails to parse), it is a
6
- * comment-only `{/* ... *\/}` expression. Code blocks are leaves, so a comment inside one is text.
5
+ * The 1-based line whose references an ignore-next-line comment for `marker` (for example
6
+ * {@link DOC_REFERENCES_IGNORE_MARKER}) suppresses, the line after the comment ends, or `undefined`
7
+ * when `node` isn't one. In `.md` the comment is an HTML comment that is the whole `html` node; in
8
+ * `.mdx`, which has no HTML comments (one fails to parse), it is a comment-only `{/* ... *\/}`
9
+ * expression. Code blocks are leaves, so a comment inside one is text. `marker` is matched literally.
7
10
  */
8
- export declare const ignoredNextLine: (node: MarkdownNode) => number | undefined;
11
+ export declare const ignoredNextLine: (node: MarkdownNode, marker: string) => number | undefined;
@@ -1,23 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ignoredNextLine = void 0;
3
+ exports.ignoredNextLine = exports.DOC_REFERENCES_IGNORE_MARKER = void 0;
4
4
  const parse_1 = require("./parse");
5
- /** `<!-- doc-references-ignore-next-line -->`, optionally with `: reason` before the `-->`. */
6
- const HTML_COMMENT_RE = /^<!--\s*doc-references-ignore-next-line(?:\s*:[\s\S]*?)?\s*-->$/u;
7
- /** `/* doc-references-ignore-next-line *\/`, optionally with `: reason`, as an MDX `{expression}`'s value. */
8
- const MDX_COMMENT_RE = /^\/\*\s*doc-references-ignore-next-line(?:\s*:[\s\S]*?)?\s*\*\/$/u;
5
+ /** The marker of doc-references' ignore-next-line comment. */
6
+ exports.DOC_REFERENCES_IGNORE_MARKER = "doc-references-ignore-next-line";
7
+ const markerPatterns = new Map();
8
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\/]/gu, "\\$&");
9
+ const patternsFor = (marker) => {
10
+ const cached = markerPatterns.get(marker);
11
+ if (cached !== undefined)
12
+ return cached;
13
+ const escaped = escapeRegExp(marker);
14
+ const patterns = {
15
+ html: new RegExp(`^<!--\\s*${escaped}(?:\\s*:[\\s\\S]*?)?\\s*-->$`, "u"),
16
+ mdx: new RegExp(`^\\/\\*\\s*${escaped}(?:\\s*:[\\s\\S]*?)?\\s*\\*\\/$`, "u"),
17
+ };
18
+ markerPatterns.set(marker, patterns);
19
+ return patterns;
20
+ };
9
21
  /**
10
- * The 1-based line whose references an ignore-next-line comment suppresses, the line after the
11
- * comment ends, or `undefined` when `node` isn't one. In `.md` the comment is an HTML comment that
12
- * is the whole `html` node; in `.mdx`, which has no HTML comments (one fails to parse), it is a
13
- * comment-only `{/* ... *\/}` expression. Code blocks are leaves, so a comment inside one is text.
22
+ * The 1-based line whose references an ignore-next-line comment for `marker` (for example
23
+ * {@link DOC_REFERENCES_IGNORE_MARKER}) suppresses, the line after the comment ends, or `undefined`
24
+ * when `node` isn't one. In `.md` the comment is an HTML comment that is the whole `html` node; in
25
+ * `.mdx`, which has no HTML comments (one fails to parse), it is a comment-only `{/* ... *\/}`
26
+ * expression. Code blocks are leaves, so a comment inside one is text. `marker` is matched literally.
14
27
  */
15
- const ignoredNextLine = (node) => {
28
+ const ignoredNextLine = (node, marker) => {
16
29
  const end = node.position?.end.line;
17
30
  const value = node.value?.trim();
18
31
  if (end === undefined || value === undefined)
19
32
  return undefined;
20
- const isMarker = node.type === "html" ? HTML_COMMENT_RE.test(value) : (0, parse_1.isCommentExpression)(node) && MDX_COMMENT_RE.test(value);
33
+ const { html, mdx } = patternsFor(marker);
34
+ const isMarker = node.type === "html" ? html.test(value) : (0, parse_1.isCommentExpression)(node) && mdx.test(value);
21
35
  return isMarker ? end + 1 : undefined;
22
36
  };
23
37
  exports.ignoredNextLine = ignoredNextLine;
package/src/lib/format.js CHANGED
@@ -4,10 +4,12 @@ exports.formatFindings = exports.formatFinding = exports.formatError = exports.O
4
4
  const config_1 = require("./config");
5
5
  const fs_errors_1 = require("./doc-references/fs-errors");
6
6
  const parse_1 = require("./doc-references/parse");
7
+ const storybook_index_1 = require("./storybook-links/storybook-index");
7
8
  exports.OUTPUT_FORMATS = ["text", "json"];
8
9
  const isExpectedError = (error) => error instanceof config_1.ConfigError ||
9
10
  error instanceof parse_1.DocumentParseError ||
10
11
  error instanceof fs_errors_1.ReadError ||
12
+ error instanceof storybook_index_1.StorybookIndexError ||
11
13
  (0, fs_errors_1.isSystemError)(error);
12
14
  /** An expected error as its message; anything else is a bug, so its stack is kept for the report. */
13
15
  const formatError = (error) => !isExpectedError(error) && error instanceof Error && error.stack !== undefined
@@ -0,0 +1,38 @@
1
+ import { type Finding } from "../doc-references/finding";
2
+ import { type StorybookLinksConfig } from "./settings";
3
+ /** The marker of storybook-links' ignore-next-line comment; doc-references' marker doesn't suppress its links. */
4
+ export declare const STORYBOOK_LINKS_IGNORE_MARKER = "storybook-links-ignore-next-line";
5
+ export interface CheckStorybookLinksOptions {
6
+ /** The directory whose documents are checked: a repository, a git worktree, or a subdirectory of one. */
7
+ readonly rootDir: string;
8
+ /**
9
+ * `storybook index` output files whose entries, combined, are the valid IDs; at least one. Relative
10
+ * paths resolve against the process's working directory.
11
+ */
12
+ readonly indexFiles: ReadonlyArray<string>;
13
+ /**
14
+ * The `storybookLinks` section of a config, as `loadConfig` returns it or written inline, validated
15
+ * with `parseStorybookLinksSettings`; the defaults when omitted.
16
+ */
17
+ readonly config?: StorybookLinksConfig;
18
+ }
19
+ /**
20
+ * Check every `.md` and `.mdx` document under `rootDir`, except those the config's `exclude` globs
21
+ * match, for Storybook links, relative (`?path=/docs/<id>`, `/?path=/story/<id>`) or absolute on one
22
+ * of the config's `hosts` (`https://design.iris.trackunit.com/?path=/docs/<id>` by default), whose ID
23
+ * is in none of `indexFiles` (`unknownStoryId`), or is there only as the other entry type
24
+ * (`wrongStoryType`, suggesting the link with its `/docs/` or `/story/` swapped when the `path` value
25
+ * is written literally). Absolute links to other hosts, links with a `#fragment`, IDs matching an
26
+ * `ignore` glob, links on the line after a {@link STORYBOOK_LINKS_IGNORE_MARKER} comment, and
27
+ * anything in code blocks, inline code, or MDX expressions, aren't checked.
28
+ *
29
+ * The config is validated, then the indexes loaded, before any document is read, so a bad config or
30
+ * index never yields a clean result. Findings are sorted by file, line, and column, with `file`
31
+ * relative to the repository root (the nearest `.git` at or above `rootDir`).
32
+ *
33
+ * @throws {ConfigError} when the config is invalid, before any index or document is read
34
+ * @throws {ReadError} when an index, a document, or a directory can't be read
35
+ * @throws {StorybookIndexError} when an index is invalid, or `indexFiles` is empty
36
+ * @throws {DocumentParseError} when a document can't be parsed
37
+ */
38
+ export declare const checkStorybookLinks: ({ rootDir, indexFiles, config }: CheckStorybookLinksOptions) => Array<Finding>;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkStorybookLinks = exports.STORYBOOK_LINKS_IGNORE_MARKER = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const picomatch_1 = tslib_1.__importDefault(require("picomatch"));
6
+ const documents_1 = require("../doc-references/documents");
7
+ const extract_1 = require("../doc-references/extract");
8
+ const finding_1 = require("../doc-references/finding");
9
+ const parse_1 = require("../doc-references/parse");
10
+ const retype_storybook_path_1 = require("./retype-storybook-path");
11
+ const settings_1 = require("./settings");
12
+ const storybook_index_1 = require("./storybook-index");
13
+ const storybook_path_1 = require("./storybook-path");
14
+ /** The marker of storybook-links' ignore-next-line comment; doc-references' marker doesn't suppress its links. */
15
+ exports.STORYBOOK_LINKS_IGNORE_MARKER = "storybook-links-ignore-next-line";
16
+ /** Storybook links are written as links, images, or definitions; inline code is prose, not a link. */
17
+ const CONSTRUCTS = { links: true, images: true, definitions: true, inlineCode: false };
18
+ const checkDocument = (document, { entries, hosts, isIgnoredId }) => {
19
+ const { file } = document;
20
+ const tree = (0, parse_1.parseMarkdown)((0, documents_1.readDocument)(document), file);
21
+ return (0, extract_1.extractReferences)(tree, { constructs: CONSTRUCTS, ignoreMarker: exports.STORYBOOK_LINKS_IGNORE_MARKER }).flatMap(({ kind, target, line, column }) => {
22
+ const storybookPath = (0, storybook_path_1.parseStorybookPath)(target, hosts);
23
+ if (storybookPath === undefined || isIgnoredId(storybookPath.id))
24
+ return [];
25
+ const entryTypes = entries.get(storybookPath.id);
26
+ if (entryTypes === undefined)
27
+ return [{ file, line, column, target, kind, reason: "unknownStoryId" }];
28
+ if (entryTypes.has(storybookPath.type))
29
+ return [];
30
+ const suggestion = (0, retype_storybook_path_1.retypeStorybookPath)(target, storybookPath.type === "docs" ? "story" : "docs");
31
+ return [
32
+ {
33
+ file,
34
+ line,
35
+ column,
36
+ target,
37
+ kind,
38
+ reason: "wrongStoryType",
39
+ ...(suggestion === undefined ? {} : { suggestion }),
40
+ },
41
+ ];
42
+ });
43
+ };
44
+ /**
45
+ * Check every `.md` and `.mdx` document under `rootDir`, except those the config's `exclude` globs
46
+ * match, for Storybook links, relative (`?path=/docs/<id>`, `/?path=/story/<id>`) or absolute on one
47
+ * of the config's `hosts` (`https://design.iris.trackunit.com/?path=/docs/<id>` by default), whose ID
48
+ * is in none of `indexFiles` (`unknownStoryId`), or is there only as the other entry type
49
+ * (`wrongStoryType`, suggesting the link with its `/docs/` or `/story/` swapped when the `path` value
50
+ * is written literally). Absolute links to other hosts, links with a `#fragment`, IDs matching an
51
+ * `ignore` glob, links on the line after a {@link STORYBOOK_LINKS_IGNORE_MARKER} comment, and
52
+ * anything in code blocks, inline code, or MDX expressions, aren't checked.
53
+ *
54
+ * The config is validated, then the indexes loaded, before any document is read, so a bad config or
55
+ * index never yields a clean result. Findings are sorted by file, line, and column, with `file`
56
+ * relative to the repository root (the nearest `.git` at or above `rootDir`).
57
+ *
58
+ * @throws {ConfigError} when the config is invalid, before any index or document is read
59
+ * @throws {ReadError} when an index, a document, or a directory can't be read
60
+ * @throws {StorybookIndexError} when an index is invalid, or `indexFiles` is empty
61
+ * @throws {DocumentParseError} when a document can't be parsed
62
+ */
63
+ const checkStorybookLinks = ({ rootDir, indexFiles, config }) => {
64
+ const settings = (0, settings_1.parseStorybookLinksSettings)(config);
65
+ const entries = (0, storybook_index_1.loadStorybookIndexes)(indexFiles);
66
+ const ignoreMatchers = settings.ignore.map(glob => (0, picomatch_1.default)(glob));
67
+ const check = {
68
+ entries,
69
+ hosts: settings.hosts,
70
+ isIgnoredId: id => ignoreMatchers.some(matches => matches(id)),
71
+ };
72
+ return (0, documents_1.discoverDocumentsToCheck)({ rootDir, exclude: settings.exclude })
73
+ .documents.flatMap(document => checkDocument(document, check))
74
+ .sort(finding_1.compareFindings);
75
+ };
76
+ exports.checkStorybookLinks = checkStorybookLinks;
77
+ //# sourceMappingURL=check-storybook-links.js.map
@@ -0,0 +1,8 @@
1
+ import type { StorybookEntryType } from "./storybook-index";
2
+ /**
3
+ * `target` with its `?path=/<other type>/` rewritten to `?path=/<type>/`, keeping everything else
4
+ * as written (host, prefix, other query params). `undefined` when the `path` param `URLSearchParams`
5
+ * reads isn't written literally as `path=/<other type>/...` (e.g. percent-encoded), so the rewrite
6
+ * would be a guess.
7
+ */
8
+ export declare const retypeStorybookPath: (target: string, type: StorybookEntryType) => string | undefined;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.retypeStorybookPath = void 0;
4
+ /**
5
+ * `target` with its `?path=/<other type>/` rewritten to `?path=/<type>/`, keeping everything else
6
+ * as written (host, prefix, other query params). `undefined` when the `path` param `URLSearchParams`
7
+ * reads isn't written literally as `path=/<other type>/...` (e.g. percent-encoded), so the rewrite
8
+ * would be a guess.
9
+ */
10
+ const retypeStorybookPath = (target, type) => {
11
+ const queryStart = target.indexOf("?");
12
+ if (queryStart === -1)
13
+ return undefined;
14
+ const params = target.slice(queryStart + 1).split("&");
15
+ const pathIndex = params.findIndex(param => new URLSearchParams(param).has("path"));
16
+ const from = `path=/${type === "docs" ? "story" : "docs"}/`;
17
+ const pathParam = params[pathIndex];
18
+ if (pathParam === undefined || !pathParam.startsWith(from))
19
+ return undefined;
20
+ const retyped = params.with(pathIndex, `path=/${type}/${pathParam.slice(from.length)}`);
21
+ return `${target.slice(0, queryStart)}?${retyped.join("&")}`;
22
+ };
23
+ exports.retypeStorybookPath = retypeStorybookPath;
24
+ //# sourceMappingURL=retype-storybook-path.js.map
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+ /** The `storybookLinks` section of `repo-checks.config.json`, as written. */
3
+ export declare const storybookLinksConfigSchema: z.ZodObject<{
4
+ exclude: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
5
+ ignore: z.ZodOptional<z.ZodArray<z.ZodType<string, z.ZodTypeDef, string>, "many">>;
6
+ hosts: z.ZodOptional<z.ZodType<import("../doc-references/settings").ListOverride, z.ZodTypeDef, import("../doc-references/settings").ListOverride>>;
7
+ }, "strict", z.ZodTypeAny, {
8
+ ignore?: string[] | undefined;
9
+ exclude?: string[] | undefined;
10
+ hosts?: import("../doc-references/settings").ListOverride | undefined;
11
+ }, {
12
+ ignore?: string[] | undefined;
13
+ exclude?: string[] | undefined;
14
+ hosts?: import("../doc-references/settings").ListOverride | undefined;
15
+ }>;
16
+ export type StorybookLinksConfig = z.input<typeof storybookLinksConfigSchema>;
17
+ export interface StorybookLinksSettings {
18
+ /**
19
+ * Picomatch globs, matched against the repo-relative path, of documents never read or checked,
20
+ * as doc-references' `exclude`.
21
+ */
22
+ readonly exclude: ReadonlyArray<string>;
23
+ /** Picomatch globs, matched against the Storybook ID (`foo--wip`), of links never reported. */
24
+ readonly ignore: ReadonlyArray<string>;
25
+ /** Lower-cased hostnames whose absolute `?path=` links are checked; relative links always are. */
26
+ readonly hosts: ReadonlyArray<string>;
27
+ }
28
+ /** The resolved settings when no config is given. */
29
+ export declare const DEFAULT_STORYBOOK_LINKS_SETTINGS: StorybookLinksSettings;
30
+ /**
31
+ * Validate a raw storybook-links config and resolve it onto the defaults. `undefined` yields
32
+ * {@link DEFAULT_STORYBOOK_LINKS_SETTINGS}.
33
+ *
34
+ * @throws {ConfigError} naming every offending key, when the config is invalid
35
+ */
36
+ export declare const parseStorybookLinksSettings: (raw: unknown) => StorybookLinksSettings;
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseStorybookLinksSettings = exports.DEFAULT_STORYBOOK_LINKS_SETTINGS = exports.storybookLinksConfigSchema = void 0;
4
+ const zod_1 = require("zod");
5
+ const config_error_1 = require("../config-error");
6
+ const settings_1 = require("../doc-references/settings");
7
+ const storybook_path_1 = require("./storybook-path");
8
+ /**
9
+ * Configuration for the storybook-links check, validated with zod like doc-references' so a bad
10
+ * config fails with a message naming the offending key. `hosts` has defaults, so it takes
11
+ * `{ extend: [...] }` or `{ replace: [...] }`; `exclude` and `ignore` have none, so they are plain
12
+ * arrays.
13
+ */
14
+ /** Storybook IDs (`button--primary`) contain no `/`, so a glob with one would silently match nothing. */
15
+ const storybookIdGlobSchema = zod_1.z.string().superRefine((glob, ctx) => {
16
+ if (glob === "") {
17
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, message: "an empty glob matches no Storybook ID" });
18
+ }
19
+ else if (glob.includes("/")) {
20
+ ctx.addIssue({
21
+ code: zod_1.z.ZodIssueCode.custom,
22
+ message: `"${glob}" contains /, which matches no Storybook ID; match the ID alone, e.g. foo--wip`,
23
+ });
24
+ }
25
+ else if (glob.startsWith("!")) {
26
+ ctx.addIssue({
27
+ code: zod_1.z.ZodIssueCode.custom,
28
+ message: `"${glob}" is a negation, which would ignore every other ID; list the IDs to ignore instead`,
29
+ });
30
+ }
31
+ });
32
+ const NOT_HOSTNAME_RE = /[\s/:@?#\\]/u;
33
+ /** The hostname a URL on `host` has, or `undefined` when `host` isn't a bare hostname at all. */
34
+ const urlHostname = (host) => {
35
+ if (host === "" || NOT_HOSTNAME_RE.test(host))
36
+ return undefined;
37
+ try {
38
+ return new URL(`http://${host}`).hostname;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ };
44
+ /**
45
+ * A host is compared with a link's `URL.hostname`, so it must be written as the URL parser writes
46
+ * it; anything else (a scheme, port, path, credentials, a Unicode or shorthand form) matches nothing.
47
+ */
48
+ const hostnameSchema = zod_1.z.string().superRefine((host, ctx) => {
49
+ const hostname = urlHostname(host);
50
+ if (hostname === undefined) {
51
+ ctx.addIssue({
52
+ code: zod_1.z.ZodIssueCode.custom,
53
+ message: `"${host}" must be a bare hostname, e.g. design.iris.trackunit.com, without a scheme, port, path, or credentials`,
54
+ });
55
+ }
56
+ else if (hostname !== host.toLowerCase()) {
57
+ ctx.addIssue({
58
+ code: zod_1.z.ZodIssueCode.custom,
59
+ message: `"${host}" is written ${hostname} in a URL; use that form`,
60
+ });
61
+ }
62
+ });
63
+ /** The `storybookLinks` section of `repo-checks.config.json`, as written. */
64
+ exports.storybookLinksConfigSchema = (0, settings_1.strictObjectNamingKeys)({
65
+ exclude: (0, settings_1.plainListSchema)(settings_1.excludeGlobSchema, { key: "exclude", of: "globs" }).optional(),
66
+ ignore: (0, settings_1.plainListSchema)(storybookIdGlobSchema, { key: "ignore", of: "Storybook ID globs" }).optional(),
67
+ hosts: (0, settings_1.listOverrideSchema)(hostnameSchema).optional(),
68
+ }, { noun: "setting", expected: "an object of storybook-links settings" });
69
+ /** The resolved settings when no config is given. */
70
+ exports.DEFAULT_STORYBOOK_LINKS_SETTINGS = {
71
+ exclude: [],
72
+ ignore: [],
73
+ hosts: storybook_path_1.DEFAULT_STORYBOOK_HOSTS,
74
+ };
75
+ /**
76
+ * Validate a raw storybook-links config and resolve it onto the defaults. `undefined` yields
77
+ * {@link DEFAULT_STORYBOOK_LINKS_SETTINGS}.
78
+ *
79
+ * @throws {ConfigError} naming every offending key, when the config is invalid
80
+ */
81
+ const parseStorybookLinksSettings = (raw) => {
82
+ if (raw === undefined) {
83
+ return exports.DEFAULT_STORYBOOK_LINKS_SETTINGS;
84
+ }
85
+ const parsed = exports.storybookLinksConfigSchema.safeParse(raw);
86
+ if (!parsed.success) {
87
+ throw new config_error_1.ConfigError(`Invalid storybook-links config: ${(0, settings_1.formatConfigIssues)(parsed.error)}`);
88
+ }
89
+ return {
90
+ exclude: parsed.data.exclude ?? [],
91
+ ignore: parsed.data.ignore ?? [],
92
+ hosts: (0, settings_1.applyOverride)(storybook_path_1.DEFAULT_STORYBOOK_HOSTS, parsed.data.hosts).map(host => host.toLowerCase()),
93
+ };
94
+ };
95
+ exports.parseStorybookLinksSettings = parseStorybookLinksSettings;
96
+ //# sourceMappingURL=settings.js.map
@@ -0,0 +1,20 @@
1
+ export declare const STORYBOOK_ENTRY_TYPES: readonly ["docs", "story"];
2
+ /** The kind of a Storybook index entry, and of the `?path=/<type>/<id>` that links to it. */
3
+ export type StorybookEntryType = (typeof STORYBOOK_ENTRY_TYPES)[number];
4
+ /**
5
+ * A Storybook index that isn't valid JSON or isn't shaped like a `storybook index` output, or no
6
+ * index at all: the check can't tell a valid link from a broken one, so it must not run.
7
+ */
8
+ export declare class StorybookIndexError extends Error {
9
+ /** @param message What is wrong, naming the index file. */
10
+ constructor(message: string);
11
+ }
12
+ /**
13
+ * Read `storybook index` output files and combine their entries into one map of entry ID to the
14
+ * types it has in any of them. Several files are combined because no single Storybook (public or
15
+ * internal) covers every ID, and an ID may be a docs entry in one and a story in another.
16
+ *
17
+ * @throws {ReadError} when a file can't be read
18
+ * @throws {StorybookIndexError} when a file isn't valid JSON or not an index, or `files` is empty
19
+ */
20
+ export declare const loadStorybookIndexes: (files: ReadonlyArray<string>) => ReadonlyMap<string, ReadonlySet<StorybookEntryType>>;