@dogsbay/types 0.2.0-beta.13 → 0.2.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ /**
2
+ * The frontmatter checker: one page's frontmatter against the vocabulary in
3
+ * frontmatter-schema.ts and the site's policy. Pure, so every surface reports
4
+ * the same findings:
5
+ *
6
+ * - `dogsbay validate` (@dogsbay/commands), which adds a one-click fix;
7
+ * - the `frontmatter/valid` rule of `@dogsbay/site-check`, run by
8
+ * `dogsbay site check` and `dogsbay-ssg check`.
9
+ */
10
+ import { AGGREGATOR_OWNED, WELL_KNOWN_FIELDS, contentRelativePath, isSafeAutoFix, matchesType, nearMisses, requiredFieldsFor, typeOf, } from "./frontmatter-schema.js";
11
+ /**
12
+ * Findings for one page. `path` is the page's source path as the policy's
13
+ * `roots` see it (the globs match its content-relative form); `keyLines`
14
+ * gives each key's line (`frontmatterKeyLines(source)`).
15
+ */
16
+ export function checkFrontmatter(frontmatter, path, policy, keyLines = new Map()) {
17
+ const out = [];
18
+ const fm = frontmatter ?? {};
19
+ const at = (key) => (keyLines.has(key) ? { key, line: keyLines.get(key) } : { key });
20
+ for (const [key, value] of Object.entries(fm)) {
21
+ const taxonomy = policy.taxonomies[key];
22
+ const spec = WELL_KNOWN_FIELDS[key];
23
+ if (AGGREGATOR_OWNED.includes(key))
24
+ continue; // reported below, once, whatever its type
25
+ if (!spec && !taxonomy) {
26
+ // an unknown-key policy applies to CONTENT only: a README or a plan in the same
27
+ // workspace is not a page, and reporting its keys is noise
28
+ if (policy.unknown !== "ignore" && contentRelativePath(policy, path) !== null) {
29
+ out.push({
30
+ severity: policy.unknown === "error" ? "error" : "warning",
31
+ code: "frontmatter-unknown",
32
+ message: `unknown frontmatter key "${key}" (not a well-known field or a declared taxonomy)`,
33
+ ...at(key),
34
+ });
35
+ }
36
+ continue;
37
+ }
38
+ if (value === null || value === undefined)
39
+ continue; // an empty key is a stub, not a wrong type
40
+ // A DECLARED taxonomy wins over the built-in field spec: taxonomy terms are strings (the
41
+ // collector drops anything else), so `product: 3` must be reported even though the chunker's
42
+ // own `product` facet would have taken a number.
43
+ const effective = taxonomy ? { type: "string|string[]" } : spec;
44
+ if (effective && !matchesType(value, effective.type)) {
45
+ out.push({ severity: "error", code: "frontmatter-type", message: `"${key}" should be ${effective.type}, got ${typeOf(value)}`, ...at(key) });
46
+ continue;
47
+ }
48
+ if (spec && !matchesType(value, spec.type)) {
49
+ out.push({ severity: "error", code: "frontmatter-type", message: `"${key}" should be ${spec.type}, got ${typeOf(value)}`, ...at(key) });
50
+ continue; // an enum check on the wrong type says nothing useful
51
+ }
52
+ // `tags: api, guides` is ONE tag called "api, guides" — the coercion wraps the scalar, it
53
+ // does not split it, so the writer silently gets a tag nobody will ever match
54
+ // ONLY where the coercion wraps rather than splits: the taxonomy/meta fields. The chunker's
55
+ // facet axes split a string themselves, so a comma there is fine.
56
+ const wrapsScalar = taxonomy !== undefined || key === "tags" || key === "audience" || key === "category";
57
+ if (typeof value === "string" && /,\s*\S/.test(value) && wrapsScalar) {
58
+ out.push({
59
+ severity: "warning",
60
+ code: "frontmatter-comma-scalar",
61
+ message: `"${key}: ${value}" is ONE value containing a comma, not a list — write it as a YAML list (\`[a, b]\`) if you meant several`,
62
+ ...at(key),
63
+ });
64
+ }
65
+ // a value the pipeline discards: an empty string or an empty list is not "no value", it is a
66
+ // value that silently disappears (parseMeta drops both)
67
+ if ((typeof value === "string" && value.trim() === "") || (Array.isArray(value) && value.length === 0)) {
68
+ out.push({
69
+ severity: "warning",
70
+ code: "frontmatter-empty",
71
+ message: `"${key}" is empty, so it is dropped — remove the key or give it a value`,
72
+ ...at(key),
73
+ });
74
+ continue;
75
+ }
76
+ // a closed set: the well-known `status`, or a taxonomy that declared `values`
77
+ const allowed = spec?.values ?? taxonomy?.values;
78
+ const terms = typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
79
+ if (allowed) {
80
+ for (const term of terms) {
81
+ const head = taxonomy?.hierarchical ? term.split("/")[0] : term;
82
+ if (allowed.includes(term) || (taxonomy?.hierarchical && allowed.includes(head)))
83
+ continue;
84
+ // a hierarchical taxonomy declares its HEAD terms, so `apu/rest` is a near miss of `api`
85
+ const probe = taxonomy?.hierarchical ? head : term;
86
+ const near = nearMisses(probe, allowed);
87
+ // a hierarchical fix keeps the sub-term: `apu/rest` → `api/rest`, never `api`
88
+ const replacement = near.length === 1
89
+ ? (taxonomy?.hierarchical && term !== head ? `${near[0]}${term.slice(head.length)}` : near[0])
90
+ : undefined;
91
+ out.push({
92
+ severity: "error",
93
+ code: "frontmatter-enum",
94
+ message: taxonomy?.hierarchical && term !== head
95
+ ? `"${key}: ${term}" starts with "${head}", which is not one of ${allowed.join(", ")}`
96
+ : `"${key}: ${term}" is not one of ${allowed.join(", ")}`,
97
+ ...at(key),
98
+ ...(near.length ? { candidates: near } : {}),
99
+ // ONLY a case slip is applied with one click: at edit distance 2 the single
100
+ // candidate for `unstable` is `stable`, and inverting a writer's meaning on a
101
+ // click is worse than making them choose
102
+ ...(replacement && typeof value === "string" && isSafeAutoFix(probe, near[0])
103
+ ? { fix: { key, value: replacement, label: `Use "${replacement}"` } }
104
+ : {}),
105
+ });
106
+ }
107
+ }
108
+ if (taxonomy && !taxonomy.hierarchical) {
109
+ for (const term of terms) {
110
+ if (!term.includes("/"))
111
+ continue;
112
+ out.push({
113
+ severity: "warning",
114
+ code: "frontmatter-nesting",
115
+ message: `"${key}: ${term}" uses slash nesting, but the ${key} taxonomy is not hierarchical — it will be one flat term`,
116
+ ...at(key),
117
+ });
118
+ }
119
+ }
120
+ }
121
+ // the free-form `props:` bag, against the config's `propSchema`
122
+ const props = fm.props;
123
+ if (props && typeof props === "object" && !Array.isArray(props)) {
124
+ for (const [key, value] of Object.entries(props)) {
125
+ const spec = policy.propSchema[key];
126
+ if (!spec || value === null || value === undefined)
127
+ continue;
128
+ if (typeof value !== spec.type) {
129
+ out.push({ severity: "error", code: "frontmatter-prop-type", message: `"props.${key}" should be ${spec.type}, got ${typeOf(value)}`, ...at("props") });
130
+ continue;
131
+ }
132
+ if (spec.enum && !spec.enum.includes(String(value))) {
133
+ const near = nearMisses(String(value), spec.enum);
134
+ out.push({
135
+ severity: "error",
136
+ code: "frontmatter-prop-enum",
137
+ message: `"props.${key}: ${String(value)}" is not one of ${spec.enum.join(", ")}`,
138
+ ...at("props"),
139
+ ...(near.length ? { candidates: near } : {}),
140
+ });
141
+ }
142
+ }
143
+ }
144
+ // keys the multi-source build writes: a writer setting one by hand routes the page wrong
145
+ for (const key of AGGREGATOR_OWNED) {
146
+ if (fm[key] === undefined)
147
+ continue;
148
+ out.push({
149
+ severity: "warning",
150
+ code: "frontmatter-aggregator-owned",
151
+ message: `"${key}" is written by the multi-source build, not by hand — the build overwrites it, so setting it here has no effect`,
152
+ ...at(key),
153
+ });
154
+ }
155
+ for (const field of requiredFieldsFor(policy, path)) {
156
+ const value = fm[field];
157
+ if (value === undefined || value === null || value === "") {
158
+ out.push({
159
+ severity: "error",
160
+ code: "frontmatter-required",
161
+ message: `"${field}" is required here but is ${value === undefined ? "missing" : "empty"}`,
162
+ ...at(field),
163
+ });
164
+ }
165
+ }
166
+ return out;
167
+ }
168
+ /**
169
+ * The policy from a parsed `dogsbay.config.*` object: declared `taxonomies:`
170
+ * (their `values`/`hierarchical` ARE the check), `propSchema:`, and the
171
+ * opt-in `content.frontmatter` strictness. `roots` are the content roots
172
+ * (`content.sources[].path`). A malformed `content.frontmatter.unknown` sets
173
+ * `invalid` rather than being guessed around.
174
+ */
175
+ export function frontmatterPolicyFromConfig(cfg, roots) {
176
+ const out = { taxonomies: {}, propSchema: {}, required: [], unknown: "ignore", roots };
177
+ if (!cfg || typeof cfg !== "object")
178
+ return out;
179
+ const taxonomies = (cfg.taxonomies ?? {});
180
+ for (const [field, raw] of Object.entries(taxonomies)) {
181
+ if (!raw || typeof raw !== "object")
182
+ continue;
183
+ const rec = raw;
184
+ out.taxonomies[field] = {
185
+ values: Array.isArray(rec.values) ? rec.values.filter((v) => typeof v === "string") : undefined,
186
+ hierarchical: rec.hierarchical === true,
187
+ };
188
+ }
189
+ // `propSchema` shorthand is a bare type name; the long form adds an enum
190
+ const propSchema = (cfg.propSchema ?? {});
191
+ for (const [key, raw] of Object.entries(propSchema)) {
192
+ if (typeof raw === "string" && ["string", "number", "boolean"].includes(raw)) {
193
+ out.propSchema[key] = { type: raw };
194
+ }
195
+ else if (raw && typeof raw === "object") {
196
+ const rec = raw;
197
+ if (typeof rec.type === "string" && ["string", "number", "boolean"].includes(rec.type)) {
198
+ out.propSchema[key] = {
199
+ type: rec.type,
200
+ enum: Array.isArray(rec.enum) ? rec.enum.map((v) => String(v)) : undefined,
201
+ };
202
+ }
203
+ }
204
+ }
205
+ const content = (cfg.content ?? {});
206
+ const fm = (content.frontmatter ?? {});
207
+ if (fm.unknown === "warn" || fm.unknown === "error")
208
+ out.unknown = fm.unknown;
209
+ else if (fm.unknown !== undefined && fm.unknown !== "ignore") {
210
+ // the CLI throws on this; the IDE reads the config directly, so say so rather than
211
+ // silently applying no policy at all
212
+ out.invalid = `content.frontmatter.unknown must be "ignore" | "warn" | "error"; got ${JSON.stringify(fm.unknown)}`;
213
+ }
214
+ const required = fm.required;
215
+ if (required && typeof required === "object") {
216
+ for (const [glob, fields] of Object.entries(required)) {
217
+ const list = Array.isArray(fields) ? fields.filter((f) => typeof f === "string") : typeof fields === "string" ? [fields] : [];
218
+ if (list.length)
219
+ out.required.push({ glob, fields: list });
220
+ }
221
+ }
222
+ return out;
223
+ }
@@ -0,0 +1,96 @@
1
+ /** The YAML shapes a field may take. `date` accepts a Date (js-yaml parses ISO dates) or an ISO-ish string. */
2
+ export type FieldType = "string" | "number" | "boolean" | "date" | "string[]" | "string|string[]" | "object" | "boolean|object" | "scalar|scalar[]";
3
+ export interface FieldSpec {
4
+ type: FieldType;
5
+ /** Closed set of values (checked case-sensitively; a case-only miss is reported with the fix). */
6
+ values?: string[];
7
+ }
8
+ /**
9
+ * The well-known fields. Anything not listed is free-form as far as the
10
+ * engine is concerned (see `unknown` above).
11
+ */
12
+ export declare const WELL_KNOWN_FIELDS: Record<string, FieldSpec>;
13
+ /**
14
+ * Fields the pipeline ACCEPTS but does not act on: they are here so imported
15
+ * content does not light up as "unknown", not because setting them does
16
+ * anything. Kept in one list so the docs can say so honestly.
17
+ */
18
+ export declare const INERT_FIELDS: Set<string>;
19
+ /**
20
+ * Keys the AGGREGATOR owns: the multi-source build writes them, and a writer
21
+ * setting one by hand is a mistake that shows up as a page routed to the
22
+ * wrong namespace/version (documented in the frontmatter-fields skill).
23
+ */
24
+ export declare const AGGREGATOR_OWNED: string[];
25
+ /** One `propSchema` entry from dogsbay.config: a type, optionally a closed set. */
26
+ export interface PropSpec {
27
+ type: "string" | "number" | "boolean";
28
+ enum?: string[];
29
+ }
30
+ export interface TaxonomySpec {
31
+ values?: string[];
32
+ hierarchical?: boolean;
33
+ }
34
+ export interface FrontmatterPolicy {
35
+ /** Declared taxonomies (config `taxonomies:`), keyed by frontmatter field name. */
36
+ taxonomies: Record<string, TaxonomySpec>;
37
+ /**
38
+ * Config `propSchema:` — the free-form `props:` bag's declared shape. It has
39
+ * been in the config schema (and validated as CONFIG) since taxonomies
40
+ * landed, with nothing ever checking a PAGE against it.
41
+ */
42
+ propSchema: Record<string, PropSpec>;
43
+ /** `content.frontmatter.required`: path glob → fields that must be present. */
44
+ required: Array<{
45
+ glob: string;
46
+ fields: string[];
47
+ }>;
48
+ /** `content.frontmatter.unknown`: what to do with keys nobody declared. */
49
+ unknown: "ignore" | "warn" | "error";
50
+ /**
51
+ * The content roots (config `content.sources[].path`). The declared policy
52
+ * applies to CONTENT: a README, a plan or a dev note in the same workspace
53
+ * is not a page, and reporting its frontmatter is noise. Globs are matched
54
+ * against the content-root-relative path, which is what a writer means by
55
+ * `guides/**`.
56
+ */
57
+ roots: string[];
58
+ /** Set when the config's policy is itself malformed — reported, never guessed around. */
59
+ invalid?: string;
60
+ }
61
+ export declare const EMPTY_POLICY: FrontmatterPolicy;
62
+ /** The type name to SHOW for a value the writer got wrong. */
63
+ export declare const typeOf: (v: unknown) => string;
64
+ export declare function matchesType(value: unknown, type: FieldType): boolean;
65
+ /**
66
+ * The near-miss values for a bad enum entry: a case-only difference first
67
+ * (the overwhelmingly common typo), then a one-edit neighbour. A fix is
68
+ * offered only when exactly one candidate comes back.
69
+ */
70
+ export declare function nearMisses(value: string, allowed: string[]): string[];
71
+ /**
72
+ * Whether a near miss may be APPLIED with one click, as opposed to merely
73
+ * listed. Only a case difference qualifies: at edit distance 2 the single
74
+ * candidate for `unstable` is `stable`, and for `review` it is `preview` —
75
+ * a one-click fix that inverts the writer's meaning is worse than no fix.
76
+ */
77
+ export declare const isSafeAutoFix: (value: string, candidate: string) => boolean;
78
+ /**
79
+ * The 1-based line of a top-level key inside the frontmatter block, so a
80
+ * finding can be revealed where the writer wrote it. Only the block is
81
+ * scanned (the body may contain a line that looks like a key).
82
+ */
83
+ export declare function frontmatterKeyLines(source: string): Map<string, number>;
84
+ /**
85
+ * `content/guides/**` / `*.md` / `content/*​/index.md`. Deliberately small:
86
+ * `**` crosses directories, `*` does not, everything else is literal.
87
+ */
88
+ export declare function globMatches(glob: string, path: string): boolean;
89
+ /**
90
+ * The path a glob is matched against: relative to the content root the doc
91
+ * lives under, so `guides/**` means what the writer means when their content
92
+ * is `content/guides/…`. A doc outside every declared root is not content.
93
+ */
94
+ export declare function contentRelativePath(policy: FrontmatterPolicy, path: string): string | null;
95
+ /** Fields required for a path by the declared globs (deduped, in declaration order). */
96
+ export declare function requiredFieldsFor(policy: FrontmatterPolicy, path: string): string[];
@@ -0,0 +1,243 @@
1
+ /**
2
+ * What page frontmatter MEANS — the vocabulary `validate` and `site check`
3
+ * (through `checkFrontmatter`, frontmatter-check.ts) check against
4
+ * (plans/frontmatter-validation.md).
5
+ *
6
+ * Three sources, in order of how much the writer had to declare:
7
+ *
8
+ * 1. WELL-KNOWN FIELDS. `docs/metadata.md` is the field reference and the
9
+ * emitters read exactly these; the table below mirrors it. A bare
10
+ * directory with no config gets type checking for free.
11
+ * 2. `taxonomies:` in `dogsbay.config.*` — already carries `values` (the
12
+ * allowed terms) and `hierarchical` (whether `api/rest` is legal). No
13
+ * new config surface: if you declared the taxonomy, you declared the
14
+ * check.
15
+ * 3. `content.frontmatter` — opt-in strictness: `required` (globs → fields
16
+ * that must be present) and `unknown` (ignore | warn | error).
17
+ *
18
+ * Unknown keys are silent unless (3) asks for them: free-form keys are
19
+ * legitimate, and a checker that cries wolf on them gets switched off.
20
+ *
21
+ * The nine fields `parseMeta` owns are checked against the rules IT applies
22
+ * (it silently drops what it cannot use), and `tests/meta-parity.test.ts`
23
+ * asserts the two agree value-by-value — the anti-drift device, since a
24
+ * checker that disagrees with the parser is worse than no checker.
25
+ */
26
+ import { STATUS_VALUES } from "./meta.js";
27
+ /**
28
+ * The well-known fields. Anything not listed is free-form as far as the
29
+ * engine is concerned (see `unknown` above).
30
+ */
31
+ export const WELL_KNOWN_FIELDS = {
32
+ title: { type: "string" },
33
+ description: { type: "string" },
34
+ // parseMeta coerces a single string ("tags: api"), so a scalar is correct authoring
35
+ tags: { type: "string|string[]" },
36
+ category: { type: "string|string[]" },
37
+ type: { type: "string" },
38
+ status: { type: "string", values: [...STATUS_VALUES] },
39
+ audience: { type: "string|string[]" },
40
+ weight: { type: "number" },
41
+ updated: { type: "date" },
42
+ created: { type: "date" },
43
+ lastUpdated: { type: "date" },
44
+ lastmod: { type: "date" },
45
+ date: { type: "date" },
46
+ props: { type: "object" },
47
+ keyword: { type: "string" },
48
+ targetKeyword: { type: "string" },
49
+ // visibility / build behaviour the emitters read
50
+ draft: { type: "boolean" },
51
+ noindex: { type: "boolean" },
52
+ nofollow: { type: "boolean" },
53
+ excludeFromSearch: { type: "boolean" },
54
+ pagefindExclude: { type: "boolean" },
55
+ ogImage: { type: "string" },
56
+ ogType: { type: "string" },
57
+ canonicalUrl: { type: "string" },
58
+ slug: { type: "string" },
59
+ // every reader casts/checks `redirect` as a STRING: a list would validate and then be ignored
60
+ redirect: { type: "string" },
61
+ // Old paths that should forward TO this page. A list, unlike `redirect`,
62
+ // because a page accumulates former URLs and they are deleted with it.
63
+ aliases: { type: "string[]" },
64
+ llmActions: { type: "boolean|object" },
65
+ preprocess: { type: "boolean" },
66
+ autoH1: { type: "boolean" },
67
+ autoLede: { type: "boolean" },
68
+ fragment: { type: "boolean" },
69
+ _fragment: { type: "boolean" },
70
+ "single-page": { type: "string", values: ["yes", "children", "no"] },
71
+ // chunk facet keys (@dogsbay/chunk facets.ts TAXONOMY_KEYS) — consumed even without a
72
+ // `taxonomies:` declaration, so reporting them as unknown would be a false positive
73
+ product: { type: "scalar|scalar[]" },
74
+ platform: { type: "scalar|scalar[]" },
75
+ edition: { type: "scalar|scalar[]" },
76
+ // DITA profiling attributes carried through the pipeline
77
+ rev: { type: "scalar|scalar[]" },
78
+ otherprops: { type: "scalar|scalar[]" },
79
+ // stamped by the single-page (book) emitter on the pages it generates
80
+ granularity: { type: "string" },
81
+ };
82
+ /**
83
+ * Fields the pipeline ACCEPTS but does not act on: they are here so imported
84
+ * content does not light up as "unknown", not because setting them does
85
+ * anything. Kept in one list so the docs can say so honestly.
86
+ */
87
+ export const INERT_FIELDS = new Set(["ogType", "autoH1", "autoLede", "date", "fragment", "_fragment", "slug"]);
88
+ /**
89
+ * Keys the AGGREGATOR owns: the multi-source build writes them, and a writer
90
+ * setting one by hand is a mistake that shows up as a page routed to the
91
+ * wrong namespace/version (documented in the frontmatter-fields skill).
92
+ */
93
+ export const AGGREGATOR_OWNED = ["multiSource"];
94
+ export const EMPTY_POLICY = { taxonomies: {}, propSchema: {}, required: [], unknown: "ignore", roots: [""] };
95
+ /* ───────────────────────────── type checking ───────────────────────────── */
96
+ // `2026`, `2026-08` and RFC-1123 are all valid to the consumers (sitemap lastmod, `new Date()`),
97
+ // so the check is "a date this system can read", not one spelling of it
98
+ const isDateString = (v) => /^\d{4}(-\d{2}(-\d{2}([T ].*)?)?)?$/.test(v.trim()) || !Number.isNaN(Date.parse(v));
99
+ const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
100
+ /** The type name to SHOW for a value the writer got wrong. */
101
+ export const typeOf = (v) => {
102
+ if (v === null)
103
+ return "null";
104
+ if (typeof v === "number" && !Number.isFinite(v))
105
+ return Number.isNaN(v) ? "NaN" : "infinity";
106
+ if (Array.isArray(v))
107
+ return v.every((x) => typeof x === "string") ? "string[]" : "list";
108
+ if (v instanceof Date)
109
+ return "date";
110
+ return typeof v;
111
+ };
112
+ export function matchesType(value, type) {
113
+ switch (type) {
114
+ case "string": return typeof value === "string";
115
+ case "number": return typeof value === "number" && Number.isFinite(value);
116
+ case "boolean": return typeof value === "boolean";
117
+ // js-yaml turns an unquoted ISO date into a Date; a quoted one stays a string
118
+ case "date": return value instanceof Date || (typeof value === "string" && isDateString(value));
119
+ case "string[]": return isStringArray(value);
120
+ case "string|string[]": return typeof value === "string" || isStringArray(value);
121
+ case "object": return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
122
+ case "boolean|object": return typeof value === "boolean" || (typeof value === "object" && value !== null && !Array.isArray(value));
123
+ // the facet/profiling axes: the chunker stringifies scalars and splits a string on
124
+ // whitespace/commas, so `rev: 2` and `product: a, b` are both real authoring
125
+ case "scalar|scalar[]": {
126
+ const scalar = (v) => v !== null && typeof v !== "object";
127
+ return scalar(value) || (Array.isArray(value) && value.every(scalar));
128
+ }
129
+ }
130
+ }
131
+ /**
132
+ * The near-miss values for a bad enum entry: a case-only difference first
133
+ * (the overwhelmingly common typo), then a one-edit neighbour. A fix is
134
+ * offered only when exactly one candidate comes back.
135
+ */
136
+ export function nearMisses(value, allowed) {
137
+ const lower = value.toLowerCase().trim();
138
+ const caseOnly = allowed.filter((a) => a.toLowerCase() === lower);
139
+ if (caseOnly.length)
140
+ return caseOnly;
141
+ return allowed.filter((a) => editDistanceAtMost(a.toLowerCase(), lower, 2));
142
+ }
143
+ /**
144
+ * Whether a near miss may be APPLIED with one click, as opposed to merely
145
+ * listed. Only a case difference qualifies: at edit distance 2 the single
146
+ * candidate for `unstable` is `stable`, and for `review` it is `preview` —
147
+ * a one-click fix that inverts the writer's meaning is worse than no fix.
148
+ */
149
+ export const isSafeAutoFix = (value, candidate) => value.trim().toLowerCase() === candidate.toLowerCase();
150
+ /** Bounded Levenshtein: true when `a` and `b` are within `max` edits. */
151
+ function editDistanceAtMost(a, b, max) {
152
+ if (Math.abs(a.length - b.length) > max)
153
+ return false;
154
+ let prev = Array.from({ length: b.length + 1 }, (_, i) => i);
155
+ for (let i = 1; i <= a.length; i++) {
156
+ const row = [i];
157
+ let best = i;
158
+ for (let j = 1; j <= b.length; j++) {
159
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
160
+ const v = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + cost);
161
+ row.push(v);
162
+ best = Math.min(best, v);
163
+ }
164
+ if (best > max)
165
+ return false;
166
+ prev = row;
167
+ }
168
+ return prev[b.length] <= max;
169
+ }
170
+ /* ───────────────────────────── key positions ───────────────────────────── */
171
+ /**
172
+ * The 1-based line of a top-level key inside the frontmatter block, so a
173
+ * finding can be revealed where the writer wrote it. Only the block is
174
+ * scanned (the body may contain a line that looks like a key).
175
+ */
176
+ export function frontmatterKeyLines(source) {
177
+ const out = new Map();
178
+ const lines = source.split("\n");
179
+ if (lines[0]?.trim() !== "---")
180
+ return out;
181
+ for (let i = 1; i < lines.length; i++) {
182
+ const line = lines[i];
183
+ // the closer is at COLUMN 0 (what splitFrontmatter matches) — an indented `---` inside a
184
+ // block scalar is content, and breaking on it lost the line of every key after it
185
+ if (/^(---|\.\.\.)[ \t]*\r?$/.test(line))
186
+ break;
187
+ const m = /^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][\w.-]*))\s*:/.exec(line); // top level only: no leading space
188
+ const key = m?.[1] ?? m?.[2] ?? m?.[3];
189
+ if (key && !out.has(key))
190
+ out.set(key, i + 1);
191
+ }
192
+ return out;
193
+ }
194
+ /* ─────────────────────────────── globs ─────────────────────────────────── */
195
+ /**
196
+ * `content/guides/**` / `*.md` / `content/*​/index.md`. Deliberately small:
197
+ * `**` crosses directories, `*` does not, everything else is literal.
198
+ */
199
+ export function globMatches(glob, path) {
200
+ const escaped = glob
201
+ .split("**")
202
+ .map((part) => part.split("*").map((lit) => lit.replace(/[.+^${}()|[\]\\?]/g, "\\$&")).join("[^/]*"))
203
+ .join(".*");
204
+ return new RegExp(`^${escaped}$`).test(path);
205
+ }
206
+ /**
207
+ * The path a glob is matched against: relative to the content root the doc
208
+ * lives under, so `guides/**` means what the writer means when their content
209
+ * is `content/guides/…`. A doc outside every declared root is not content.
210
+ */
211
+ export function contentRelativePath(policy, path) {
212
+ const roots = policy.roots.length ? policy.roots : [""];
213
+ let best = null;
214
+ for (const root of roots) {
215
+ if (root === "") {
216
+ if (best === null)
217
+ best = path;
218
+ continue;
219
+ }
220
+ const prefix = root.replace(/\/+$/, "") + "/";
221
+ if (path.startsWith(prefix)) {
222
+ const rel = path.slice(prefix.length);
223
+ if (best === null || rel.length < best.length)
224
+ best = rel;
225
+ }
226
+ }
227
+ return best;
228
+ }
229
+ /** Fields required for a path by the declared globs (deduped, in declaration order). */
230
+ export function requiredFieldsFor(policy, path) {
231
+ const rel = contentRelativePath(policy, path);
232
+ if (rel === null)
233
+ return [];
234
+ const out = [];
235
+ for (const rule of policy.required) {
236
+ if (!globMatches(rule.glob, rel))
237
+ continue;
238
+ for (const f of rule.fields)
239
+ if (!out.includes(f))
240
+ out.push(f);
241
+ }
242
+ return out;
243
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,13 @@
1
- export type { TreeNode, InlineNode, InlineText, InlineLink, InlineImage, InlineCode, InlineFootnoteRef, InlineKbd, InlineIcon, InlineMath, InlineHtml, InlineBreak } from "./tree.js";
1
+ export type { TreeNode, InlineNode, InlineText, InlineLink, InlineAttrs, InlineImage, InlineCode, InlineFootnoteRef, InlineKbd, InlineIcon, InlineBadge, InlineMath, InlineHtml, InlineBreak } from "./tree.js";
2
+ export type { ConditionalNode, IncludeNode, VarDefNode, DirectiveRawNode, DirectiveBlockNode, InlineVariable, InlineConditionalSpan, InlineDirectiveRaw, InlineDirectiveNode, InlineNodeWithDirectives, ProfilingAttr, } from "./directives.js";
3
+ export { isConditional, isInclude, isVarDef, isDirectiveRaw, isDirectiveBlock, isInlineDirective, PROFILING_ATTRS, profilingOf, } from "./directives.js";
2
4
  export { treeToJson, chunkByHeadings, extractText } from "./json.js";
3
5
  export type { RagChunk } from "./json.js";
4
- export type { ExportPage, Heading, NavItem, FormatPlugin, FormatOption, SiteConfig, PlausibleConfig, TagPrefixDisplay, TagPaletteName, TaxonomyDisplay, LlmActionsConfig, LlmActionsPlacement, LlmProviderName } from "./format.js";
6
+ export type { ExportPage, Heading, NavItem, NavMark, NavMarkKind, FormatPlugin, FormatCapability, FormatOption, ImportResult, ImportLedgerEntry, SiteConfig, PlausibleConfig, TagPrefixDisplay, TagPaletteName, TaxonomyDisplay, LlmActionsConfig, LlmActionsPlacement, LlmProviderName, LinkIconsConfig } from "./format.js";
5
7
  export type { PageMeta, PageStatus, ParseMetaOptions } from "./meta.js";
6
- export { parseMeta } from "./meta.js";
8
+ export { STATUS_VALUES, parseMeta } from "./meta.js";
7
9
  export type { DogsbayPlugin, DogsbayPluginContext, DogsbayPluginFactory, PluginVisibleConfig, PluginLogger, PluginRule, PluginIssue, PluginConfigEntry, EmitFilesHelpers, AstroIntegrationRef, } from "./plugin.js";
8
- //# sourceMappingURL=index.d.ts.map
10
+ export { WELL_KNOWN_FIELDS, INERT_FIELDS, AGGREGATOR_OWNED, EMPTY_POLICY, typeOf, matchesType, nearMisses, isSafeAutoFix, frontmatterKeyLines, globMatches, contentRelativePath, requiredFieldsFor, } from "./frontmatter-schema.js";
11
+ export type { FieldType, FieldSpec, PropSpec, TaxonomySpec, FrontmatterPolicy } from "./frontmatter-schema.js";
12
+ export { checkFrontmatter, frontmatterPolicyFromConfig } from "./frontmatter-check.js";
13
+ export type { FrontmatterFinding } from "./frontmatter-check.js";
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ export { isConditional, isInclude, isVarDef, isDirectiveRaw, isDirectiveBlock, isInlineDirective, PROFILING_ATTRS, profilingOf, } from "./directives.js";
1
2
  export { treeToJson, chunkByHeadings, extractText } from "./json.js";
2
- export { parseMeta } from "./meta.js";
3
- //# sourceMappingURL=index.js.map
3
+ export { STATUS_VALUES, parseMeta } from "./meta.js";
4
+ export { WELL_KNOWN_FIELDS, INERT_FIELDS, AGGREGATOR_OWNED, EMPTY_POLICY, typeOf, matchesType, nearMisses, isSafeAutoFix, frontmatterKeyLines, globMatches, contentRelativePath, requiredFieldsFor, } from "./frontmatter-schema.js";
5
+ export { checkFrontmatter, frontmatterPolicyFromConfig } from "./frontmatter-check.js";
package/dist/json.d.ts CHANGED
@@ -23,4 +23,3 @@ export declare function chunkByHeadings(nodes: TreeNode[], maxLevel?: number): R
23
23
  * Extract plain text from a TreeNode, stripping any markup.
24
24
  */
25
25
  export declare function extractText(node: TreeNode): string;
26
- //# sourceMappingURL=json.d.ts.map
package/dist/json.js CHANGED
@@ -85,4 +85,3 @@ export function extractText(node) {
85
85
  function stripHtml(html) {
86
86
  return html.replace(/<[^>]+>/g, "").trim();
87
87
  }
88
- //# sourceMappingURL=json.js.map
package/dist/meta.d.ts CHANGED
@@ -19,13 +19,19 @@ export interface PageMeta {
19
19
  tags?: string[];
20
20
  /**
21
21
  * Broader grouping. Auto-derived from path when frontmatter
22
- * doesn't supply a valid value (`content/guides/auth.md` →
23
- * `["guides"]`). Override with `category: foo` or
24
- * `category: [foo, bar]`.
22
+ * doesn't supply a valid value, emitted as **cumulative slash-
23
+ * paths** so each value uniquely identifies its position in the
24
+ * hierarchy (`content/guides/oauth/setup.md` →
25
+ * `["guides", "guides/oauth"]`). The bare top segment is
26
+ * preserved so simple queries like `category:guides` still match
27
+ * the whole subtree. Override with `category: foo` or
28
+ * `category: [foo, bar]` (explicit values pass through
29
+ * unchanged — no auto-prefix).
25
30
  *
26
31
  * No first-class "belongs nowhere" sentinel in v1: `category: []`
27
32
  * falls through to slug-derived default. See
28
- * plans/metadata-and-taxonomies.md.
33
+ * plans/metadata-and-taxonomies.md and
34
+ * plans/hierarchical-facets.md.
29
35
  */
30
36
  category?: string[];
31
37
  /**
@@ -41,6 +47,16 @@ export interface PageMeta {
41
47
  /** ISO date strings. Consumers parse to Date when needed. */
42
48
  updated?: string;
43
49
  created?: string;
50
+ /**
51
+ * Post authors. Accepts a single string or a list in frontmatter;
52
+ * always normalized to a list here so consumers have one shape.
53
+ *
54
+ * Added for the blog capability (plans/blog-capability.md) — it was
55
+ * the only field a post needs that PageMeta did not already carry.
56
+ * Absent means "no byline", never "unknown author": the layout omits
57
+ * the row entirely rather than rendering a placeholder.
58
+ */
59
+ author?: string[];
44
60
  /** Sort hint for navigation/list pages. Lower weight first. */
45
61
  weight?: number;
46
62
  /**
@@ -77,6 +93,12 @@ export interface ParseMetaOptions {
77
93
  */
78
94
  taxonomyNames?: readonly string[];
79
95
  }
96
+ /**
97
+ * Closed enum for status validation. Exported so the frontmatter CHECKER
98
+ * (packages/commands) reports exactly the values this parser drops, instead
99
+ * of restating the list a third time.
100
+ */
101
+ export declare const STATUS_VALUES: readonly PageStatus[];
80
102
  /**
81
103
  * Parse and normalize frontmatter into `PageMeta`. Pure function;
82
104
  * no I/O. Unknown frontmatter keys are not lifted — they stay in
@@ -97,4 +119,3 @@ export interface ParseMetaOptions {
97
119
  * `meta.taxonomies` as string arrays.
98
120
  */
99
121
  export declare function parseMeta(frontmatter: Record<string, unknown> | undefined, options?: ParseMetaOptions): PageMeta;
100
- //# sourceMappingURL=meta.d.ts.map