@lexibase/rdx-core 1.3.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+ import { RdxContentSource, RdxDocPage, RdxProject } from '@lexibase/rdx-types';
2
+
3
+ type DocumentationDiagnostic = {
4
+ file: string;
5
+ line: number;
6
+ column: number;
7
+ code: 'page' | 'anchor' | 'asset' | 'syntax';
8
+ message: string;
9
+ };
10
+ type DocumentationCheck = {
11
+ checkedPages: number;
12
+ diagnostics: DocumentationDiagnostic[];
13
+ };
14
+ /** Host adapters can describe aliases without changing the project's authoring API. */
15
+ type DocumentationCheckOptions = {
16
+ documentRoutes?: (source: RdxContentSource, page: RdxDocPage, pages: readonly RdxDocPage[]) => string[];
17
+ sourceRoute?: (source: RdxContentSource) => string;
18
+ redirects?: Readonly<Record<string, string>>;
19
+ };
20
+ /** Read static MDX only. Never build Next, evaluate document JS or request URLs. */
21
+ declare function checkDocumentation(project: RdxProject, options?: DocumentationCheckOptions): DocumentationCheck;
22
+ declare function formatDocumentationCheck(report: DocumentationCheck): string;
23
+
24
+ export { checkDocumentation, formatDocumentationCheck };
25
+ export type { DocumentationCheck, DocumentationCheckOptions, DocumentationDiagnostic };
@@ -0,0 +1,256 @@
1
+ import {
2
+ getDocsIndex,
3
+ getSourceOptions,
4
+ parseStaticDocument
5
+ } from "../chunk-MALRN4SS.js";
6
+ import {
7
+ headingText
8
+ } from "../chunk-FPBRKD4M.js";
9
+ import {
10
+ RdxDocumentLinkError,
11
+ createDocumentLinkResolver
12
+ } from "../chunk-FWPJPY46.js";
13
+ import {
14
+ remarkDocumentationComponents
15
+ } from "../chunk-J7VCQHSL.js";
16
+
17
+ // src/check/index.ts
18
+ import fs from "fs";
19
+ import path from "path";
20
+ import GithubSlugger from "github-slugger";
21
+ import remarkGfm from "remark-gfm";
22
+ import remarkMdx from "remark-mdx";
23
+ import remarkParse from "remark-parse";
24
+ import { unified } from "unified";
25
+ var parser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx).use(remarkDocumentationComponents);
26
+ var sourceRoute = (source) => ["/docs", source.routePrefix].filter(Boolean).join("/");
27
+ var documentRoute = (source, page) => `${sourceRoute(source)}/${page.slug.split("/").map(encodeURIComponent).join("/")}`;
28
+ var identifier = (value) => value.trim().replace(/\s+/g, " ").toLowerCase();
29
+ function walk(node, visit) {
30
+ visit(node);
31
+ for (const child of node.children ?? []) walk(child, visit);
32
+ }
33
+ function parse(content) {
34
+ const tree = parser.runSync(parser.parse(content), { value: content });
35
+ const anchors = /* @__PURE__ */ new Set();
36
+ const references = [];
37
+ const definitions = /* @__PURE__ */ new Map();
38
+ const slugger = new GithubSlugger();
39
+ let dynamicIds = false;
40
+ walk(tree, (node) => {
41
+ if (node.type === "definition" && node.identifier && node.url && !definitions.has(identifier(node.identifier)))
42
+ definitions.set(identifier(node.identifier), node.url);
43
+ });
44
+ walk(tree, (node) => {
45
+ if (node.type === "heading") anchors.add(slugger.slug(headingText(node)));
46
+ if (node.type === "link" || node.type === "image") {
47
+ if (typeof node.url === "string")
48
+ references.push({
49
+ href: node.url,
50
+ image: node.type === "image",
51
+ position: node.position
52
+ });
53
+ }
54
+ if ((node.type === "linkReference" || node.type === "imageReference") && node.identifier) {
55
+ const href = definitions.get(identifier(node.identifier));
56
+ if (href)
57
+ references.push({
58
+ href,
59
+ image: node.type === "imageReference",
60
+ position: node.position
61
+ });
62
+ }
63
+ if (!node.type.startsWith("mdxJsx")) return;
64
+ for (const attribute of node.attributes ?? []) {
65
+ if (attribute.name === "id" || node.name === "a" && attribute.name === "name") {
66
+ if (typeof attribute.value === "string") anchors.add(attribute.value);
67
+ else if (attribute.value) dynamicIds = true;
68
+ }
69
+ if ((node.name === "a" && attribute.name === "href" || node.name === "img" && attribute.name === "src") && typeof attribute.value === "string") {
70
+ references.push({
71
+ href: attribute.value,
72
+ image: node.name === "img",
73
+ position: node.position
74
+ });
75
+ }
76
+ }
77
+ });
78
+ return { anchors, references, dynamicIds };
79
+ }
80
+ function checkDocumentation(project, options = {}) {
81
+ const diagnostics = [];
82
+ const documents = [];
83
+ const routes = /* @__PURE__ */ new Map();
84
+ const coreRoutes = /* @__PURE__ */ new Map();
85
+ const roots = /* @__PURE__ */ new Set(["/robots.txt", "/sitemap.xml"]);
86
+ const prefixes = [];
87
+ const redirects = new Map(Object.entries(options.redirects ?? {}));
88
+ const failed = /* @__PURE__ */ new Set();
89
+ const origin = project.config.metadata.metadataBase ? new URL(project.config.metadata.metadataBase).origin : "https://rdx.invalid";
90
+ const key = (href) => decodeURIComponent(new URL(href, origin).pathname).replace(/\/$/, "") || "/";
91
+ const rootFor = options.sourceRoute ?? sourceRoute;
92
+ const relativeFile = (file) => path.relative(project.rootDir, file).split(path.sep).join("/") || ".";
93
+ function syntax(error, file, offset = 0) {
94
+ const value = error;
95
+ diagnostics.push({
96
+ file: relativeFile(file),
97
+ line: value.mark ? value.mark.line + 1 : (value.line ?? 1) + offset,
98
+ column: value.column ?? (value.mark ? value.mark.column + 1 : 1),
99
+ code: "syntax",
100
+ message: value.message ?? String(error)
101
+ });
102
+ }
103
+ for (const source of project.sources) {
104
+ if (source.redirectTo !== void 0) {
105
+ const destination = project.sources.find(
106
+ (entry) => entry.routePrefix === source.redirectTo
107
+ );
108
+ prefixes.push([key(rootFor(source)), key(rootFor(destination))]);
109
+ continue;
110
+ }
111
+ let pages;
112
+ try {
113
+ pages = getDocsIndex(getSourceOptions(project, source), (error, file) => {
114
+ syntax(error, file);
115
+ failed.add(file);
116
+ }).flatMap((category) => category.pages);
117
+ } catch (error) {
118
+ syntax(error, getSourceOptions(project, source).docsDir);
119
+ continue;
120
+ }
121
+ roots.add(key(rootFor(source)));
122
+ if (project.config.search)
123
+ roots.add(`/rdx-search/${source.routePrefix || "_"}`);
124
+ for (const page of pages) {
125
+ const hrefs = options.documentRoutes?.(source, page, pages) ?? [
126
+ documentRoute(source, page)
127
+ ];
128
+ const document = {
129
+ page,
130
+ source,
131
+ href: hrefs[0],
132
+ lineOffset: 0
133
+ };
134
+ documents.push(document);
135
+ for (const href of hrefs) routes.set(key(href), document);
136
+ coreRoutes.set(key(documentRoute(source, page)), document);
137
+ if (page === pages[0]) {
138
+ routes.set(key(rootFor(source)), document);
139
+ if (source === project.sources[0]) routes.set("/docs", document);
140
+ }
141
+ }
142
+ }
143
+ if (project.config.homepage?.enabled) roots.add("/");
144
+ else redirects.set("/", "/docs");
145
+ for (const document of documents) {
146
+ if (failed.has(document.page.sourcePath)) continue;
147
+ try {
148
+ const raw = fs.readFileSync(document.page.sourcePath, "utf8");
149
+ const content = parseStaticDocument(raw).content;
150
+ document.lineOffset = (raw.slice(0, raw.length - content.length).match(/\n/g) ?? []).length;
151
+ document.parsed = parse(content);
152
+ } catch (error) {
153
+ syntax(error, document.page.sourcePath, document.lineOffset);
154
+ }
155
+ }
156
+ function redirectRoute(pathname) {
157
+ const seen = /* @__PURE__ */ new Set();
158
+ while (!seen.has(pathname)) {
159
+ seen.add(pathname);
160
+ const exact = redirects.get(pathname);
161
+ const prefix = prefixes.find(
162
+ ([from]) => pathname === from || pathname.startsWith(`${from}/`)
163
+ );
164
+ const next = exact ? key(exact) : prefix ? prefix[1] + pathname.slice(prefix[0].length) : pathname;
165
+ if (next === pathname) return pathname;
166
+ pathname = next;
167
+ }
168
+ throw new Error("The destination contains a redirect loop.");
169
+ }
170
+ for (const document of documents) {
171
+ const parsed = document.parsed;
172
+ if (!parsed) continue;
173
+ const resolve = createDocumentLinkResolver({
174
+ sourceRoot: getSourceOptions(project, document.source).docsDir,
175
+ sourcePath: document.page.sourcePath,
176
+ routePrefix: document.source.routePrefix,
177
+ documents: documents.filter((entry) => entry.source === document.source).map((entry) => entry.page)
178
+ });
179
+ for (const reference of parsed.references) {
180
+ let code = reference.image ? "asset" : "page";
181
+ try {
182
+ const url = new URL(reference.href, `${origin}${document.href}`);
183
+ if (!["http:", "https:"].includes(url.protocol)) continue;
184
+ if (url.origin !== origin) continue;
185
+ if (!project.config.metadata.metadataBase && /^(?:[a-z][\w+.-]*:|\/\/)/i.test(reference.href))
186
+ continue;
187
+ let target;
188
+ let pathname;
189
+ const explicitMdx = !reference.image && !/^(?:[a-z][\w+.-]*:|\/|#|\?)/i.test(reference.href) && /\.mdx(?:[?#]|$)/.test(decodeURIComponent(reference.href));
190
+ if (explicitMdx) {
191
+ const resolved = resolve(reference.href);
192
+ pathname = key(resolved);
193
+ target = coreRoutes.get(pathname);
194
+ } else {
195
+ pathname = redirectRoute(key(url.href));
196
+ if (!reference.image) target = routes.get(pathname);
197
+ }
198
+ if (target) {
199
+ if (url.hash) {
200
+ code = "anchor";
201
+ const anchor = decodeURIComponent(url.hash.slice(1));
202
+ if (target.parsed && !target.parsed.dynamicIds && !target.parsed.anchors.has(anchor))
203
+ throw new Error(
204
+ `Section "#${anchor}" does not exist in ${relativeFile(target.page.sourcePath)}.`
205
+ );
206
+ }
207
+ continue;
208
+ }
209
+ if (!reference.image && roots.has(pathname)) continue;
210
+ code = reference.image || !/^\/docs(?:\/|$)/.test(pathname) ? "asset" : "page";
211
+ if (pathname.includes("\\") || pathname.includes("\0"))
212
+ throw new Error("Use a valid URL with forward slashes.");
213
+ const publicRoot = path.resolve(project.rootDir, "public");
214
+ const asset = path.resolve(publicRoot, `.${pathname}`);
215
+ const relative = path.relative(publicRoot, asset);
216
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
217
+ throw new Error("The destination escapes public/.");
218
+ let exists = false;
219
+ try {
220
+ exists = fs.statSync(asset).isFile();
221
+ } catch {
222
+ }
223
+ if (!exists)
224
+ throw new Error(
225
+ code === "page" ? `Documentation page "${pathname}" does not exist.` : `Local file "${pathname}" does not exist in public/.`
226
+ );
227
+ } catch (error) {
228
+ const value = error instanceof RdxDocumentLinkError ? error.reason : error instanceof Error ? error.message : String(error);
229
+ diagnostics.push({
230
+ file: relativeFile(document.page.sourcePath),
231
+ line: (reference.position?.start.line ?? 1) + document.lineOffset,
232
+ column: reference.position?.start.column ?? 1,
233
+ code,
234
+ message: `"${reference.href}": ${value}`
235
+ });
236
+ }
237
+ }
238
+ }
239
+ diagnostics.sort(
240
+ (a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column
241
+ );
242
+ return { checkedPages: documents.length, diagnostics };
243
+ }
244
+ function formatDocumentationCheck(report) {
245
+ const lines = report.diagnostics.map(
246
+ (entry) => `${entry.file}:${entry.line}:${entry.column} [${entry.code}] ${entry.message}`
247
+ );
248
+ lines.push(
249
+ `RDX check ${report.diagnostics.length ? "failed" : "passed"}: ${report.checkedPages} ${report.checkedPages === 1 ? "page" : "pages"} checked, ${report.diagnostics.length} ${report.diagnostics.length === 1 ? "problem" : "problems"}.`
250
+ );
251
+ return lines.join("\n");
252
+ }
253
+ export {
254
+ checkDocumentation,
255
+ formatDocumentationCheck
256
+ };
@@ -53,7 +53,6 @@ function validateMetadata(input) {
53
53
  "keywords",
54
54
  "icons",
55
55
  "manifest",
56
- "robots",
57
56
  "openGraph",
58
57
  "twitter"
59
58
  ]);
@@ -93,15 +92,6 @@ function validateMetadata(input) {
93
92
  else url(value, field, true);
94
93
  }
95
94
  }
96
- if (metadata.robots !== void 0) {
97
- const robots = object2(metadata.robots, "metadata.robots", [
98
- "index",
99
- "follow"
100
- ]);
101
- for (const [key, value] of Object.entries(robots))
102
- if (value !== void 0 && typeof value !== "boolean")
103
- throw new RdxConfigError(`metadata.robots.${key} must be a boolean.`);
104
- }
105
95
  for (const key of ["openGraph", "twitter"]) {
106
96
  if (metadata[key] === void 0) continue;
107
97
  const field = `metadata.${key}`;
@@ -353,6 +343,7 @@ async function createRdxProject(input, {
353
343
  "build",
354
344
  "start",
355
345
  "prepare",
346
+ "check",
356
347
  "help",
357
348
  "add"
358
349
  ]);
@@ -441,9 +432,21 @@ async function createRdxProject(input, {
441
432
  }
442
433
  if (source.badge !== void 0)
443
434
  text(source.badge, `content source ${id}.badge`);
435
+ if (source.redirectTo !== void 0)
436
+ text(source.redirectTo, `content source ${id}.redirectTo`);
444
437
  sources.push(source);
445
438
  }
446
439
  }
440
+ for (const source of sources) {
441
+ if (source.redirectTo === void 0) continue;
442
+ const target = sources.find(
443
+ (entry) => entry.routePrefix === source.redirectTo
444
+ );
445
+ if (!target || target === source || target.redirectTo !== void 0 || target.docsDir !== source.docsDir)
446
+ throw new RdxConfigError(
447
+ `content source ${source.id}.redirectTo must reference a canonical source with the same docsDir.`
448
+ );
449
+ }
447
450
  return { rootDir, config, sources, commands, runtimeFiles: [...runtimeFiles] };
448
451
  }
449
452
 
@@ -0,0 +1,14 @@
1
+ // src/mdx/heading-text.ts
2
+ function headingText(node) {
3
+ if (["image", "imageReference", "break"].includes(node.type)) return "";
4
+ if (node.children) return node.children.map(headingText).join("");
5
+ if (["mdxjsEsm", "mdxFlowExpression", "mdxTextExpression", "html"].includes(
6
+ node.type
7
+ ))
8
+ return "";
9
+ return node.value ?? "";
10
+ }
11
+
12
+ export {
13
+ headingText
14
+ };
@@ -3,8 +3,10 @@ import path from "path";
3
3
  var RdxDocumentLinkError = class extends Error {
4
4
  constructor(sourcePath, href, reason) {
5
5
  super(`[RDX] Invalid document link "${href}" in ${sourcePath}: ${reason}`);
6
+ this.reason = reason;
6
7
  this.name = "RdxDocumentLinkError";
7
8
  }
9
+ reason;
8
10
  };
9
11
  function createDocumentLinkResolver(options) {
10
12
  const root = path.resolve(options.sourceRoot);
@@ -172,7 +172,12 @@ function remarkDocumentationComponents() {
172
172
  throw new Error("[RDX] Write keyboard keys as :kbd[Ctrl].");
173
173
  const key = label(node.children ?? []);
174
174
  if (!key) throw new Error("[RDX] :kbd[...] requires a key name.");
175
- return component("Kbd", {}, [{ type: "text", value: key }], true);
175
+ return component(
176
+ /\s+\+\s+/.test(key) ? "KeyboardShortcut" : "Kbd",
177
+ {},
178
+ [{ type: "text", value: key }],
179
+ true
180
+ );
176
181
  }
177
182
  if (node.type !== "containerDirective")
178
183
  throw new Error(
@@ -0,0 +1,194 @@
1
+ // src/content/static-source.ts
2
+ import matter from "gray-matter";
3
+ function parseStaticDocument(source) {
4
+ const text = source.replace(/^\uFEFF/, "");
5
+ if (text.startsWith("---") && text[3] !== "-") {
6
+ const language = matter.language(text).name.toLowerCase();
7
+ if (language && !["yaml", "yml", "json"].includes(language))
8
+ throw new Error(
9
+ "rdx check accepts YAML or JSON frontmatter, without executing document code."
10
+ );
11
+ }
12
+ return matter(source, {});
13
+ }
14
+
15
+ // src/content/index.ts
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import matter2 from "gray-matter";
19
+ var MDX_EXTENSION = ".mdx";
20
+ var DEFAULT_POSITION = Number.MAX_SAFE_INTEGER;
21
+ function getDocsRoot(docsDir = "docs") {
22
+ return path.resolve(
23
+ /* turbopackIgnore: true */
24
+ process.cwd(),
25
+ docsDir
26
+ );
27
+ }
28
+ function toTitle(value) {
29
+ return value.replace(/[-_]/g, " ").replace(/\b\w/g, (character) => character.toUpperCase());
30
+ }
31
+ function isRecord(value) {
32
+ return typeof value === "object" && value !== null;
33
+ }
34
+ function stringValue(value, fallback) {
35
+ return typeof value === "string" && value.trim() ? value : fallback;
36
+ }
37
+ function numberValue(value, fallback = DEFAULT_POSITION) {
38
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
39
+ }
40
+ function readCategoryMeta(categoryPath, fallbackTitle) {
41
+ const metaPath = path.join(categoryPath, "_category.json");
42
+ if (!fs.existsSync(metaPath)) {
43
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
44
+ }
45
+ try {
46
+ const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
47
+ if (!isRecord(parsed)) {
48
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
49
+ }
50
+ return {
51
+ title: stringValue(parsed.title, fallbackTitle),
52
+ position: numberValue(parsed.sidebar_position)
53
+ };
54
+ } catch {
55
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
56
+ }
57
+ }
58
+ function findMdxFiles(directory) {
59
+ const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
60
+ return entries.flatMap((entry) => {
61
+ const entryPath = path.join(directory, entry.name);
62
+ if (entry.isDirectory()) return findMdxFiles(entryPath);
63
+ if (entry.isFile() && entry.name.endsWith(MDX_EXTENSION)) return [entryPath];
64
+ return [];
65
+ });
66
+ }
67
+ function slugFromRelativePath(relativePath) {
68
+ return relativePath.split(path.sep).join("/").replace(/\.mdx$/, "");
69
+ }
70
+ function isSafeSlug(slug) {
71
+ if (path.isAbsolute(slug) || slug.includes("\\")) return false;
72
+ return slug.split("/").every((segment) => segment && segment !== "." && segment !== "..");
73
+ }
74
+ function getDocsIndex({ docsDir } = {}, onError) {
75
+ const docsRoot = getDocsRoot(docsDir);
76
+ if (!fs.existsSync(docsRoot)) return [];
77
+ const categories = /* @__PURE__ */ new Map();
78
+ for (const filePath of findMdxFiles(docsRoot)) {
79
+ const relativePath = path.relative(docsRoot, filePath);
80
+ const pathParts = relativePath.split(path.sep);
81
+ const categoryId = pathParts.length > 1 ? pathParts[0] ?? "_root" : "_root";
82
+ const categoryPath = categoryId === "_root" ? docsRoot : path.join(docsRoot, categoryId);
83
+ const fallbackCategoryTitle = categoryId === "_root" ? "Overview" : toTitle(categoryId);
84
+ let category = categories.get(categoryId);
85
+ if (!category) {
86
+ const meta = readCategoryMeta(categoryPath, fallbackCategoryTitle);
87
+ const createdCategory = {
88
+ id: categoryId,
89
+ title: meta.title,
90
+ position: meta.position,
91
+ pages: [],
92
+ categoryPath
93
+ };
94
+ categories.set(categoryId, createdCategory);
95
+ category = createdCategory;
96
+ }
97
+ let frontmatter = {};
98
+ try {
99
+ const raw = fs.readFileSync(filePath, "utf8");
100
+ const parsed = onError ? parseStaticDocument(raw) : matter2(raw);
101
+ frontmatter = isRecord(parsed.data) ? parsed.data : {};
102
+ } catch (error) {
103
+ if (!onError) throw error;
104
+ onError(error, filePath);
105
+ }
106
+ const slug = slugFromRelativePath(relativePath);
107
+ const fallbackTitle = toTitle(path.basename(slug));
108
+ category.pages.push({
109
+ slug,
110
+ title: stringValue(frontmatter.title, fallbackTitle),
111
+ description: stringValue(frontmatter.description, ""),
112
+ position: numberValue(frontmatter.link_position),
113
+ sourcePath: filePath
114
+ });
115
+ }
116
+ return [...categories.values()].map(({ categoryPath: _categoryPath, ...category }) => ({
117
+ ...category,
118
+ pages: category.pages.sort(
119
+ (first, second) => first.position - second.position || first.slug.localeCompare(second.slug)
120
+ )
121
+ })).sort(
122
+ (first, second) => first.position - second.position || first.title.localeCompare(second.title)
123
+ );
124
+ }
125
+ function getDocsPaths(options) {
126
+ return getDocsIndex(options).flatMap(
127
+ (category) => category.pages.map((page) => page.slug)
128
+ );
129
+ }
130
+ function getDocument(slug, { docsDir } = {}) {
131
+ if (!isSafeSlug(slug)) return null;
132
+ const docsRoot = getDocsRoot(docsDir);
133
+ const sourcePath = path.resolve(docsRoot, `${slug}${MDX_EXTENSION}`);
134
+ const relativePath = path.relative(docsRoot, sourcePath);
135
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath))
136
+ return null;
137
+ if (!fs.existsSync(sourcePath)) return null;
138
+ const parsed = matter2(fs.readFileSync(sourcePath, "utf8"));
139
+ return {
140
+ slug,
141
+ sourcePath,
142
+ content: parsed.content,
143
+ frontmatter: isRecord(parsed.data) ? parsed.data : {}
144
+ };
145
+ }
146
+
147
+ // src/project/index.ts
148
+ import path2 from "path";
149
+ function getSourceOptions(project, source) {
150
+ return { docsDir: path2.resolve(project.rootDir, source.docsDir) };
151
+ }
152
+ function resolveDocsRoute(project, segments = []) {
153
+ const source = project.sources.find(
154
+ (entry) => entry.routePrefix && entry.routePrefix === segments[0]
155
+ ) ?? project.sources[0];
156
+ const options = getSourceOptions(project, source);
157
+ const slug = (source.routePrefix ? segments.slice(1) : segments).join("/") || getDocsPaths(options)[0];
158
+ return {
159
+ source,
160
+ slug,
161
+ document: slug ? getDocument(slug, options) : null,
162
+ categories: getDocsIndex(options)
163
+ };
164
+ }
165
+ function getProjectDocsPaths(project) {
166
+ const paths = /* @__PURE__ */ new Set();
167
+ for (const source of project.sources) {
168
+ if (source.redirectTo !== void 0) continue;
169
+ for (const slug of getDocsPaths(getSourceOptions(project, source))) {
170
+ const route = [source.routePrefix, slug].filter(Boolean).join("/");
171
+ if (paths.has(route))
172
+ throw new Error(`Conflicting documentation route: /docs/${route}`);
173
+ if (!source.routePrefix && project.sources.some(
174
+ (other) => other.routePrefix === slug.split("/")[0]
175
+ )) {
176
+ throw new Error(
177
+ `Live documentation route /docs/${slug} conflicts with a plugin content source.`
178
+ );
179
+ }
180
+ paths.add(route);
181
+ }
182
+ }
183
+ return [...paths];
184
+ }
185
+
186
+ export {
187
+ parseStaticDocument,
188
+ getDocsIndex,
189
+ getDocsPaths,
190
+ getDocument,
191
+ getSourceOptions,
192
+ resolveDocsRoute,
193
+ getProjectDocsPaths
194
+ };
@@ -4,7 +4,7 @@ import {
4
4
  defineConfig,
5
5
  resolveConfig,
6
6
  resolveProjectPath
7
- } from "../chunk-ZX6IDGQW.js";
7
+ } from "../chunk-6GMOZSPH.js";
8
8
  export {
9
9
  RdxConfigError,
10
10
  createRdxProject,
@@ -8,6 +8,7 @@ interface DocumentLinkOptions {
8
8
  }[];
9
9
  }
10
10
  declare class RdxDocumentLinkError extends Error {
11
+ readonly reason: string;
11
12
  constructor(sourcePath: string, href: string, reason: string);
12
13
  }
13
14
  /** Resolve only explicit relative MDX links within the current content source. */
package/dist/index.d.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import * as _lexibase_rdx_types from '@lexibase/rdx-types';
2
2
  import { RdxDocsOptions, RdxDocCategory, RdxDocument, RdxProject, RdxContentSource } from '@lexibase/rdx-types';
3
- export { D as DocumentLinkOptions, R as RdxDocumentLinkError, c as createDocumentLinkResolver } from './document-links-BtWSWs2x.js';
3
+ export { D as DocumentLinkOptions, R as RdxDocumentLinkError, c as createDocumentLinkResolver } from './document-links-CkvFGpe1.js';
4
4
  export { RdxConfigError, createRdxProject, defineConfig, resolveConfig, resolveProjectPath } from './config/index.js';
5
5
 
6
6
  /**
7
7
  * Reads the documentation tree from the user's project. The URL slug always
8
8
  * preserves the full path, so `guides/intro.mdx` and `api/intro.mdx` never
9
9
  * collide.
10
+ * With onError, static readers collect per-file failures and retain fallback
11
+ * route metadata. Default callers keep the existing fail-fast behavior.
10
12
  */
11
- declare function getDocsIndex({ docsDir, }?: RdxDocsOptions): RdxDocCategory[];
13
+ declare function getDocsIndex({ docsDir }?: RdxDocsOptions, onError?: (error: unknown, sourcePath: string) => void): RdxDocCategory[];
12
14
  declare function getDocsPaths(options?: RdxDocsOptions): string[];
13
15
  declare function getDocument(slug: string, { docsDir }?: RdxDocsOptions): RdxDocument | null;
14
16
 
package/dist/index.js CHANGED
@@ -1,180 +1,22 @@
1
+ import {
2
+ getDocsIndex,
3
+ getDocsPaths,
4
+ getDocument,
5
+ getProjectDocsPaths,
6
+ getSourceOptions,
7
+ resolveDocsRoute
8
+ } from "./chunk-MALRN4SS.js";
1
9
  import {
2
10
  RdxConfigError,
3
11
  createRdxProject,
4
12
  defineConfig,
5
13
  resolveConfig,
6
14
  resolveProjectPath
7
- } from "./chunk-ZX6IDGQW.js";
15
+ } from "./chunk-6GMOZSPH.js";
8
16
  import {
9
17
  RdxDocumentLinkError,
10
18
  createDocumentLinkResolver
11
- } from "./chunk-Z6GCGXVC.js";
12
-
13
- // src/content/index.ts
14
- import fs from "fs";
15
- import path from "path";
16
- import matter from "gray-matter";
17
- var MDX_EXTENSION = ".mdx";
18
- var DEFAULT_POSITION = Number.MAX_SAFE_INTEGER;
19
- function getDocsRoot(docsDir = "docs") {
20
- return path.resolve(
21
- /* turbopackIgnore: true */
22
- process.cwd(),
23
- docsDir
24
- );
25
- }
26
- function toTitle(value) {
27
- return value.replace(/[-_]/g, " ").replace(/\b\w/g, (character) => character.toUpperCase());
28
- }
29
- function isRecord(value) {
30
- return typeof value === "object" && value !== null;
31
- }
32
- function stringValue(value, fallback) {
33
- return typeof value === "string" && value.trim() ? value : fallback;
34
- }
35
- function numberValue(value, fallback = DEFAULT_POSITION) {
36
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
37
- }
38
- function readCategoryMeta(categoryPath, fallbackTitle) {
39
- const metaPath = path.join(categoryPath, "_category.json");
40
- if (!fs.existsSync(metaPath)) {
41
- return { title: fallbackTitle, position: DEFAULT_POSITION };
42
- }
43
- try {
44
- const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
45
- if (!isRecord(parsed)) {
46
- return { title: fallbackTitle, position: DEFAULT_POSITION };
47
- }
48
- return {
49
- title: stringValue(parsed.title, fallbackTitle),
50
- position: numberValue(parsed.sidebar_position)
51
- };
52
- } catch {
53
- return { title: fallbackTitle, position: DEFAULT_POSITION };
54
- }
55
- }
56
- function findMdxFiles(directory) {
57
- const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
58
- return entries.flatMap((entry) => {
59
- const entryPath = path.join(directory, entry.name);
60
- if (entry.isDirectory()) return findMdxFiles(entryPath);
61
- if (entry.isFile() && entry.name.endsWith(MDX_EXTENSION)) return [entryPath];
62
- return [];
63
- });
64
- }
65
- function slugFromRelativePath(relativePath) {
66
- return relativePath.split(path.sep).join("/").replace(/\.mdx$/, "");
67
- }
68
- function isSafeSlug(slug) {
69
- if (path.isAbsolute(slug) || slug.includes("\\")) return false;
70
- return slug.split("/").every((segment) => segment && segment !== "." && segment !== "..");
71
- }
72
- function getDocsIndex({
73
- docsDir
74
- } = {}) {
75
- const docsRoot = getDocsRoot(docsDir);
76
- if (!fs.existsSync(docsRoot)) return [];
77
- const categories = /* @__PURE__ */ new Map();
78
- for (const filePath of findMdxFiles(docsRoot)) {
79
- const relativePath = path.relative(docsRoot, filePath);
80
- const pathParts = relativePath.split(path.sep);
81
- const categoryId = pathParts.length > 1 ? pathParts[0] ?? "_root" : "_root";
82
- const categoryPath = categoryId === "_root" ? docsRoot : path.join(docsRoot, categoryId);
83
- const fallbackCategoryTitle = categoryId === "_root" ? "Overview" : toTitle(categoryId);
84
- let category = categories.get(categoryId);
85
- if (!category) {
86
- const meta = readCategoryMeta(categoryPath, fallbackCategoryTitle);
87
- const createdCategory = {
88
- id: categoryId,
89
- title: meta.title,
90
- position: meta.position,
91
- pages: [],
92
- categoryPath
93
- };
94
- categories.set(categoryId, createdCategory);
95
- category = createdCategory;
96
- }
97
- const source = fs.readFileSync(filePath, "utf8");
98
- const parsed = matter(source);
99
- const frontmatter = isRecord(parsed.data) ? parsed.data : {};
100
- const slug = slugFromRelativePath(relativePath);
101
- const fallbackTitle = toTitle(path.basename(slug));
102
- category.pages.push({
103
- slug,
104
- title: stringValue(frontmatter.title, fallbackTitle),
105
- description: stringValue(frontmatter.description, ""),
106
- position: numberValue(frontmatter.link_position),
107
- sourcePath: filePath
108
- });
109
- }
110
- return [...categories.values()].map(({ categoryPath: _categoryPath, ...category }) => ({
111
- ...category,
112
- pages: category.pages.sort(
113
- (first, second) => first.position - second.position || first.slug.localeCompare(second.slug)
114
- )
115
- })).sort(
116
- (first, second) => first.position - second.position || first.title.localeCompare(second.title)
117
- );
118
- }
119
- function getDocsPaths(options) {
120
- return getDocsIndex(options).flatMap(
121
- (category) => category.pages.map((page) => page.slug)
122
- );
123
- }
124
- function getDocument(slug, { docsDir } = {}) {
125
- if (!isSafeSlug(slug)) return null;
126
- const docsRoot = getDocsRoot(docsDir);
127
- const sourcePath = path.resolve(docsRoot, `${slug}${MDX_EXTENSION}`);
128
- const relativePath = path.relative(docsRoot, sourcePath);
129
- if (relativePath.startsWith("..") || path.isAbsolute(relativePath))
130
- return null;
131
- if (!fs.existsSync(sourcePath)) return null;
132
- const parsed = matter(fs.readFileSync(sourcePath, "utf8"));
133
- return {
134
- slug,
135
- sourcePath,
136
- content: parsed.content,
137
- frontmatter: isRecord(parsed.data) ? parsed.data : {}
138
- };
139
- }
140
-
141
- // src/project/index.ts
142
- import path2 from "path";
143
- function getSourceOptions(project, source) {
144
- return { docsDir: path2.resolve(project.rootDir, source.docsDir) };
145
- }
146
- function resolveDocsRoute(project, segments = []) {
147
- const source = project.sources.find(
148
- (entry) => entry.routePrefix && entry.routePrefix === segments[0]
149
- ) ?? project.sources[0];
150
- const options = getSourceOptions(project, source);
151
- const slug = (source.routePrefix ? segments.slice(1) : segments).join("/") || getDocsPaths(options)[0];
152
- return {
153
- source,
154
- slug,
155
- document: slug ? getDocument(slug, options) : null,
156
- categories: getDocsIndex(options)
157
- };
158
- }
159
- function getProjectDocsPaths(project) {
160
- const paths = /* @__PURE__ */ new Set();
161
- for (const source of project.sources) {
162
- for (const slug of getDocsPaths(getSourceOptions(project, source))) {
163
- const route = [source.routePrefix, slug].filter(Boolean).join("/");
164
- if (paths.has(route))
165
- throw new Error(`Conflicting documentation route: /docs/${route}`);
166
- if (!source.routePrefix && project.sources.some(
167
- (other) => other.routePrefix === slug.split("/")[0]
168
- )) {
169
- throw new Error(
170
- `Live documentation route /docs/${slug} conflicts with a plugin content source.`
171
- );
172
- }
173
- paths.add(route);
174
- }
175
- }
176
- return [...paths];
177
- }
19
+ } from "./chunk-FWPJPY46.js";
178
20
  export {
179
21
  RdxConfigError,
180
22
  RdxDocumentLinkError,
@@ -1,4 +1,4 @@
1
- export { D as DocumentLinkOptions, r as remarkDocumentLinks } from '../document-links-BtWSWs2x.js';
1
+ export { D as DocumentLinkOptions, r as remarkDocumentLinks } from '../document-links-CkvFGpe1.js';
2
2
  export { default as rehypeDocumentationHeadings } from 'rehype-slug';
3
3
  import rehypeShiki from '@shikijs/rehype';
4
4
  import remarkDirective from 'remark-directive';
package/dist/mdx/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  remarkDocumentLinks
3
- } from "../chunk-Z6GCGXVC.js";
3
+ } from "../chunk-FWPJPY46.js";
4
4
  import {
5
5
  remarkDocumentationComponents
6
- } from "../chunk-H2E5IS4E.js";
6
+ } from "../chunk-J7VCQHSL.js";
7
7
 
8
8
  // src/mdx/index.ts
9
9
  import { default as default2 } from "rehype-slug";
@@ -1,6 +1,9 @@
1
+ import {
2
+ headingText
3
+ } from "../chunk-FPBRKD4M.js";
1
4
  import {
2
5
  remarkDocumentationComponents
3
- } from "../chunk-H2E5IS4E.js";
6
+ } from "../chunk-J7VCQHSL.js";
4
7
 
5
8
  // src/search/index.ts
6
9
  import GithubSlugger from "github-slugger";
@@ -35,11 +38,6 @@ function text(node) {
35
38
  function plain(value) {
36
39
  return value.replace(/\s+/g, " ").trim();
37
40
  }
38
- function headingText(node) {
39
- if (["image", "imageReference", "break"].includes(node.type)) return "";
40
- if (node.children) return node.children.map(headingText).join("");
41
- return text(node);
42
- }
43
41
  function buildSearchIndex(documents) {
44
42
  const entries = [];
45
43
  for (const document of documents) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lexibase/rdx-core",
3
- "version": "1.3.0",
3
+ "version": "2.0.0",
4
4
  "description": "Content indexing and document utilities for RDX documentation projects.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,6 +19,10 @@
19
19
  "types": "./dist/mdx/index.d.ts",
20
20
  "import": "./dist/mdx/index.js"
21
21
  },
22
+ "./check": {
23
+ "types": "./dist/check/index.d.ts",
24
+ "import": "./dist/check/index.js"
25
+ },
22
26
  "./search": {
23
27
  "types": "./dist/search/index.d.ts",
24
28
  "import": "./dist/search/index.js"
@@ -50,7 +54,7 @@
50
54
  "remark-mdx": "^3.1.1",
51
55
  "remark-parse": "^11.0.0",
52
56
  "unified": "^11.0.5",
53
- "@lexibase/rdx-types": "1.1.1"
57
+ "@lexibase/rdx-types": "2.0.0"
54
58
  },
55
59
  "devDependencies": {
56
60
  "@types/node": "^22.15.3",
@@ -62,8 +66,8 @@
62
66
  "node": "^22.18.0 || ^24.11.0"
63
67
  },
64
68
  "scripts": {
65
- "dev": "tsup src/index.ts src/config/index.ts src/mdx/index.ts src/search/index.ts --format esm --dts --watch --external @lexibase/rdx-types --external gray-matter",
66
- "build": "tsup src/index.ts src/config/index.ts src/mdx/index.ts src/search/index.ts --format esm --dts --clean --external @lexibase/rdx-types --external gray-matter",
69
+ "dev": "tsup src/index.ts src/config/index.ts src/mdx/index.ts src/search/index.ts src/check/index.ts --format esm --dts --watch --external @lexibase/rdx-types --external gray-matter",
70
+ "build": "tsup src/index.ts src/config/index.ts src/mdx/index.ts src/search/index.ts src/check/index.ts --format esm --dts --clean --external @lexibase/rdx-types --external gray-matter",
67
71
  "check-types": "tsc --noEmit",
68
72
  "test": "node --test tests/*.test.mjs"
69
73
  }