@tokenroll/llmdoc 3.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,421 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import matter from "gray-matter";
4
+ import { DOC_LINE_WARNING_LIMIT } from "./constants.js";
5
+ import { CliError } from "./errors.js";
6
+ import { estimateTokens, extractCodeRefs, extractLinks, extractTitle, resolveDocLink, stripMarkdownLiterals, validateCodeRefTags } from "./markdown.js";
7
+ import { assertDocKindMatchesShape, parseDocTargetShape } from "./doc-shape.js";
8
+ import { normalizeRepoRelativePath, repoPath, resolveInsideRoot } from "./fs.js";
9
+ import { gitCommitExists } from "./git.js";
10
+ import { validateDocFrontmatter, validateMeta } from "./schema.js";
11
+ export function loadWorkspace(rootDir) {
12
+ const configuredLlmdocDir = path.join(rootDir, "llmdoc");
13
+ if (!fs.existsSync(configuredLlmdocDir) || !fs.statSync(configuredLlmdocDir).isDirectory()) {
14
+ throw new CliError("仓库内不存在 llmdoc/ 目录。", 2);
15
+ }
16
+ resolveInsideRoot(rootDir, "llmdoc");
17
+ const llmdocDir = configuredLlmdocDir;
18
+ const preloadIssues = [];
19
+ const documents = scanDocuments(rootDir, llmdocDir, preloadIssues);
20
+ const documentsByLlmdocPath = new Map(documents.map((document) => [document.llmdocPath, document]));
21
+ const topics = new Map();
22
+ const rootSingletons = [];
23
+ for (const document of documents) {
24
+ if (document.topic) {
25
+ const bucket = topics.get(document.topic) ?? [];
26
+ bucket.push(document);
27
+ topics.set(document.topic, bucket);
28
+ }
29
+ else {
30
+ rootSingletons.push(document);
31
+ }
32
+ }
33
+ for (const docs of topics.values()) {
34
+ docs.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
35
+ }
36
+ rootSingletons.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
37
+ const metaPath = path.join(llmdocDir, "meta.json");
38
+ const meta = loadMeta(metaPath, preloadIssues);
39
+ return {
40
+ rootDir,
41
+ llmdocDir,
42
+ metaPath,
43
+ documents,
44
+ documentsByLlmdocPath,
45
+ topics,
46
+ rootSingletons,
47
+ meta,
48
+ preloadIssues
49
+ };
50
+ }
51
+ function scanDocuments(rootDir, llmdocDir, preloadIssues) {
52
+ const results = [];
53
+ walk(llmdocDir, (absolutePath) => {
54
+ const repoRelativePath = repoPath(rootDir, absolutePath);
55
+ if (!absolutePath.endsWith(".mdx")) {
56
+ if (absolutePath !== path.join(llmdocDir, "meta.json")) {
57
+ preloadIssues.push({
58
+ severity: "error",
59
+ code: "file.extension.invalid",
60
+ path: repoRelativePath,
61
+ message: "llmdoc/ 下仅允许 .mdx 文档与根级唯一 meta.json。"
62
+ });
63
+ }
64
+ return;
65
+ }
66
+ const raw = fs.readFileSync(absolutePath, "utf8");
67
+ let parsed;
68
+ try {
69
+ parsed = matter(raw);
70
+ }
71
+ catch (error) {
72
+ preloadIssues.push({
73
+ severity: "error",
74
+ code: "frontmatter.parse",
75
+ path: repoRelativePath,
76
+ message: `front matter 解析失败: ${error.message}`
77
+ });
78
+ return;
79
+ }
80
+ const frontmatter = parsed.data;
81
+ const llmdocPath = repoPath(llmdocDir, absolutePath);
82
+ const segments = llmdocPath.split("/");
83
+ results.push({
84
+ absolutePath,
85
+ repoPath: repoPath(rootDir, absolutePath),
86
+ llmdocPath,
87
+ topic: segments.length > 1 ? segments[0] ?? null : null,
88
+ basename: path.basename(absolutePath),
89
+ frontmatter,
90
+ body: parsed.content.trim(),
91
+ raw,
92
+ title: extractTitle(parsed.content),
93
+ links: extractLinks(parsed.content),
94
+ codeRefs: extractCodeRefs(parsed.content),
95
+ estimatedTokens: estimateTokens(parsed.content),
96
+ lineCount: raw.split(/\r?\n/).length
97
+ });
98
+ });
99
+ results.sort((left, right) => left.llmdocPath.localeCompare(right.llmdocPath));
100
+ return results;
101
+ }
102
+ function walk(currentDir, visitor) {
103
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
104
+ for (const entry of entries) {
105
+ const absolutePath = path.join(currentDir, entry.name);
106
+ if (entry.isDirectory()) {
107
+ walk(absolutePath, visitor);
108
+ }
109
+ else if (entry.isFile()) {
110
+ visitor(absolutePath);
111
+ }
112
+ }
113
+ }
114
+ function loadMeta(metaPath, preloadIssues) {
115
+ if (!fs.existsSync(metaPath)) {
116
+ return null;
117
+ }
118
+ let raw;
119
+ try {
120
+ raw = JSON.parse(fs.readFileSync(metaPath, "utf8"));
121
+ }
122
+ catch (error) {
123
+ preloadIssues.push({
124
+ severity: "error",
125
+ code: "meta.parse",
126
+ path: "llmdoc/meta.json",
127
+ message: `meta.json 解析失败: ${error.message}`
128
+ });
129
+ return null;
130
+ }
131
+ const errors = validateMeta(raw);
132
+ if (errors.length > 0) {
133
+ for (const error of errors) {
134
+ preloadIssues.push({
135
+ severity: "error",
136
+ code: "meta.invalid",
137
+ path: "llmdoc/meta.json",
138
+ message: `meta.json 非法: ${error}`
139
+ });
140
+ }
141
+ return null;
142
+ }
143
+ return raw;
144
+ }
145
+ export function validateWorkspace(workspace) {
146
+ const issues = [...workspace.preloadIssues];
147
+ const seenDocPaths = new Set();
148
+ if (!workspace.meta) {
149
+ issues.push({
150
+ severity: "error",
151
+ code: "meta.missing",
152
+ path: "llmdoc/meta.json",
153
+ message: "缺少 llmdoc/meta.json。"
154
+ });
155
+ }
156
+ for (const document of workspace.documents) {
157
+ seenDocPaths.add(document.llmdocPath);
158
+ const frontmatterErrors = validateDocFrontmatter(document.frontmatter);
159
+ for (const error of frontmatterErrors) {
160
+ issues.push({
161
+ severity: "error",
162
+ code: "frontmatter.invalid",
163
+ path: document.repoPath,
164
+ message: `front matter 非法: ${error}`
165
+ });
166
+ }
167
+ try {
168
+ const shape = parseDocTargetShape(document.repoPath);
169
+ assertDocKindMatchesShape(shape);
170
+ }
171
+ catch (error) {
172
+ issues.push({
173
+ severity: "error",
174
+ code: "doc.shape.invalid",
175
+ path: document.repoPath,
176
+ message: error.message
177
+ });
178
+ }
179
+ const depth = document.llmdocPath.split("/").length;
180
+ if (depth > 2) {
181
+ issues.push({
182
+ severity: "error",
183
+ code: "hierarchy.nested",
184
+ path: document.repoPath,
185
+ message: "topic 下不允许继续嵌套子目录。"
186
+ });
187
+ }
188
+ const mdxBodyErrors = validateMdxBody(document.body);
189
+ for (const message of mdxBodyErrors) {
190
+ issues.push({
191
+ severity: "error",
192
+ code: "mdx.syntax.forbidden",
193
+ path: document.repoPath,
194
+ message
195
+ });
196
+ }
197
+ for (const relationPath of document.frontmatter.relations?.requires ?? []) {
198
+ const normalizedRelation = validateLlmdocRelativePath(relationPath);
199
+ if (!normalizedRelation.ok) {
200
+ issues.push({
201
+ severity: "error",
202
+ code: "relations.requires.invalid-path",
203
+ path: document.repoPath,
204
+ message: normalizedRelation.message
205
+ });
206
+ }
207
+ else if (!workspace.documentsByLlmdocPath.has(normalizedRelation.value)) {
208
+ issues.push({
209
+ severity: "error",
210
+ code: "relations.requires.missing",
211
+ path: document.repoPath,
212
+ message: `requires 指向不存在的文档: ${relationPath}`
213
+ });
214
+ }
215
+ }
216
+ for (const relationPath of document.frontmatter.relations?.related ?? []) {
217
+ const normalizedRelation = validateLlmdocRelativePath(relationPath);
218
+ if (!normalizedRelation.ok) {
219
+ issues.push({
220
+ severity: "error",
221
+ code: "relations.related.invalid-path",
222
+ path: document.repoPath,
223
+ message: normalizedRelation.message
224
+ });
225
+ }
226
+ else if (!workspace.documentsByLlmdocPath.has(normalizedRelation.value)) {
227
+ issues.push({
228
+ severity: "error",
229
+ code: "relations.related.missing",
230
+ path: document.repoPath,
231
+ message: `related 指向不存在的文档: ${relationPath}`
232
+ });
233
+ }
234
+ }
235
+ for (const linkTarget of document.links) {
236
+ const resolved = resolveDocLink(document.llmdocPath, linkTarget);
237
+ const normalizedLink = validateLlmdocRelativePath(resolved);
238
+ if (!normalizedLink.ok) {
239
+ issues.push({
240
+ severity: "error",
241
+ code: "link.invalid-path",
242
+ path: document.repoPath,
243
+ message: `正文链接非法: ${linkTarget} (${normalizedLink.message})`
244
+ });
245
+ }
246
+ else if (!workspace.documentsByLlmdocPath.has(normalizedLink.value)) {
247
+ issues.push({
248
+ severity: "error",
249
+ code: "link.missing",
250
+ path: document.repoPath,
251
+ message: `正文链接悬空: ${linkTarget}`
252
+ });
253
+ }
254
+ }
255
+ for (const codeRef of document.codeRefs) {
256
+ const normalized = validateRepoPath(workspace.rootDir, codeRef.path);
257
+ if (!normalized.ok) {
258
+ issues.push({
259
+ severity: "error",
260
+ code: "coderef.path.invalid",
261
+ path: document.repoPath,
262
+ message: normalized.message
263
+ });
264
+ }
265
+ else if (!fs.existsSync(normalized.absolutePath)) {
266
+ issues.push({
267
+ severity: "error",
268
+ code: "coderef.path.missing",
269
+ path: document.repoPath,
270
+ message: `CodeRef path 不存在: ${codeRef.path}`
271
+ });
272
+ }
273
+ }
274
+ for (const codePath of document.frontmatter.code?.paths ?? []) {
275
+ const normalized = validateCodePathPattern(workspace.rootDir, codePath);
276
+ if (!normalized.ok) {
277
+ issues.push({
278
+ severity: "error",
279
+ code: "code.paths.invalid",
280
+ path: document.repoPath,
281
+ message: normalized.message
282
+ });
283
+ }
284
+ else if (!normalized.isGlob && !fs.existsSync(normalized.absolutePath)) {
285
+ issues.push({
286
+ severity: "error",
287
+ code: "code.paths.missing",
288
+ path: document.repoPath,
289
+ message: `code.paths 指向不存在的路径: ${codePath}`
290
+ });
291
+ }
292
+ }
293
+ if (document.lineCount > DOC_LINE_WARNING_LIMIT) {
294
+ issues.push({
295
+ severity: "warning",
296
+ code: "size.line-warning",
297
+ path: document.repoPath,
298
+ message: `文档 ${document.lineCount} 行,超过建议上限 ${DOC_LINE_WARNING_LIMIT} 行。`
299
+ });
300
+ }
301
+ }
302
+ for (const [topic, docs] of workspace.topics) {
303
+ if (docs.length === 0) {
304
+ issues.push({
305
+ severity: "warning",
306
+ code: "topic.empty",
307
+ path: `llmdoc/${topic}`,
308
+ message: "topic 目录为空。"
309
+ });
310
+ }
311
+ }
312
+ if (workspace.meta) {
313
+ if (!gitCommitExists(workspace.rootDir, workspace.meta.baseline.revision)) {
314
+ issues.push({
315
+ severity: "error",
316
+ code: "meta.baseline.revision.missing",
317
+ path: "llmdoc/meta.json",
318
+ message: `baseline.revision 不存在于当前 git 历史: ${workspace.meta.baseline.revision}`
319
+ });
320
+ }
321
+ const metaPaths = Object.keys(workspace.meta.documents).sort();
322
+ const docPaths = [...seenDocPaths].sort();
323
+ for (const docPath of docPaths) {
324
+ if (!(docPath in workspace.meta.documents)) {
325
+ issues.push({
326
+ severity: "error",
327
+ code: "meta.entry.missing",
328
+ path: `llmdoc/${docPath}`,
329
+ message: "meta.json 缺少对应 documents entry。"
330
+ });
331
+ }
332
+ }
333
+ for (const metaPath of metaPaths) {
334
+ if (!seenDocPaths.has(metaPath)) {
335
+ issues.push({
336
+ severity: "error",
337
+ code: "meta.entry.orphaned",
338
+ path: `llmdoc/${metaPath}`,
339
+ message: "meta.json 中存在孤儿 documents entry。"
340
+ });
341
+ }
342
+ const revision = workspace.meta.documents[metaPath]?.validatedRevision;
343
+ if (revision && !gitCommitExists(workspace.rootDir, revision)) {
344
+ issues.push({
345
+ severity: "error",
346
+ code: "meta.document.revision.missing",
347
+ path: `llmdoc/${metaPath}`,
348
+ message: `validatedRevision 不存在于当前 git 历史: ${revision}`
349
+ });
350
+ }
351
+ }
352
+ }
353
+ return issues;
354
+ }
355
+ function isGlob(input) {
356
+ return /[*?[\]{}]/.test(input);
357
+ }
358
+ function validateMdxBody(body) {
359
+ const cleanBody = stripMarkdownLiterals(body);
360
+ const issues = [];
361
+ if (/^\s*import\s+/m.test(cleanBody) || /^\s*export\s+/m.test(cleanBody)) {
362
+ issues.push("仅允许纯 Markdown 与自闭合 CodeRef,禁止 import/export。");
363
+ }
364
+ if (/<(?!CodeRef\b)[A-Za-z][^>]*>/m.test(cleanBody) || /<\/[A-Za-z][^>]*>/m.test(cleanBody)) {
365
+ issues.push("仅允许自闭合 <CodeRef ... /> 组件,禁止任意 JSX 标签。");
366
+ }
367
+ if (/\{[^}\n]+\}/m.test(cleanBody)) {
368
+ issues.push("禁止在正文中使用 MDX/JS 表达式。");
369
+ }
370
+ issues.push(...validateCodeRefTags(body));
371
+ return [...new Set(issues)];
372
+ }
373
+ function validateLlmdocRelativePath(input) {
374
+ try {
375
+ const normalized = normalizeRepoRelativePath(input);
376
+ if (!normalized.endsWith(".mdx")) {
377
+ return { ok: false, message: `路径必须指向 .mdx 文档: ${input}` };
378
+ }
379
+ if (normalized.startsWith("llmdoc/")) {
380
+ return { ok: false, message: `路径必须是 llmdoc/ 下相对路径而非仓库根路径: ${input}` };
381
+ }
382
+ return { ok: true, value: normalized };
383
+ }
384
+ catch (error) {
385
+ return { ok: false, message: error.message };
386
+ }
387
+ }
388
+ function validateRepoPath(rootDir, input) {
389
+ try {
390
+ const normalized = normalizeRepoRelativePath(input);
391
+ const absolutePath = resolveInsideRoot(rootDir, normalized);
392
+ return { ok: true, absolutePath, normalized };
393
+ }
394
+ catch (error) {
395
+ return { ok: false, message: error.message };
396
+ }
397
+ }
398
+ function validateCodePathPattern(rootDir, input) {
399
+ try {
400
+ const normalized = normalizeRepoRelativePath(input);
401
+ const glob = isGlob(normalized);
402
+ if (!glob) {
403
+ const absolutePath = resolveInsideRoot(rootDir, normalized);
404
+ return { ok: true, absolutePath, normalized, isGlob: false };
405
+ }
406
+ const staticPrefixSegments = [];
407
+ for (const segment of normalized.split("/")) {
408
+ if (isGlob(segment)) {
409
+ break;
410
+ }
411
+ staticPrefixSegments.push(segment);
412
+ }
413
+ const staticPrefix = staticPrefixSegments.join("/");
414
+ const prefix = staticPrefix || ".";
415
+ const absolutePath = prefix === "." ? rootDir : resolveInsideRoot(rootDir, prefix);
416
+ return { ok: true, absolutePath, normalized, isGlob: true };
417
+ }
418
+ catch (error) {
419
+ return { ok: false, message: error.message };
420
+ }
421
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@tokenroll/llmdoc",
3
+ "version": "3.0.0",
4
+ "description": "V3 runtime CLI for llmdoc repositories",
5
+ "homepage": "https://github.com/TokenRollAI/llmdoc",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/TokenRollAI/llmdoc.git"
9
+ },
10
+ "author": "DJJ & Danniel",
11
+ "type": "module",
12
+ "bin": {
13
+ "llmdoc": "./dist/bin/llmdoc.js"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "schemas",
24
+ "templates",
25
+ "assets"
26
+ ],
27
+ "scripts": {
28
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json && node -e \"require('node:fs').chmodSync('dist/bin/llmdoc.js', 0o755)\"",
29
+ "prepack": "npm run build",
30
+ "lint": "eslint src tests",
31
+ "test": "npm run build && vitest run",
32
+ "typecheck": "tsc -p tsconfig.typecheck.json --noEmit"
33
+ },
34
+ "dependencies": {
35
+ "ajv": "^8.17.1",
36
+ "commander": "^13.1.0",
37
+ "gray-matter": "^4.0.3",
38
+ "marked": "^15.0.12",
39
+ "minimatch": "^9.0.5"
40
+ },
41
+ "devDependencies": {
42
+ "@eslint/js": "9.39.5",
43
+ "@types/node": "^24.3.0",
44
+ "eslint": "9.39.5",
45
+ "typescript": "^5.9.2",
46
+ "typescript-eslint": "8.46.4",
47
+ "vite": "6.4.3",
48
+ "vitest": "3.2.7"
49
+ }
50
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://llmdoc.dev/schemas/doc-frontmatter.schema.json",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": ["description", "kind"],
7
+ "properties": {
8
+ "description": {
9
+ "type": "string",
10
+ "minLength": 1
11
+ },
12
+ "kind": {
13
+ "type": "string",
14
+ "enum": ["architecture", "guide", "reference"]
15
+ },
16
+ "relations": {
17
+ "type": "object",
18
+ "additionalProperties": false,
19
+ "properties": {
20
+ "requires": {
21
+ "$ref": "#/$defs/pathArray"
22
+ },
23
+ "related": {
24
+ "$ref": "#/$defs/pathArray"
25
+ }
26
+ }
27
+ },
28
+ "code": {
29
+ "type": "object",
30
+ "additionalProperties": false,
31
+ "properties": {
32
+ "paths": {
33
+ "$ref": "#/$defs/pathArray"
34
+ }
35
+ }
36
+ }
37
+ },
38
+ "$defs": {
39
+ "pathArray": {
40
+ "type": "array",
41
+ "items": {
42
+ "type": "string",
43
+ "minLength": 1
44
+ },
45
+ "uniqueItems": true
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,65 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://llmdoc.dev/schemas/meta.schema.json",
4
+ "type": "object",
5
+ "additionalProperties": false,
6
+ "required": ["schema", "baseline", "documents", "convergence"],
7
+ "properties": {
8
+ "schema": {
9
+ "type": "string",
10
+ "const": "llmdoc.meta/v3"
11
+ },
12
+ "baseline": {
13
+ "type": "object",
14
+ "additionalProperties": false,
15
+ "required": ["revision", "verifiedAt"],
16
+ "properties": {
17
+ "revision": {
18
+ "type": "string",
19
+ "minLength": 1
20
+ },
21
+ "verifiedAt": {
22
+ "type": "string",
23
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$"
24
+ }
25
+ }
26
+ },
27
+ "documents": {
28
+ "type": "object",
29
+ "additionalProperties": {
30
+ "type": "object",
31
+ "additionalProperties": false,
32
+ "required": ["validatedRevision"],
33
+ "properties": {
34
+ "validatedRevision": {
35
+ "type": ["string", "null"],
36
+ "minLength": 1
37
+ }
38
+ }
39
+ }
40
+ },
41
+ "convergence": {
42
+ "type": "object",
43
+ "additionalProperties": false,
44
+ "required": ["capturedAt", "source", "documentCount", "totalEstimatedTokens"],
45
+ "properties": {
46
+ "capturedAt": {
47
+ "type": "string",
48
+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z$"
49
+ },
50
+ "source": {
51
+ "type": "string",
52
+ "enum": ["init", "prune"]
53
+ },
54
+ "documentCount": {
55
+ "type": "integer",
56
+ "minimum": 0
57
+ },
58
+ "totalEstimatedTokens": {
59
+ "type": "integer",
60
+ "minimum": 0
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }