@writedocs/generator 0.13.4 → 0.14.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.
Files changed (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
@@ -1,291 +1,291 @@
1
- // Lets a static asset referenced by a root-relative URL - a writedocs.json
2
- // field (styles.favicon, styles.logo, footer.logo, styles.background.
3
- // images.{light,dark}, seo.ogImage, styles.fonts.*.source - the exact set
4
- // collectConfiguredAssetPaths() in lib/config.ts resolves) *or* a plain
5
- // image written directly into a page's own MDX/Markdown body
6
- // (`![alt](/images/foo.png)`, a raw `<img src="/images/foo.png">`, the
7
- // `<Image src="...">` component, `<Card img="...">`, ...) - resolve from
8
- // *anywhere* in the project, not just public/. "Any place to store
9
- // assets" is the whole point: a site author shouldn't have to know Astro
10
- // has a public/ convention at all, let alone reorganize their project
11
- // around it, just to reference an image from a doc page.
12
- //
13
- // Deliberately NOT implemented as "copy everything into public/ (or a
14
- // merged scratch dir) before Astro starts, then leave Astro's own
15
- // publicDir alone": that would either (a) write into the user's own
16
- // public/ folder as a side effect - a real file appearing in their
17
- // project tree that they didn't create, which writedocsTempDir()'s own
18
- // doc comment already argues against doing anywhere in this codebase, or
19
- // (b) point publicDir at a one-shot copied scratch dir instead of the
20
- // real public/, which would regress `writedocs dev`'s live file-reload
21
- // for the *existing*, common case of a file genuinely living under
22
- // public/ - Vite's own dev server watches and serves publicDir straight
23
- // off disk per-request with no copy step involved at all today; a byte
24
- // copy taken once at startup wouldn't pick up a live edit to that file
25
- // without a full dev-server restart.
26
- //
27
- // Instead, this is a small Astro integration with two hooks, each
28
- // resolving fresh rather than relying on any one-shot copy:
29
- // - astro:server:setup (dev): adds Vite dev-server middleware that
30
- // intercepts any request whose extension looks like a static asset
31
- // (looksLikeAssetPath() below - images/fonts, the same set
32
- // MIME_BY_EXTENSION already knows how to serve) and - only if it
33
- // doesn't already exist under public/ (that stays Vite's own job,
34
- // unshadowed) - streams it straight from wherever it lives in the
35
- // project. Not scoped to writedocs.json's own configured fields specifically
36
- // (an earlier version of this file was) - a page's own MDX can
37
- // reference an image path this integration has no way to know about
38
- // ahead of time short of parsing every page's content on every
39
- // request, so instead of trying to enumerate what *should* be
40
- // reachable, it just resolves whatever *is* actually requested,
41
- // directly, the same way Vite's own publicDir serving already does.
42
- // - astro:build:done: a one-time pass after Astro's own build finishes.
43
- // First, the same writedocs.json-field-driven copy as before (still needed
44
- // as its own pass - background images/font sources render into CSS
45
- // `url(...)` inside a `<style>` block, and seo.ogImage into a `<meta
46
- // content="...">` tag, neither of which the second pass below would
47
- // ever see). Second, copyReferencedContentAssets() below scans every
48
- // built .html page for `src="/..."` references (an `<img>`, mainly -
49
- // see its own comment) not already present in the output, and resolves
50
- // + copies each the same way - this is what actually covers a plain
51
- // content image, since there's no fixed field name to read it from up
52
- // front the way there is for writedocs.json's own fields. A real static
53
- // build has no "later" for a live-reload concern to apply to, so a
54
- // single pass of each here is sufficient.
55
- //
56
- // A file the project's ignore rules leave out (lib/wdignore.js: the default
57
- // exclusions and `.wdignore`) is never served nor copied, whoever names it:
58
- // the reference is left broken, as for a file that isn't there
59
- // (`writedocs broken-links` reports it). In `writedocs dev` that goes for
60
- // public/ too, which Vite would otherwise serve whole; in a build,
61
- // removeIgnoredPublicFiles() (lib/project-files-integration.js) takes such
62
- // files out of the output.
63
- import fs from 'node:fs';
64
- import path from 'node:path';
65
- import { fileURLToPath } from 'node:url';
66
- import { withoutBase } from './base-path.js';
67
- import { loadDocsConfig, collectConfiguredAssetPaths } from './config.ts';
68
- import { resolveOutsidePublic } from './asset-path.js';
69
- import { PUBLISHED_TYPES, isPublishedFile, readSpecPaths } from './project-files.js';
70
- import { projectIgnore, isIgnoredFile } from './project-ignore.js';
71
-
72
- const MIME_BY_EXTENSION = {
73
- '.svg': 'image/svg+xml',
74
- '.png': 'image/png',
75
- '.jpg': 'image/jpeg',
76
- '.jpeg': 'image/jpeg',
77
- '.gif': 'image/gif',
78
- '.webp': 'image/webp',
79
- '.avif': 'image/avif',
80
- '.ico': 'image/x-icon',
81
- '.woff': 'font/woff',
82
- '.woff2': 'font/woff2',
83
- '.ttf': 'font/ttf',
84
- '.otf': 'font/otf',
85
- };
86
-
87
- function mimeFor(filePath) {
88
- const extension = path.extname(filePath).toLowerCase();
89
- return MIME_BY_EXTENSION[extension] || PUBLISHED_TYPES[extension] || 'application/octet-stream';
90
- }
91
-
92
- /** `writedocs dev`: a request for one of the project's published files that
93
- * isn't an image or a font - robots.txt, a PDF, a JSON file (see
94
- * lib/project-files.js; the build copies them, publishProjectFiles()).
95
- * Images and fonts keep the wider rule above them: whatever path a page
96
- * names is tried. */
97
- function isPublishedFileRequest(urlPath, contentDir) {
98
- let rel;
99
- try {
100
- rel = decodeURIComponent(urlPath).replace(/^\/+/, '');
101
- } catch {
102
- return false;
103
- }
104
- return isPublishedFile(rel, { specs: readSpecPaths(contentDir), rules: projectIgnore(contentDir) });
105
- }
106
-
107
- /** Whether a request is for a file in public/ that the project's ignore
108
- * rules leave out - one `writedocs dev` must not serve. */
109
- function isIgnoredPublicRequest(urlPath, contentDir) {
110
- let rel;
111
- try {
112
- rel = decodeURIComponent(urlPath).replace(/^\/+/, '');
113
- } catch {
114
- return false;
115
- }
116
- if (!rel || !projectIgnore(contentDir).ignores(`public/${rel}`)) return false;
117
- try {
118
- return fs.statSync(path.join(contentDir, 'public', ...rel.split('/'))).isFile();
119
- } catch {
120
- return false;
121
- }
122
- }
123
-
124
-
125
- function publicPathFor(urlPath, contentDir) {
126
- const segments = urlPath.replace(/^\/+/, '').split('/');
127
- return path.join(contentDir, 'public', ...segments);
128
- }
129
-
130
- /** Root-relative, recognized-extension paths only - the same "does this
131
- * look like a static asset at all" question mimeFor()'s own map already
132
- * answers, reused here as the dev-middleware/build-scan gate instead of
133
- * a fixed list of writedocs.json field names. Deliberately permissive: a page
134
- * or config field asking for a path this returns true for gets a real
135
- * attempt to resolve it from anywhere in the project; anything else
136
- * (an actual API route, a `.html` page request, ...) is left alone,
137
- * same as before this existed. */
138
- function looksLikeAssetPath(urlPath) {
139
- return Object.prototype.hasOwnProperty.call(MIME_BY_EXTENSION, path.extname(urlPath).toLowerCase());
140
- }
141
-
142
- /** Recursively lists every `.html` file under `dir`. Astro's own build
143
- * output is already a flat-ish tree of one .html per route, so this is
144
- * just a plain walk - no globbing dependency needed for something this
145
- * small. */
146
- function listHtmlFiles(dir) {
147
- return listFilesWithExtension(dir, '.html');
148
- }
149
-
150
- // Generalização de listHtmlFiles, usada também para achar os .css do build.
151
- function listFilesWithExtension(dir, extension) {
152
- const results = [];
153
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
154
- const full = path.join(dir, entry.name);
155
- if (entry.isDirectory()) {
156
- results.push(...listFilesWithExtension(full, extension));
157
- } else if (entry.isFile() && entry.name.endsWith(extension)) {
158
- results.push(full);
159
- }
160
- }
161
- return results;
162
- }
163
-
164
- /** Scans every built page for root-relative, recognized-extension `src="/..."`
165
- * references (`<img src="...">`, mainly - what `Image.astro`, `Frame.astro`,
166
- * and a raw `![]()`/`<img>` in MDX all ultimately render down to; a
167
- * `srcset="..."` attribute is checked too, since it's the same kind of
168
- * reference and costs nothing extra to also cover) that aren't already
169
- * present in the build output, and copies each one in from wherever it
170
- * resolves in the project via resolveOutsidePublic() - the same
171
- * fallback the dev middleware below already uses, just applied once,
172
- * after the fact, to the rendered HTML instead of to live requests.
173
- * This is what actually covers a plain content-body image: unlike a
174
- * writedocs.json field, there's no fixed set of field names to read a
175
- * content image's path from ahead of time, so instead this reads
176
- * whatever `src` a page's own rendered markup ends up containing. */
177
- function copyReferencedContentAssets(outDir, contentDir, basePath) {
178
- const attrPattern = /\b(?:src|srcset)="([^"]+)"/g;
179
- for (const htmlFile of listHtmlFiles(outDir)) {
180
- const html = fs.readFileSync(htmlFile, 'utf8');
181
- let match;
182
- while ((match = attrPattern.exec(html))) {
183
- // srcset can hold a comma-separated list of "url descriptor" pairs -
184
- // split it out; a plain src is already just the one URL.
185
- const candidates = match[1].split(',').map((part) => part.trim().split(/\s+/)[0]).filter(Boolean);
186
- for (const urlPath of candidates) copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
187
- }
188
- // Referências em CSS dentro do próprio HTML: um bloco <style> escrito
189
- // na página (o `<style>` de uma página `mode: custom`, por exemplo) ou
190
- // um atributo style="...". Sem isto, uma imagem usada só como
191
- // background-image nunca era copiada para o build e dava 404 em
192
- // produção, embora funcionasse no dev (onde o middleware resolve
193
- // qualquer caminho direto do disco).
194
- for (const urlPath of cssUrlReferences(html)) copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
195
- }
196
- // O mesmo para as folhas de estilo que o build gera (_astro/*.css): é
197
- // para onde vai o .css solto na raiz do projeto, carregado automaticamente.
198
- for (const cssFile of listFilesWithExtension(outDir, '.css')) {
199
- for (const urlPath of cssUrlReferences(fs.readFileSync(cssFile, 'utf8'))) {
200
- copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
201
- }
202
- }
203
- }
204
-
205
- /** Every `url(...)` target in a chunk of CSS (or HTML containing CSS),
206
- * quoted or not. Query strings and fragments (`font.woff2?v=2`,
207
- * `icons.svg#home`) are dropped - the file on disk has neither. */
208
- function cssUrlReferences(text) {
209
- const urls = [];
210
- const urlPattern = /url\(\s*(['"]?)([^'")]+?)\1\s*\)/g;
211
- let match;
212
- while ((match = urlPattern.exec(text))) urls.push(match[2].trim().split(/[?#]/)[0]);
213
- return urls;
214
- }
215
-
216
- /** Copies one root-relative asset reference into the build output from
217
- * wherever it lives in the project, unless it's already there. A built
218
- * page's addresses carry the site's `basePath` ("/docs/images/a.png" -
219
- * lib/base-path.js); the file is the one at the address under it, and an
220
- * address outside the base isn't the site's. */
221
- function copyAssetIfMissing(address, outDir, contentDir, basePath = '') {
222
- if (!address.startsWith('/') || address.startsWith('//')) return; // only root-relative - not external, not protocol-relative
223
- const urlPath = withoutBase(basePath, address);
224
- if (urlPath === null) return;
225
- if (!looksLikeAssetPath(urlPath)) return;
226
- const segments = urlPath.replace(/^\/+/, '').split('/');
227
- const outPath = path.join(outDir, ...segments);
228
- if (fs.existsSync(outPath)) return; // already present - via public/'s passthrough copy, or an earlier reference to the same file
229
- const resolved = resolveOutsidePublic(urlPath, contentDir);
230
- if (!resolved) return; // doesn't resolve to a real file anywhere in the project either - leave the broken reference as-is
231
- if (isIgnoredFile(resolved, contentDir)) return; // left out by the ignore rules - never published
232
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
233
- fs.copyFileSync(resolved, outPath);
234
- }
235
-
236
- // `basePath`: writedocs.json's, "" or "/docs" (lib/base-path.js). A request
237
- // outside the base isn't the site's. Astro's dev server takes the base off
238
- // req.url before this middleware runs, so /docs/images/a.png and a bare
239
- // /images/a.png would look the same there - the path asked for is
240
- // req.originalUrl.
241
- export function stylesAssetFallback(contentDir, { basePath = '' } = {}) {
242
- return {
243
- name: 'writedocs-styles-asset-fallback',
244
- hooks: {
245
- 'astro:server:setup': ({ server }) => {
246
- server.middlewares.use((req, res, next) => {
247
- if (!req.url) return next();
248
- const [requestPath, query = ''] = (req.originalUrl ?? req.url).split('?');
249
- const urlPath = withoutBase(basePath, requestPath);
250
- if (urlPath === null) return next();
251
- if (!query && isIgnoredPublicRequest(urlPath, contentDir)) {
252
- res.statusCode = 404;
253
- res.end('Not found');
254
- return;
255
- }
256
- // A request with a query is Vite's own (a module: `data.json?import`).
257
- if (!looksLikeAssetPath(urlPath) && (query || !isPublishedFileRequest(urlPath, contentDir))) return next();
258
- if (fs.existsSync(publicPathFor(urlPath, contentDir))) return next(); // real public/ file - Vite's own static serving already handles it, don't shadow
259
- const resolved = resolveOutsidePublic(urlPath, contentDir);
260
- if (!resolved || isIgnoredFile(resolved, contentDir)) return next();
261
- res.setHeader('Content-Type', mimeFor(resolved));
262
- fs.createReadStream(resolved).pipe(res);
263
- });
264
- },
265
- 'astro:build:done': async ({ dir }) => {
266
- const outDir = fileURLToPath(dir);
267
- const config = loadDocsConfig(contentDir);
268
- // Pass 1: writedocs.json's own configured fields. Kept as its own,
269
- // field-name-driven pass rather than folded into pass 2 below -
270
- // seo.ogImage renders into a `<meta content="...">` tag, which
271
- // pass 2 never scans. (Pass 2 agora também lê `url(...)` em CSS,
272
- // então background images/fontes seriam pegas pelas duas; manter
273
- // o pass 1 explícito não custa nada.)
274
- for (const urlPath of collectConfiguredAssetPaths(config)) {
275
- const segments = urlPath.replace(/^\/+/, '').split('/');
276
- const outPath = path.join(outDir, ...segments);
277
- if (fs.existsSync(outPath)) continue; // already present via public/'s normal passthrough copy
278
- const resolved = resolveOutsidePublic(urlPath, contentDir);
279
- if (!resolved) continue; // not configured to a real file anywhere - same as today, just renders a broken <link>/<img>
280
- if (isIgnoredFile(resolved, contentDir)) continue; // left out by the ignore rules - never published
281
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
282
- fs.copyFileSync(resolved, outPath);
283
- }
284
- // Pass 2: arbitrary content-body assets - anything a page's own
285
- // rendered HTML references by src/srcset that pass 1 didn't
286
- // already account for.
287
- copyReferencedContentAssets(outDir, contentDir, basePath);
288
- },
289
- },
290
- };
291
- }
1
+ // Lets a static asset referenced by a root-relative URL - a writedocs.json
2
+ // field (styles.favicon, styles.logo, footer.logo, styles.background.
3
+ // images.{light,dark}, seo.ogImage, styles.fonts.*.source - the exact set
4
+ // collectConfiguredAssetPaths() in lib/config.ts resolves) *or* a plain
5
+ // image written directly into a page's own MDX/Markdown body
6
+ // (`![alt](/images/foo.png)`, a raw `<img src="/images/foo.png">`, the
7
+ // `<Image src="...">` component, `<Card img="...">`, ...) - resolve from
8
+ // *anywhere* in the project, not just public/. "Any place to store
9
+ // assets" is the whole point: a site author shouldn't have to know Astro
10
+ // has a public/ convention at all, let alone reorganize their project
11
+ // around it, just to reference an image from a doc page.
12
+ //
13
+ // Deliberately NOT implemented as "copy everything into public/ (or a
14
+ // merged scratch dir) before Astro starts, then leave Astro's own
15
+ // publicDir alone": that would either (a) write into the user's own
16
+ // public/ folder as a side effect - a real file appearing in their
17
+ // project tree that they didn't create, which writedocsTempDir()'s own
18
+ // doc comment already argues against doing anywhere in this codebase, or
19
+ // (b) point publicDir at a one-shot copied scratch dir instead of the
20
+ // real public/, which would regress `writedocs dev`'s live file-reload
21
+ // for the *existing*, common case of a file genuinely living under
22
+ // public/ - Vite's own dev server watches and serves publicDir straight
23
+ // off disk per-request with no copy step involved at all today; a byte
24
+ // copy taken once at startup wouldn't pick up a live edit to that file
25
+ // without a full dev-server restart.
26
+ //
27
+ // Instead, this is a small Astro integration with two hooks, each
28
+ // resolving fresh rather than relying on any one-shot copy:
29
+ // - astro:server:setup (dev): adds Vite dev-server middleware that
30
+ // intercepts any request whose extension looks like a static asset
31
+ // (looksLikeAssetPath() below - images/fonts, the same set
32
+ // MIME_BY_EXTENSION already knows how to serve) and - only if it
33
+ // doesn't already exist under public/ (that stays Vite's own job,
34
+ // unshadowed) - streams it straight from wherever it lives in the
35
+ // project. Not scoped to writedocs.json's own configured fields specifically
36
+ // (an earlier version of this file was) - a page's own MDX can
37
+ // reference an image path this integration has no way to know about
38
+ // ahead of time short of parsing every page's content on every
39
+ // request, so instead of trying to enumerate what *should* be
40
+ // reachable, it just resolves whatever *is* actually requested,
41
+ // directly, the same way Vite's own publicDir serving already does.
42
+ // - astro:build:done: a one-time pass after Astro's own build finishes.
43
+ // First, the same writedocs.json-field-driven copy as before (still needed
44
+ // as its own pass - background images/font sources render into CSS
45
+ // `url(...)` inside a `<style>` block, and seo.ogImage into a `<meta
46
+ // content="...">` tag, neither of which the second pass below would
47
+ // ever see). Second, copyReferencedContentAssets() below scans every
48
+ // built .html page for `src="/..."` references (an `<img>`, mainly -
49
+ // see its own comment) not already present in the output, and resolves
50
+ // + copies each the same way - this is what actually covers a plain
51
+ // content image, since there's no fixed field name to read it from up
52
+ // front the way there is for writedocs.json's own fields. A real static
53
+ // build has no "later" for a live-reload concern to apply to, so a
54
+ // single pass of each here is sufficient.
55
+ //
56
+ // A file the project's ignore rules leave out (lib/wdignore.js: the default
57
+ // exclusions and `.wdignore`) is never served nor copied, whoever names it:
58
+ // the reference is left broken, as for a file that isn't there
59
+ // (`writedocs broken-links` reports it). In `writedocs dev` that goes for
60
+ // public/ too, which Vite would otherwise serve whole; in a build,
61
+ // removeIgnoredPublicFiles() (lib/project-files-integration.js) takes such
62
+ // files out of the output.
63
+ import fs from 'node:fs';
64
+ import path from 'node:path';
65
+ import { fileURLToPath } from 'node:url';
66
+ import { withoutBase } from './base-path.js';
67
+ import { loadDocsConfig, collectConfiguredAssetPaths } from './config.ts';
68
+ import { resolveOutsidePublic } from './asset-path.js';
69
+ import { PUBLISHED_TYPES, isPublishedFile, readSpecPaths } from './project-files.js';
70
+ import { projectIgnore, isIgnoredFile } from './project-ignore.js';
71
+
72
+ const MIME_BY_EXTENSION = {
73
+ '.svg': 'image/svg+xml',
74
+ '.png': 'image/png',
75
+ '.jpg': 'image/jpeg',
76
+ '.jpeg': 'image/jpeg',
77
+ '.gif': 'image/gif',
78
+ '.webp': 'image/webp',
79
+ '.avif': 'image/avif',
80
+ '.ico': 'image/x-icon',
81
+ '.woff': 'font/woff',
82
+ '.woff2': 'font/woff2',
83
+ '.ttf': 'font/ttf',
84
+ '.otf': 'font/otf',
85
+ };
86
+
87
+ function mimeFor(filePath) {
88
+ const extension = path.extname(filePath).toLowerCase();
89
+ return MIME_BY_EXTENSION[extension] || PUBLISHED_TYPES[extension] || 'application/octet-stream';
90
+ }
91
+
92
+ /** `writedocs dev`: a request for one of the project's published files that
93
+ * isn't an image or a font - robots.txt, a PDF, a JSON file (see
94
+ * lib/project-files.js; the build copies them, publishProjectFiles()).
95
+ * Images and fonts keep the wider rule above them: whatever path a page
96
+ * names is tried. */
97
+ function isPublishedFileRequest(urlPath, contentDir) {
98
+ let rel;
99
+ try {
100
+ rel = decodeURIComponent(urlPath).replace(/^\/+/, '');
101
+ } catch {
102
+ return false;
103
+ }
104
+ return isPublishedFile(rel, { specs: readSpecPaths(contentDir), rules: projectIgnore(contentDir) });
105
+ }
106
+
107
+ /** Whether a request is for a file in public/ that the project's ignore
108
+ * rules leave out - one `writedocs dev` must not serve. */
109
+ function isIgnoredPublicRequest(urlPath, contentDir) {
110
+ let rel;
111
+ try {
112
+ rel = decodeURIComponent(urlPath).replace(/^\/+/, '');
113
+ } catch {
114
+ return false;
115
+ }
116
+ if (!rel || !projectIgnore(contentDir).ignores(`public/${rel}`)) return false;
117
+ try {
118
+ return fs.statSync(path.join(contentDir, 'public', ...rel.split('/'))).isFile();
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+
125
+ function publicPathFor(urlPath, contentDir) {
126
+ const segments = urlPath.replace(/^\/+/, '').split('/');
127
+ return path.join(contentDir, 'public', ...segments);
128
+ }
129
+
130
+ /** Root-relative, recognized-extension paths only - the same "does this
131
+ * look like a static asset at all" question mimeFor()'s own map already
132
+ * answers, reused here as the dev-middleware/build-scan gate instead of
133
+ * a fixed list of writedocs.json field names. Deliberately permissive: a page
134
+ * or config field asking for a path this returns true for gets a real
135
+ * attempt to resolve it from anywhere in the project; anything else
136
+ * (an actual API route, a `.html` page request, ...) is left alone,
137
+ * same as before this existed. */
138
+ function looksLikeAssetPath(urlPath) {
139
+ return Object.prototype.hasOwnProperty.call(MIME_BY_EXTENSION, path.extname(urlPath).toLowerCase());
140
+ }
141
+
142
+ /** Recursively lists every `.html` file under `dir`. Astro's own build
143
+ * output is already a flat-ish tree of one .html per route, so this is
144
+ * just a plain walk - no globbing dependency needed for something this
145
+ * small. */
146
+ function listHtmlFiles(dir) {
147
+ return listFilesWithExtension(dir, '.html');
148
+ }
149
+
150
+ // Generalização de listHtmlFiles, usada também para achar os .css do build.
151
+ function listFilesWithExtension(dir, extension) {
152
+ const results = [];
153
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
154
+ const full = path.join(dir, entry.name);
155
+ if (entry.isDirectory()) {
156
+ results.push(...listFilesWithExtension(full, extension));
157
+ } else if (entry.isFile() && entry.name.endsWith(extension)) {
158
+ results.push(full);
159
+ }
160
+ }
161
+ return results;
162
+ }
163
+
164
+ /** Scans every built page for root-relative, recognized-extension `src="/..."`
165
+ * references (`<img src="...">`, mainly - what `Image.astro`, `Frame.astro`,
166
+ * and a raw `![]()`/`<img>` in MDX all ultimately render down to; a
167
+ * `srcset="..."` attribute is checked too, since it's the same kind of
168
+ * reference and costs nothing extra to also cover) that aren't already
169
+ * present in the build output, and copies each one in from wherever it
170
+ * resolves in the project via resolveOutsidePublic() - the same
171
+ * fallback the dev middleware below already uses, just applied once,
172
+ * after the fact, to the rendered HTML instead of to live requests.
173
+ * This is what actually covers a plain content-body image: unlike a
174
+ * writedocs.json field, there's no fixed set of field names to read a
175
+ * content image's path from ahead of time, so instead this reads
176
+ * whatever `src` a page's own rendered markup ends up containing. */
177
+ function copyReferencedContentAssets(outDir, contentDir, basePath) {
178
+ const attrPattern = /\b(?:src|srcset)="([^"]+)"/g;
179
+ for (const htmlFile of listHtmlFiles(outDir)) {
180
+ const html = fs.readFileSync(htmlFile, 'utf8');
181
+ let match;
182
+ while ((match = attrPattern.exec(html))) {
183
+ // srcset can hold a comma-separated list of "url descriptor" pairs -
184
+ // split it out; a plain src is already just the one URL.
185
+ const candidates = match[1].split(',').map((part) => part.trim().split(/\s+/)[0]).filter(Boolean);
186
+ for (const urlPath of candidates) copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
187
+ }
188
+ // Referências em CSS dentro do próprio HTML: um bloco <style> escrito
189
+ // na página (o `<style>` de uma página `mode: custom`, por exemplo) ou
190
+ // um atributo style="...". Sem isto, uma imagem usada só como
191
+ // background-image nunca era copiada para o build e dava 404 em
192
+ // produção, embora funcionasse no dev (onde o middleware resolve
193
+ // qualquer caminho direto do disco).
194
+ for (const urlPath of cssUrlReferences(html)) copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
195
+ }
196
+ // O mesmo para as folhas de estilo que o build gera (_astro/*.css): é
197
+ // para onde vai o .css solto na raiz do projeto, carregado automaticamente.
198
+ for (const cssFile of listFilesWithExtension(outDir, '.css')) {
199
+ for (const urlPath of cssUrlReferences(fs.readFileSync(cssFile, 'utf8'))) {
200
+ copyAssetIfMissing(urlPath, outDir, contentDir, basePath);
201
+ }
202
+ }
203
+ }
204
+
205
+ /** Every `url(...)` target in a chunk of CSS (or HTML containing CSS),
206
+ * quoted or not. Query strings and fragments (`font.woff2?v=2`,
207
+ * `icons.svg#home`) are dropped - the file on disk has neither. */
208
+ function cssUrlReferences(text) {
209
+ const urls = [];
210
+ const urlPattern = /url\(\s*(['"]?)([^'")]+?)\1\s*\)/g;
211
+ let match;
212
+ while ((match = urlPattern.exec(text))) urls.push(match[2].trim().split(/[?#]/)[0]);
213
+ return urls;
214
+ }
215
+
216
+ /** Copies one root-relative asset reference into the build output from
217
+ * wherever it lives in the project, unless it's already there. A built
218
+ * page's addresses carry the site's `basePath` ("/docs/images/a.png" -
219
+ * lib/base-path.js); the file is the one at the address under it, and an
220
+ * address outside the base isn't the site's. */
221
+ function copyAssetIfMissing(address, outDir, contentDir, basePath = '') {
222
+ if (!address.startsWith('/') || address.startsWith('//')) return; // only root-relative - not external, not protocol-relative
223
+ const urlPath = withoutBase(basePath, address);
224
+ if (urlPath === null) return;
225
+ if (!looksLikeAssetPath(urlPath)) return;
226
+ const segments = urlPath.replace(/^\/+/, '').split('/');
227
+ const outPath = path.join(outDir, ...segments);
228
+ if (fs.existsSync(outPath)) return; // already present - via public/'s passthrough copy, or an earlier reference to the same file
229
+ const resolved = resolveOutsidePublic(urlPath, contentDir);
230
+ if (!resolved) return; // doesn't resolve to a real file anywhere in the project either - leave the broken reference as-is
231
+ if (isIgnoredFile(resolved, contentDir)) return; // left out by the ignore rules - never published
232
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
233
+ fs.copyFileSync(resolved, outPath);
234
+ }
235
+
236
+ // `basePath`: writedocs.json's, "" or "/docs" (lib/base-path.js). A request
237
+ // outside the base isn't the site's. Astro's dev server takes the base off
238
+ // req.url before this middleware runs, so /docs/images/a.png and a bare
239
+ // /images/a.png would look the same there - the path asked for is
240
+ // req.originalUrl.
241
+ export function stylesAssetFallback(contentDir, { basePath = '' } = {}) {
242
+ return {
243
+ name: 'writedocs-styles-asset-fallback',
244
+ hooks: {
245
+ 'astro:server:setup': ({ server }) => {
246
+ server.middlewares.use((req, res, next) => {
247
+ if (!req.url) return next();
248
+ const [requestPath, query = ''] = (req.originalUrl ?? req.url).split('?');
249
+ const urlPath = withoutBase(basePath, requestPath);
250
+ if (urlPath === null) return next();
251
+ if (!query && isIgnoredPublicRequest(urlPath, contentDir)) {
252
+ res.statusCode = 404;
253
+ res.end('Not found');
254
+ return;
255
+ }
256
+ // A request with a query is Vite's own (a module: `data.json?import`).
257
+ if (!looksLikeAssetPath(urlPath) && (query || !isPublishedFileRequest(urlPath, contentDir))) return next();
258
+ if (fs.existsSync(publicPathFor(urlPath, contentDir))) return next(); // real public/ file - Vite's own static serving already handles it, don't shadow
259
+ const resolved = resolveOutsidePublic(urlPath, contentDir);
260
+ if (!resolved || isIgnoredFile(resolved, contentDir)) return next();
261
+ res.setHeader('Content-Type', mimeFor(resolved));
262
+ fs.createReadStream(resolved).pipe(res);
263
+ });
264
+ },
265
+ 'astro:build:done': async ({ dir }) => {
266
+ const outDir = fileURLToPath(dir);
267
+ const config = loadDocsConfig(contentDir);
268
+ // Pass 1: writedocs.json's own configured fields. Kept as its own,
269
+ // field-name-driven pass rather than folded into pass 2 below -
270
+ // seo.ogImage renders into a `<meta content="...">` tag, which
271
+ // pass 2 never scans. (Pass 2 agora também lê `url(...)` em CSS,
272
+ // então background images/fontes seriam pegas pelas duas; manter
273
+ // o pass 1 explícito não custa nada.)
274
+ for (const urlPath of collectConfiguredAssetPaths(config)) {
275
+ const segments = urlPath.replace(/^\/+/, '').split('/');
276
+ const outPath = path.join(outDir, ...segments);
277
+ if (fs.existsSync(outPath)) continue; // already present via public/'s normal passthrough copy
278
+ const resolved = resolveOutsidePublic(urlPath, contentDir);
279
+ if (!resolved) continue; // not configured to a real file anywhere - same as today, just renders a broken <link>/<img>
280
+ if (isIgnoredFile(resolved, contentDir)) continue; // left out by the ignore rules - never published
281
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
282
+ fs.copyFileSync(resolved, outPath);
283
+ }
284
+ // Pass 2: arbitrary content-body assets - anything a page's own
285
+ // rendered HTML references by src/srcset that pass 1 didn't
286
+ // already account for.
287
+ copyReferencedContentAssets(outDir, contentDir, basePath);
288
+ },
289
+ },
290
+ };
291
+ }