Repository navigation
Expand file tree
/
Copy pathbuild-llms.mjs
More file actions
210 lines (188 loc) · 6.89 KB
/
Copy pathbuild-llms.mjs
File metadata and controls
210 lines (188 loc) · 6.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env node
/**
* Build the llms.txt documentation files.
*
* Three files, one source of truth:
*
* - `docs/static/llms.txt` — hand-written, concise. **The source.** Not
* generated by this script; it only copies it.
* - `packages/core/llms.txt` — a copy of the above, shipped to npm so an
* agent can read the API of the exact version
* it has installed, out of `node_modules`,
* rather than guessing from a hosted page that
* describes a different release.
* - `docs/static/llms-full.txt` — generated from every page in `docs/docs`, in
* sidebar order.
*
* Impulse publishes one package, so unlike `inertia`'s version of this script
* there is no per-adapter slice. Add one here if that ever changes.
*
* Run with `pnpm run build:llms`, and re-run after editing any page or
* changing the public API.
*
* `--check` writes nothing and exits non-zero when a generated file is not
* what this script would produce. That is the CI guard, and it lives here
* rather than in a second script so the check and the build cannot disagree
* about what "correct" means.
*/
import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const repoRoot = resolve(here, '..')
const docsDir = join(repoRoot, 'docs')
const docsContentDir = join(docsDir, 'docs')
const staticDir = join(docsDir, 'static')
const corePkgDir = join(repoRoot, 'packages', 'core')
// Page order comes from docs/sidebars.ts, so the rendered site and this file
// cannot drift. The sidebar is TypeScript and this repo supports Node 20, so
// it is read as text rather than imported. Every quoted string that is not a
// `type`, `label`, or import specifier is a doc id.
const sidebarsPath = join(docsDir, 'sidebars.ts')
function readSidebarDocIds(source) {
const body = source
.split('\n')
.filter((line) => !line.trimStart().startsWith('import '))
.join('\n')
.replace(/\b(type|label)\s*:\s*(['"])(?:(?!\2).)*\2/g, '')
const ids = []
for (const match of body.matchAll(/(['"])((?:(?!\1).)+)\1/g)) {
ids.push(match[2])
}
if (ids.length === 0) {
throw new Error(`[build-llms] no doc ids found in ${sidebarsPath}`)
}
return ids
}
const PAGES = readSidebarDocIds(readFileSync(sidebarsPath, 'utf8'))
/** Strip the leading YAML frontmatter block from a markdown page. */
function stripFrontmatter(md) {
if (!md.startsWith('---')) return md
const end = md.indexOf('\n---', 3)
if (end === -1) return md
const after = md.indexOf('\n', end + 4)
return after === -1 ? '' : md.slice(after + 1)
}
/** Drop the `import` block an MDX page may carry, so the output is prose. */
function stripMdxImports(md) {
const lines = md.split('\n')
let i = 0
while (i < lines.length) {
const line = lines[i]
if (line.startsWith('import ') || line.trim() === '') {
i++
continue
}
break
}
return lines.slice(i).join('\n')
}
/**
* Turn Docusaurus admonitions into plain markdown.
*
* These pages lean on `:::danger` and `:::warning` for the things that fail
* silently, and those are exactly the parts an agent reading this file most
* needs. Left as `:::` fences they are noise; as a bold label and a blockquote
* they survive as emphasis in any plain-text reader.
*/
function expandAdmonitions(md) {
return md.replace(
/^:::(note|tip|info|warning|danger|caution)(?:[ \t]+([^\n]*))?\n([\s\S]*?)^:::[ \t]*$/gm,
(_match, kind, title, body) => {
const label = title?.trim()
? `${kind.toUpperCase()} — ${title.trim()}`
: kind.toUpperCase()
const quoted = body
.replace(/^\s*\n/, '')
.trimEnd()
.split('\n')
.map((line) => (line.trim() === '' ? '>' : `> ${line}`))
.join('\n')
return `> **${label}**\n>\n${quoted}`
},
)
}
function resolveDocPath(id) {
const mdx = join(docsContentDir, `${id}.mdx`)
if (existsSync(mdx)) return mdx
const md = join(docsContentDir, `${id}.md`)
if (existsSync(md)) return md
throw new Error(
`[build-llms] no page for id "${id}" — looked for ${id}.mdx and ${id}.md ` +
`in ${docsContentDir}. Every id in docs/sidebars.ts needs a file.`,
)
}
function renderPage(id) {
const raw = readFileSync(resolveDocPath(id), 'utf8')
return expandAdmonitions(stripMdxImports(stripFrontmatter(raw))).trimEnd()
}
function buildLlmsFull() {
const header = [
'# Impulse — full documentation',
'',
'> Every documentation page, in sidebar order. scripts/build-llms.mjs builds',
"> this file from docs/docs. Don't edit it by hand.",
'',
'> Source: https://github.com/rootnative/impulse',
'> Site: https://rootnative.github.io/impulse/',
'',
'---',
'',
].join('\n')
return header + PAGES.map(renderPage).join('\n\n---\n\n') + '\n'
}
const llmsTxtPath = join(staticDir, 'llms.txt')
const llmsFullPath = join(staticDir, 'llms-full.txt')
const corePackageLlmsPath = join(corePkgDir, 'llms.txt')
const checkOnly = process.argv.includes('--check')
if (!existsSync(llmsTxtPath)) {
throw new Error(
`[build-llms] ${llmsTxtPath} is missing. You write it by hand, and ` +
`this script only copies it into the package.`,
)
}
const label = checkOnly ? 'check-llms' : 'build-llms'
console.log(`[${label}] ${PAGES.length} pages: ${PAGES.join(', ')}`)
const outputs = [
{
rel: 'docs/static/llms-full.txt',
path: llmsFullPath,
build: buildLlmsFull,
},
{
rel: 'packages/core/llms.txt',
path: corePackageLlmsPath,
build: () => readFileSync(llmsTxtPath, 'utf8'),
},
]
if (checkOnly) {
const problems = []
for (const output of outputs) {
if (!existsSync(output.path)) {
problems.push(`${output.rel} is missing`)
} else if (readFileSync(output.path, 'utf8') !== output.build()) {
problems.push(`${output.rel} is out of date`)
}
}
if (problems.length > 0) {
console.error(`\n[check-llms] ${problems.length} problem(s):`)
for (const problem of problems) {
console.error(` ERROR ${problem}`)
}
console.error(
'\nRun `pnpm run build:llms` and commit the result. These files are ' +
'generated from docs/docs and docs/static/llms.txt, so a page edit ' +
'without a regenerate leaves them describing the previous version.\n',
)
process.exit(1)
}
console.log('[check-llms] ok — the generated files match the pages.')
} else {
console.log('[build-llms] writing docs/static/llms-full.txt …')
writeFileSync(llmsFullPath, buildLlmsFull())
console.log(
'[build-llms] copying docs/static/llms.txt → packages/core/llms.txt',
)
copyFileSync(llmsTxtPath, corePackageLlmsPath)
console.log('[build-llms] done.')
}