@writedocs/generator 0.10.18 → 0.10.20

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.
package/src/lib/pages.js CHANGED
@@ -1,291 +1,312 @@
1
- // Which files in a content directory are pages. Plain JavaScript, not
2
- // TypeScript, so `writedocs validate` can load it with plain Node (Node
3
- // refuses to strip types under node_modules - see lib/icons.js's comment);
4
- // lib/config.ts re-exports findAllPages() for everything inside Astro.
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import matter from 'gray-matter';
8
- import { readConfigText } from './config-file.js';
9
-
10
- // Top-level folders of a content directory that are never scanned for
11
- // pages - build output, dependencies, and static assets. Any folder whose
12
- // name starts with a dot (.git, .github, .claude, .mintlify, ...) is
13
- // skipped too, at any depth - see findAllPages().
14
- export const EXCLUDED_TOP_LEVEL_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
15
-
16
- /** A page's title when its frontmatter has none - Mintlify's rule, so a
17
- * migrated page that relied on it keeps the same title: the file name
18
- * without its extension, dashes and underscores as spaces, first letter
19
- * capitalized. `guides/getting-started.mdx` -> "Getting started". A
20
- * folder's index page is named for the folder (`api/index.mdx` -> "Api"),
21
- * and the site's own index.mdx is "Home" - "Index" names neither. */
22
- export function titleFromPath(filePath) {
23
- const parts = String(filePath).split(/[\\/]/).filter(Boolean);
24
- let base = (parts.pop() ?? '').replace(/\.mdx?$/i, '');
25
- if (base.toLowerCase() === 'index') {
26
- if (parts.length === 0) return 'Home';
27
- base = parts.pop();
28
- }
29
- const words = base.replace(/[-_]+/g, ' ').trim();
30
- return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'Untitled';
31
- }
32
-
33
- /** Mintlify's .mintignore, if the content directory has one: gitignore-
34
- * style patterns for files and folders that aren't published. Supports
35
- * comments, blank lines, `*`, `**`, `?`, a leading `/` (anchored to the
36
- * content directory) and a trailing `/` (folders only); negation (`!`)
37
- * isn't supported and such lines are skipped. Returns (relPath, isDir) =>
38
- * boolean. */
39
- function readIgnoreFile(contentDir) {
40
- let text;
41
- try {
42
- text = fs.readFileSync(path.join(contentDir, '.mintignore'), 'utf-8');
43
- } catch {
44
- return () => false;
45
- }
46
- const rules = text
47
- .split(/\r?\n/)
48
- .map((l) => l.trim())
49
- .filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
50
- .map((pattern) => {
51
- const dirOnly = pattern.endsWith('/');
52
- let p = pattern.replace(/\/+$/, '');
53
- const anchored = p.startsWith('/') || p.includes('/');
54
- p = p.replace(/^\/+/, '');
55
- const source = p
56
- .split(/(\*\*\/?|\*|\?)/)
57
- .map((part) =>
58
- part === '**/' || part === '**' ? '(?:.*/)?' : part === '*' ? '[^/]*' : part === '?' ? '[^/]' : part.replace(/[.+^${}()|[\]\\]/g, '\\$&')
59
- )
60
- .join('');
61
- const re = new RegExp(anchored ? `^${source}$` : `(?:^|/)${source}$`);
62
- return { re, dirOnly };
63
- });
64
- return (rel, isDir) => rules.some((r) => (!r.dirOnly || isDir) && r.re.test(rel));
65
- }
66
-
67
- /** Page ids writedocs.json's navigation lists (strings in arrays, and
68
- * groups' `page`) - read straight from the file, since this runs before
69
- * (and independently of) config validation. Empty when there's no
70
- * readable writedocs.json. */
71
- /** The page id a navigation entry names. "guides/index" and "guides" are
72
- * the same page: a folder's index.mdx has the folder's id (fileIdForPath()
73
- * below), and Mintlify projects write it either way. The root "index"
74
- * stays as it is. */
75
- export function navPageId(id) {
76
- return id.endsWith('/index') ? id.slice(0, -'/index'.length) : id;
77
- }
78
-
79
- /** Every page id a `navigation` lists, in the order a reader meets them -
80
- * top to bottom, each group's own `page` before its `pages` - without
81
- * repeats. */
82
- export function navigationPageOrder(navigation) {
83
- const ids = new Set();
84
- (function walk(node) {
85
- if (Array.isArray(node)) node.forEach((item) => (typeof item === 'string' ? ids.add(navPageId(item)) : walk(item)));
86
- else if (node && typeof node === 'object') {
87
- if (typeof node.page === 'string') ids.add(navPageId(node.page));
88
- for (const [key, value] of Object.entries(node)) {
89
- if (key !== 'page' && key !== 'openapi' && key !== 'href') walk(value);
90
- }
91
- }
92
- })(navigation);
93
- return [...ids];
94
- }
95
-
96
- function navigationPageIds(contentDir) {
97
- let config;
98
- try {
99
- config = JSON.parse(readConfigText(contentDir));
100
- } catch {
101
- return new Set();
102
- }
103
- return new Set(navigationPageOrder(config.navigation));
104
- }
105
-
106
- /** Recursively finds every .md/.mdx file under `contentDir` that is a page:
107
- * one with a frontmatter block, or one writedocs.json's navigation lists
108
- * (a Mintlify page needs no frontmatter at all - see titleFromPath()).
109
- * Skips EXCLUDED_TOP_LEVEL_DIRS, every dot-folder at any depth, and
110
- * anything a .mintignore file lists. docs/ is scanned exactly like any
111
- * other folder, no special-casing. Returns POSIX-relative paths (from
112
- * `contentDir`) suitable to hand straight to Astro's `glob()` loader as a
113
- * literal `pattern` array - see content.config.ts's `pages` collection,
114
- * and [...slug].astro, which needs the identical list to decide whether
115
- * calling `getCollection('pages')` is worth doing at all. Also reused by
116
- * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
117
- * all of them see exactly the same file set. Synchronous and re-run from
118
- * scratch wherever it's called - cheap enough for a docs site's file
119
- * count. */
120
- export function findAllPages(contentDir) {
121
- const results = [];
122
- const ignored = readIgnoreFile(contentDir);
123
- const listed = navigationPageIds(contentDir);
124
- function walk(dir, relBase) {
125
- let entries;
126
- try {
127
- entries = fs.readdirSync(dir, { withFileTypes: true });
128
- } catch {
129
- return;
130
- }
131
- for (const entry of entries) {
132
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
133
- const abs = path.join(dir, entry.name);
134
- if (entry.isDirectory()) {
135
- if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
136
- if (entry.name.startsWith('.')) continue;
137
- if (ignored(rel, true)) continue;
138
- walk(abs, rel);
139
- continue;
140
- }
141
- if (!entry.isFile() || !/\.mdx?$/i.test(entry.name)) continue;
142
- if (ignored(rel, false)) continue;
143
- let raw;
144
- try {
145
- raw = fs.readFileSync(abs, 'utf-8');
146
- } catch {
147
- continue;
148
- }
149
- let data;
150
- try {
151
- ({ data } = matter(raw));
152
- } catch {
153
- // Frontmatter that isn't valid YAML: still a page (it opens a
154
- // frontmatter block), so the error surfaces with this file's name -
155
- // from `writedocs validate`, or Astro's own loader in the build -
156
- // instead of as a bare YAML error thrown from here.
157
- if (/^---\r?\n/.test(raw)) results.push(rel);
158
- continue;
159
- }
160
- if (Object.keys(data).length === 0 && !listed.has(fileIdForPath(rel))) continue; // not a page
161
- results.push(rel);
162
- }
163
- }
164
- walk(contentDir, '');
165
- return results;
166
- }
167
-
168
- /** The id writedocs.json's navigation refers to a page by: its path from
169
- * the content directory, without the extension or a trailing `/index`
170
- * (same algorithm as fileIdForEntry() in lib/config.ts). */
171
- export function fileIdForPath(relativePath) {
172
- return relativePath.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
173
- }
174
-
175
- /** Any `.css`/`.js` file anywhere in the project - root or any subfolder,
176
- * `public/` included - auto-loaded site-wide with zero `writedocs.json`
177
- * config, on top of (not instead of) the explicit `scripts` field
178
- * (bannerSchema and friends, above). Drop a file in, it loads;
179
- * there's no field naming which ones to use, matching the same "just
180
- * works" convention `docs/`'s own file discovery already follows (see
181
- * findAllPages() above / `content-pipeline.mdx`) - a site author already
182
- * drops content files in and expects them found, rather than also
183
- * listing every one in writedocs.json.
184
- *
185
- * Two separate walks, because `public/` needs different treatment than
186
- * everywhere else:
187
- *
188
- * - `css`/`js`: every `.css`/`.js` file outside `public/` (root, `docs/`,
189
- * `snippets/`, any custom folder) - reused as the walk-with-exclusions
190
- * shape from findAllPages() above, and its exact `EXCLUDED_TOP_LEVEL_DIRS`
191
- * set (skipped only at the project root, same as there), so `dist/`,
192
- * `node_modules/`, `.astro/`, `.writedocs/`, `.git/`, and (for this
193
- * half only - see below) `public/` are never walked into. BaseLayout.astro
194
- * reads each one's raw content and inlines it as a `<style>`/
195
- * `<script is:inline>` tag.
196
- * - `publicCss`/`publicJs`: every `.css`/`.js` file *inside* `public/`,
197
- * walked separately (starting from `<contentDir>/public` rather than
198
- * `contentDir` itself, so the same `EXCLUDED_TOP_LEVEL_DIRS` check
199
- * doesn't apply here - there's no `public/public/` or `public/dist/`
200
- * convention to guard against). Returned as public-URL-rooted hrefs
201
- * (a leading `/`, no `public` segment - `public/custom.css` becomes
202
- * `/custom.css`) rather than content-dir-relative paths, since these
203
- * files are already served as static assets at exactly that URL once
204
- * Astro copies `public/` into the build output. BaseLayout.astro
205
- * renders these as ordinary `<link rel="stylesheet">`/`<script src>`
206
- * tags pointing at that URL instead of inlining their content -
207
- * inlining would duplicate every byte (once in the page's own HTML,
208
- * once more as the independently-fetchable static file at that same
209
- * URL) for no benefit, where a `<link>`/`<script src>` gets normal
210
- * browser caching across pages instead of repeating the content on
211
- * every single page's markup.
212
- *
213
- * Both halves are broader than they might sound - a stray `.js` file
214
- * kept in `docs/`, `snippets/`, or `public/` for an unrelated reason
215
- * (a snippet's own local helper, an image gallery's lightbox script
216
- * someone dropped in `public/` to reference from a raw `<script src>`
217
- * in an .mdx file, say) gets auto-injected sitewide the same as a
218
- * deliberate one; there's no separate "this one's just tooling" signal
219
- * to opt out of the convention short of renaming its extension.
220
- *
221
- * Both `css`/`js` and `publicCss`/`publicJs` are sorted alphabetically
222
- * by their respective path for deterministic load order across rebuilds
223
- * - filesystem readdir order isn't guaranteed portable across OSes or
224
- * directory-walk order otherwise.
225
- *
226
- * `css`/`js` return POSIX-separated paths relative to `contentDir`, not
227
- * absolute paths or file contents - BaseLayout.astro (the sole caller)
228
- * resolves and reads each one's content itself, right before inlining
229
- * it, so a file's content is always current as of that specific
230
- * request/build rather than cached here across a `writedocs dev`
231
- * session. `publicCss`/`publicJs` return the public-URL hrefs described
232
- * above - nothing to read, Astro's own static-file serving/copy already
233
- * handles those. */
234
- export function findRootAssets(contentDir) {
235
- const css = [];
236
- const js = [];
237
- function walk(dir, relBase) {
238
- let entries;
239
- try {
240
- entries = fs.readdirSync(dir, { withFileTypes: true });
241
- } catch {
242
- return;
243
- }
244
- for (const entry of entries) {
245
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
246
- const abs = path.join(dir, entry.name);
247
- if (entry.isDirectory()) {
248
- if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
249
- // Dot-folders (.github, .claude, .husky, .vscode, ...) hold tooling,
250
- // never site assets - the same rule findAllPages() applies to pages.
251
- // Without it, a CI script under .github/ ran on every page.
252
- if (entry.name.startsWith('.')) continue;
253
- walk(abs, rel);
254
- continue;
255
- }
256
- if (!entry.isFile() || entry.name.startsWith('.')) continue; // .eslintrc.js and friends
257
- if (/\.css$/i.test(entry.name)) css.push(rel);
258
- else if (/\.js$/i.test(entry.name)) js.push(rel);
259
- }
260
- }
261
- walk(contentDir, '');
262
- css.sort();
263
- js.sort();
264
-
265
- const publicCss = [];
266
- const publicJs = [];
267
- function walkPublic(dir, relBase) {
268
- let entries;
269
- try {
270
- entries = fs.readdirSync(dir, { withFileTypes: true });
271
- } catch {
272
- return;
273
- }
274
- for (const entry of entries) {
275
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
276
- const abs = path.join(dir, entry.name);
277
- if (entry.isDirectory()) {
278
- walkPublic(abs, rel);
279
- continue;
280
- }
281
- if (!entry.isFile()) continue;
282
- if (/\.css$/i.test(entry.name)) publicCss.push(`/${rel}`);
283
- else if (/\.js$/i.test(entry.name)) publicJs.push(`/${rel}`);
284
- }
285
- }
286
- walkPublic(path.join(contentDir, 'public'), '');
287
- publicCss.sort();
288
- publicJs.sort();
289
-
290
- return { css, js, publicCss, publicJs };
291
- }
1
+ // Which files in a content directory are pages. Plain JavaScript, not
2
+ // TypeScript, so `writedocs validate` can load it with plain Node (Node
3
+ // refuses to strip types under node_modules - see lib/icons.js's comment);
4
+ // lib/config.ts re-exports findAllPages() for everything inside Astro.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import matter from 'gray-matter';
8
+ import { readConfigText } from './config-file.js';
9
+ import { oncePerBuild } from './build-memo.js';
10
+ import { projectIgnore } from './project-ignore.js';
11
+
12
+ // Top-level folders of a content directory that are never scanned for
13
+ // pages - build output, dependencies, and static assets. Any folder whose
14
+ // name starts with a dot (.git, .github, .claude, .mintlify, ...) is
15
+ // skipped too, at any depth - see findAllPages().
16
+ export const EXCLUDED_TOP_LEVEL_DIRS = new Set(['node_modules', 'dist', '.astro', '.writedocs', 'public', '.git']);
17
+
18
+ /** A page's title when its frontmatter has none - Mintlify's rule, so a
19
+ * migrated page that relied on it keeps the same title: the file name
20
+ * without its extension, dashes and underscores as spaces, first letter
21
+ * capitalized. `guides/getting-started.mdx` -> "Getting started". A
22
+ * folder's index page is named for the folder (`api/index.mdx` -> "Api"),
23
+ * and the site's own index.mdx is "Home" - "Index" names neither. */
24
+ export function titleFromPath(filePath) {
25
+ const parts = String(filePath).split(/[\\/]/).filter(Boolean);
26
+ let base = (parts.pop() ?? '').replace(/\.mdx?$/i, '');
27
+ if (base.toLowerCase() === 'index') {
28
+ if (parts.length === 0) return 'Home';
29
+ base = parts.pop();
30
+ }
31
+ const words = base.replace(/[-_]+/g, ' ').trim();
32
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'Untitled';
33
+ }
34
+
35
+ /** Mintlify's .mintignore, if the content directory has one: gitignore-
36
+ * style patterns for files and folders that aren't published. Supports
37
+ * comments, blank lines, `*`, `**`, `?`, a leading `/` (anchored to the
38
+ * content directory) and a trailing `/` (folders only); negation (`!`)
39
+ * isn't supported and such lines are skipped. Returns (relPath, isDir) =>
40
+ * boolean. */
41
+ function readIgnoreFile(contentDir) {
42
+ let text;
43
+ try {
44
+ text = fs.readFileSync(path.join(contentDir, '.mintignore'), 'utf-8');
45
+ } catch {
46
+ return () => false;
47
+ }
48
+ const rules = text
49
+ .split(/\r?\n/)
50
+ .map((l) => l.trim())
51
+ .filter((l) => l && !l.startsWith('#') && !l.startsWith('!'))
52
+ .map((pattern) => {
53
+ const dirOnly = pattern.endsWith('/');
54
+ let p = pattern.replace(/\/+$/, '');
55
+ const anchored = p.startsWith('/') || p.includes('/');
56
+ p = p.replace(/^\/+/, '');
57
+ const source = p
58
+ .split(/(\*\*\/?|\*|\?)/)
59
+ .map((part) =>
60
+ part === '**/' || part === '**' ? '(?:.*/)?' : part === '*' ? '[^/]*' : part === '?' ? '[^/]' : part.replace(/[.+^${}()|[\]\\]/g, '\\$&')
61
+ )
62
+ .join('');
63
+ const re = new RegExp(anchored ? `^${source}$` : `(?:^|/)${source}$`);
64
+ return { re, dirOnly };
65
+ });
66
+ return (rel, isDir) => rules.some((r) => (!r.dirOnly || isDir) && r.re.test(rel));
67
+ }
68
+
69
+ /** Page ids writedocs.json's navigation lists (strings in arrays, and
70
+ * groups' `page`) - read straight from the file, since this runs before
71
+ * (and independently of) config validation. Empty when there's no
72
+ * readable writedocs.json. */
73
+ /** The page id a navigation entry names. "guides/index" and "guides" are
74
+ * the same page: a folder's index.mdx has the folder's id (fileIdForPath()
75
+ * below), and Mintlify projects write it either way. The root "index"
76
+ * stays as it is. */
77
+ export function navPageId(id) {
78
+ return id.endsWith('/index') ? id.slice(0, -'/index'.length) : id;
79
+ }
80
+
81
+ /** Every page id a `navigation` lists, in the order a reader meets them -
82
+ * top to bottom, each group's own `page` before its `pages` - without
83
+ * repeats. */
84
+ export function navigationPageOrder(navigation) {
85
+ const ids = new Set();
86
+ (function walk(node) {
87
+ if (Array.isArray(node)) node.forEach((item) => (typeof item === 'string' ? ids.add(navPageId(item)) : walk(item)));
88
+ else if (node && typeof node === 'object') {
89
+ if (typeof node.page === 'string') ids.add(navPageId(node.page));
90
+ for (const [key, value] of Object.entries(node)) {
91
+ if (key !== 'page' && key !== 'openapi' && key !== 'href') walk(value);
92
+ }
93
+ }
94
+ })(navigation);
95
+ return [...ids];
96
+ }
97
+
98
+ function navigationPageIds(contentDir) {
99
+ let config;
100
+ try {
101
+ config = JSON.parse(readConfigText(contentDir));
102
+ } catch {
103
+ return new Set();
104
+ }
105
+ return new Set(navigationPageOrder(config.navigation));
106
+ }
107
+
108
+ /** Recursively finds every .md/.mdx file under `contentDir` that is a page:
109
+ * one with a frontmatter block, or one writedocs.json's navigation lists
110
+ * (a Mintlify page needs no frontmatter at all - see titleFromPath()).
111
+ * Skips EXCLUDED_TOP_LEVEL_DIRS, every dot-folder at any depth, whatever
112
+ * the project's ignore rules leave out (lib/wdignore.js: the default
113
+ * exclusions and its `.wdignore`) and anything a .mintignore file lists. docs/ is scanned exactly like any
114
+ * other folder, no special-casing. Returns POSIX-relative paths (from
115
+ * `contentDir`) suitable to hand straight to Astro's `glob()` loader as a
116
+ * literal `pattern` array - see content.config.ts's `pages` collection,
117
+ * and [...slug].astro, which needs the identical list to decide whether
118
+ * calling `getCollection('pages')` is worth doing at all. Also reused by
119
+ * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
120
+ * all of them see exactly the same file set. Synchronous. In a build the
121
+ * project is scanned once and every later call gets that list
122
+ * (lib/build-memo.js) - a page that scanned it again made the build N x N;
123
+ * everywhere else (`writedocs dev`, `validate`) every call scans afresh,
124
+ * so a page added or removed is seen. */
125
+ export function findAllPages(contentDir) {
126
+ // A copy, so a caller that changes its list doesn't change everyone's.
127
+ return oncePerBuild(`pages:${contentDir}`, () => scanAllPages(contentDir)).slice();
128
+ }
129
+
130
+ function scanAllPages(contentDir) {
131
+ const results = [];
132
+ const ignored = readIgnoreFile(contentDir);
133
+ const rules = projectIgnore(contentDir);
134
+ const listed = navigationPageIds(contentDir);
135
+ function walk(dir, relBase) {
136
+ let entries;
137
+ try {
138
+ entries = fs.readdirSync(dir, { withFileTypes: true });
139
+ } catch {
140
+ return;
141
+ }
142
+ for (const entry of entries) {
143
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
144
+ const abs = path.join(dir, entry.name);
145
+ if (entry.isDirectory()) {
146
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
147
+ if (entry.name.startsWith('.')) continue;
148
+ if (ignored(rel, true) || rules.ignores(rel, true)) continue;
149
+ walk(abs, rel);
150
+ continue;
151
+ }
152
+ if (!entry.isFile() || !/\.mdx?$/i.test(entry.name)) continue;
153
+ if (ignored(rel, false) || rules.ignores(rel)) continue;
154
+ let raw;
155
+ try {
156
+ raw = fs.readFileSync(abs, 'utf-8');
157
+ } catch {
158
+ continue;
159
+ }
160
+ let data;
161
+ try {
162
+ ({ data } = matter(raw));
163
+ } catch {
164
+ // Frontmatter that isn't valid YAML: still a page (it opens a
165
+ // frontmatter block), so the error surfaces with this file's name -
166
+ // from `writedocs validate`, or Astro's own loader in the build -
167
+ // instead of as a bare YAML error thrown from here.
168
+ if (/^---\r?\n/.test(raw)) results.push(rel);
169
+ continue;
170
+ }
171
+ if (Object.keys(data).length === 0 && !listed.has(fileIdForPath(rel))) continue; // not a page
172
+ results.push(rel);
173
+ }
174
+ }
175
+ walk(contentDir, '');
176
+ return results;
177
+ }
178
+
179
+ /** The id writedocs.json's navigation refers to a page by: its path from
180
+ * the content directory, without the extension or a trailing `/index`
181
+ * (same algorithm as fileIdForEntry() in lib/config.ts). */
182
+ export function fileIdForPath(relativePath) {
183
+ return relativePath.replace(/\.mdx?$/i, '').replace(/\/index$/, '');
184
+ }
185
+
186
+ /** Any `.css`/`.js` file anywhere in the project - root or any subfolder,
187
+ * `public/` included - auto-loaded site-wide with zero `writedocs.json`
188
+ * config, on top of (not instead of) the explicit `scripts` field
189
+ * (bannerSchema and friends, above). Drop a file in, it loads;
190
+ * there's no field naming which ones to use, matching the same "just
191
+ * works" convention `docs/`'s own file discovery already follows (see
192
+ * findAllPages() above / `content-pipeline.mdx`) - a site author already
193
+ * drops content files in and expects them found, rather than also
194
+ * listing every one in writedocs.json.
195
+ *
196
+ * Two separate walks, because `public/` needs different treatment than
197
+ * everywhere else:
198
+ *
199
+ * - `css`/`js`: every `.css`/`.js` file outside `public/` (root, `docs/`,
200
+ * `snippets/`, any custom folder) - reused as the walk-with-exclusions
201
+ * shape from findAllPages() above, and its exact `EXCLUDED_TOP_LEVEL_DIRS`
202
+ * set (skipped only at the project root, same as there), so `dist/`,
203
+ * `node_modules/`, `.astro/`, `.writedocs/`, `.git/`, and (for this
204
+ * half only - see below) `public/` are never walked into. BaseLayout.astro
205
+ * reads each one's raw content and inlines it as a `<style>`/
206
+ * `<script is:inline>` tag.
207
+ * - `publicCss`/`publicJs`: every `.css`/`.js` file *inside* `public/`,
208
+ * walked separately (starting from `<contentDir>/public` rather than
209
+ * `contentDir` itself, so the same `EXCLUDED_TOP_LEVEL_DIRS` check
210
+ * doesn't apply here - there's no `public/public/` or `public/dist/`
211
+ * convention to guard against). Returned as public-URL-rooted hrefs
212
+ * (a leading `/`, no `public` segment - `public/custom.css` becomes
213
+ * `/custom.css`) rather than content-dir-relative paths, since these
214
+ * files are already served as static assets at exactly that URL once
215
+ * Astro copies `public/` into the build output. BaseLayout.astro
216
+ * renders these as ordinary `<link rel="stylesheet">`/`<script src>`
217
+ * tags pointing at that URL instead of inlining their content -
218
+ * inlining would duplicate every byte (once in the page's own HTML,
219
+ * once more as the independently-fetchable static file at that same
220
+ * URL) for no benefit, where a `<link>`/`<script src>` gets normal
221
+ * browser caching across pages instead of repeating the content on
222
+ * every single page's markup.
223
+ *
224
+ * Both halves are broader than they might sound - a stray `.js` file
225
+ * kept in `docs/`, `snippets/`, or `public/` for an unrelated reason
226
+ * (a snippet's own local helper, an image gallery's lightbox script
227
+ * someone dropped in `public/` to reference from a raw `<script src>`
228
+ * in an .mdx file, say) gets auto-injected sitewide the same as a
229
+ * deliberate one; there's no separate "this one's just tooling" signal
230
+ * to opt out of the convention short of renaming its extension.
231
+ *
232
+ * Both `css`/`js` and `publicCss`/`publicJs` are sorted alphabetically
233
+ * by their respective path for deterministic load order across rebuilds
234
+ * - filesystem readdir order isn't guaranteed portable across OSes or
235
+ * directory-walk order otherwise.
236
+ *
237
+ * `css`/`js` return POSIX-separated paths relative to `contentDir`, not
238
+ * absolute paths or file contents - BaseLayout.astro (the sole caller)
239
+ * resolves and reads each one's content itself, right before inlining
240
+ * it, so a file's content is always current as of that specific
241
+ * request/build rather than cached here across a `writedocs dev`
242
+ * session. `publicCss`/`publicJs` return the public-URL hrefs described
243
+ * above - nothing to read, Astro's own static-file serving/copy already
244
+ * handles those. */
245
+ export function findRootAssets(contentDir) {
246
+ // Once per build (lib/build-memo.js); on every call in `writedocs dev`.
247
+ return oncePerBuild(`root-assets:${contentDir}`, () => scanRootAssets(contentDir));
248
+ }
249
+
250
+ function scanRootAssets(contentDir) {
251
+ // What the project's ignore rules leave out (lib/wdignore.js) is never
252
+ // loaded into the pages either - in public/ too.
253
+ const rules = projectIgnore(contentDir);
254
+ const css = [];
255
+ const js = [];
256
+ function walk(dir, relBase) {
257
+ let entries;
258
+ try {
259
+ entries = fs.readdirSync(dir, { withFileTypes: true });
260
+ } catch {
261
+ return;
262
+ }
263
+ for (const entry of entries) {
264
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
265
+ const abs = path.join(dir, entry.name);
266
+ if (entry.isDirectory()) {
267
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
268
+ // Dot-folders (.github, .claude, .husky, .vscode, ...) hold tooling,
269
+ // never site assets - the same rule findAllPages() applies to pages.
270
+ // Without it, a CI script under .github/ ran on every page.
271
+ if (entry.name.startsWith('.')) continue;
272
+ if (rules.ignores(rel, true)) continue;
273
+ walk(abs, rel);
274
+ continue;
275
+ }
276
+ if (!entry.isFile() || entry.name.startsWith('.')) continue; // .eslintrc.js and friends
277
+ if (rules.ignores(rel)) continue;
278
+ if (/\.css$/i.test(entry.name)) css.push(rel);
279
+ else if (/\.js$/i.test(entry.name)) js.push(rel);
280
+ }
281
+ }
282
+ walk(contentDir, '');
283
+ css.sort();
284
+ js.sort();
285
+
286
+ const publicCss = [];
287
+ const publicJs = [];
288
+ function walkPublic(dir, relBase) {
289
+ let entries;
290
+ try {
291
+ entries = fs.readdirSync(dir, { withFileTypes: true });
292
+ } catch {
293
+ return;
294
+ }
295
+ for (const entry of entries) {
296
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
297
+ const abs = path.join(dir, entry.name);
298
+ if (entry.isDirectory()) {
299
+ walkPublic(abs, rel);
300
+ continue;
301
+ }
302
+ if (!entry.isFile() || rules.ignores(`public/${rel}`)) continue;
303
+ if (/\.css$/i.test(entry.name)) publicCss.push(`/${rel}`);
304
+ else if (/\.js$/i.test(entry.name)) publicJs.push(`/${rel}`);
305
+ }
306
+ }
307
+ walkPublic(path.join(contentDir, 'public'), '');
308
+ publicCss.sort();
309
+ publicJs.sort();
310
+
311
+ return { css, js, publicCss, publicJs };
312
+ }