@writedocs/generator 0.11.1 → 0.13.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,101 @@
1
+ // `writedocs dev`, installed: Astro's content store changes reach the page.
2
+ //
3
+ // When a collection entry changes - a page's frontmatter, a generated API
4
+ // page added, renamed or removed (lib/openapi-reload-integration.js) - Astro
5
+ // writes two files under <packageRoot>/.astro/ and learns that it did from
6
+ // Vite's file watcher:
7
+ // - data-store.json, the entries: on its change event Astro re-reads it,
8
+ // clears the routes getStaticPaths() gave, and reloads the open tab
9
+ // (astro/dist/content/vite-plugin-content-virtual-mod.js);
10
+ // - content-modules.mjs, the module that renders each entry: an ordinary
11
+ // module, which Vite invalidates when it changes - without that, a new
12
+ // entry fails to render (UnknownContentCollectionError).
13
+ // Vite's watcher ignores everything under node_modules, whatever the config
14
+ // says - and an installed writedocs is there
15
+ // (<project>/node_modules/@writedocs/generator/.astro/...). So neither event
16
+ // came: a title edited in a page's frontmatter, or a new operation's page,
17
+ // stayed as it was until the preview restarted. In a checkout of this
18
+ // repository the folder isn't under node_modules and Vite sees it by itself.
19
+ //
20
+ // This watches the two files directly and hands their change events to
21
+ // Vite's watcher - the module list first, so the reload Astro sends for the
22
+ // store finds it current. lib/openapi-reload-integration.js hands them on
23
+ // itself (contentStoreChanged()), at the moment it knows the store is
24
+ // complete; the echo of that from the watcher is skipped.
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ /** The files, in the order their change is handed on. */
29
+ export const CONTENT_STORE_FILES = ['content-modules.mjs', 'data-store.json'];
30
+
31
+ // When contentStoreChanged() last ran - the watcher's own event for the same
32
+ // writes comes right after it.
33
+ let handedOnAt = 0;
34
+ const ECHO_MS = 1000;
35
+
36
+ /** Hands Astro the change events of its content store files, as if Vite's
37
+ * watcher had seen them - Astro re-reads the store, clears its routes and
38
+ * reloads the open tab. For a caller that has just synced the store
39
+ * (refreshContent() resolves once both files are written). */
40
+ export function contentStoreChanged(server, packageRoot) {
41
+ handedOnAt = Date.now();
42
+ for (const name of CONTENT_STORE_FILES) {
43
+ const file = path.join(packageRoot, '.astro', name);
44
+ if (fs.existsSync(file)) server.watcher.emit('change', file);
45
+ }
46
+ }
47
+
48
+ /** Whether Vite's watcher can't see files in `packageRoot` - it's inside a
49
+ * node_modules folder. */
50
+ export function insideNodeModules(packageRoot) {
51
+ return path.resolve(packageRoot).split(/[\\/]/).includes('node_modules');
52
+ }
53
+
54
+ /** Calls `onChange(files)` - the ones of `names` in `dir` written since the
55
+ * last call, in the order of `names` - once a burst of writes settles.
56
+ * Astro replaces each file whole (a rename), so the folder is what's
57
+ * watched. Returns a function that stops. */
58
+ export function watchFiles(dir, names, onChange, { settleMs = 100 } = {}) {
59
+ fs.mkdirSync(dir, { recursive: true });
60
+ const changed = new Set();
61
+ let timer = null;
62
+ let watcher;
63
+ try {
64
+ watcher = fs.watch(dir, (_event, filename) => {
65
+ if (!filename || !names.includes(filename)) return;
66
+ changed.add(filename);
67
+ clearTimeout(timer);
68
+ timer = setTimeout(() => {
69
+ const files = names.filter((name) => changed.has(name)).map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
70
+ changed.clear();
71
+ if (files.length) onChange(files);
72
+ }, settleMs);
73
+ });
74
+ watcher.on('error', () => {});
75
+ } catch {
76
+ return () => {};
77
+ }
78
+ return () => {
79
+ clearTimeout(timer);
80
+ watcher.close();
81
+ };
82
+ }
83
+
84
+ export function contentStoreReload({ packageRoot }) {
85
+ return {
86
+ name: 'writedocs-content-store-reload',
87
+ hooks: {
88
+ 'astro:server:setup': ({ server }) => {
89
+ if (!insideNodeModules(packageRoot)) return;
90
+ // The paths exactly as Astro compares them: fileURLToPath() of
91
+ // new URL('.astro/<file>', root), root being packageRoot.
92
+ const dir = path.join(packageRoot, '.astro');
93
+ const stop = watchFiles(dir, CONTENT_STORE_FILES, (files) => {
94
+ if (Date.now() - handedOnAt < ECHO_MS) return;
95
+ for (const file of files) server.watcher.emit('change', file);
96
+ });
97
+ server.httpServer?.once('close', stop);
98
+ },
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,53 @@
1
+ // `writedocs dev`: astro-icon's icons reach the page from a file, not through
2
+ // Vite's module graph.
3
+ //
4
+ // In dev, astro-icon's `virtual:astro-icon` module holds every icon of every
5
+ // installed @iconify-json collection - `export default {...}` with ~15 MB of
6
+ // JSON (a build keeps only the icons pages use). Vite then transforms that
7
+ // module for the server, writes a source map for it and inlines it (the 15 MB
8
+ // again, in base64), Node reads that map back, and V8 compiles the whole
9
+ // thing: ~5 s of the first page of every `writedocs dev`, whatever the site,
10
+ // and over 1 GB of memory (measured in WD-312's round 03 - see
11
+ // docs/dev/docs/dev-preview.mdx).
12
+ //
13
+ // So the data astro-icon puts in the module goes to a file instead, and the
14
+ // module becomes `export default JSON.parse(readFileSync(<file>))` - the same
15
+ // object, the same icons; only the 15 MB stops passing through Vite.
16
+ //
17
+ // Only in `writedocs dev` (`apply: 'serve'`), and only for the server: a
18
+ // build doesn't load this plugin at all. A module that doesn't look the way
19
+ // this expects (a new astro-icon) is left as it is - the preview is slower
20
+ // again, not broken.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ const MODULE_ID = '\0virtual:astro-icon';
25
+
26
+ /** astro-icon's module - `export default <json>;\nexport const config = <json>` -
27
+ * as { data, config } (the two JSON texts), or null for anything else. */
28
+ export function splitAstroIconModule(code) {
29
+ const match = /^export default (\{[\s\S]*\});\nexport const config = (\{[\s\S]*\})\s*$/.exec(code);
30
+ return match ? { data: match[1], config: match[2] } : null;
31
+ }
32
+
33
+ /** The module that replaces it: the data read from `file`, `config` as it was. */
34
+ export function iconDataModule(file, config) {
35
+ return `import { readFileSync } from 'node:fs';\nexport default JSON.parse(readFileSync(${JSON.stringify(file)}, 'utf-8'));\nexport const config = ${config};\n`;
36
+ }
37
+
38
+ /** The Vite plugin; the data goes to `<dir>/astro-icon.json`. */
39
+ export function iconDataFromFile(dir) {
40
+ return {
41
+ name: 'writedocs:astro-icon-data-file',
42
+ apply: 'serve',
43
+ transform(code, id) {
44
+ if (id !== MODULE_ID || this.environment?.config?.consumer === 'client') return null;
45
+ const parts = splitAstroIconModule(code);
46
+ if (!parts) return null;
47
+ const file = path.join(dir, 'astro-icon.json');
48
+ fs.mkdirSync(dir, { recursive: true });
49
+ fs.writeFileSync(file, parts.data);
50
+ return { code: iconDataModule(file, parts.config), map: null };
51
+ },
52
+ };
53
+ }
@@ -1,54 +1,49 @@
1
- // Generated API pages whose address changed between writedocs versions, as
2
- // redirects from the old address to the new one - so links to a published
3
- // site keep working after an update.
4
- //
5
- // One case so far: an operation with no tag used to be served under
6
- // "<path>/untagged/<operation>/" and is now at "<path>/<operation>/".
7
- // generateApiPages() (src/cli/generate-api-pages.js) works the list out
8
- // from the specs and writes it; astro.config.mjs adds it to the site's
9
- // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
- // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
- // counts the old addresses as existing.
12
- //
13
- // Plain JavaScript: read by code that runs under plain Node.
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import { writedocsTempDir } from './writedocs-temp-dir.js';
17
-
18
- const fileFor = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'moved.json');
19
-
20
- /** `[{ source: "/api/untagged/get-pets", destination: "/api/get-pets/" }]` -
21
- * empty when nothing moved, or generateApiPages() hasn't run. */
22
- export function readMovedApiPages(contentDir) {
23
- try {
24
- const list = JSON.parse(fs.readFileSync(fileFor(contentDir), 'utf-8'));
25
- return Array.isArray(list) ? list.filter((r) => typeof r?.source === 'string' && typeof r?.destination === 'string') : [];
26
- } catch {
27
- return [];
28
- }
29
- }
30
-
31
- export function writeMovedApiPages(contentDir, redirects) {
32
- const file = fileFor(contentDir);
33
- fs.mkdirSync(path.dirname(file), { recursive: true });
34
- fs.writeFileSync(file, JSON.stringify(redirects, null, 2));
35
- }
36
-
37
- /** The redirects for one spec's untagged operations. `moved` is
38
- * `[{ oldSlug, newSlug }]` in the spec's order; `taken` holds every slug a
39
- * page is served at (an operation tagged "untagged" still lives under
40
- * that folder - its address isn't a redirect's to take). The folder's own
41
- * address, which used to lead to its first page, goes to that page's new
42
- * address. */
43
- export function untaggedRedirects(pathPrefix, moved, taken) {
44
- const redirects = [];
45
- const free = (slug) => !taken.has(slug);
46
- for (const { oldSlug, newSlug } of moved) {
47
- if (free(oldSlug)) redirects.push({ source: `/${oldSlug}`, destination: `/${newSlug}/` });
48
- }
49
- const folder = `${pathPrefix}/untagged`;
50
- if (moved.length && free(folder) && ![...taken].some((slug) => slug.startsWith(`${folder}/`))) {
51
- redirects.push({ source: `/${folder}`, destination: `/${moved[0].newSlug}/` });
52
- }
53
- return redirects;
54
- }
1
+ // Generated API pages whose address changed between writedocs versions, as
2
+ // redirects from the old address to the new one - so links to a published
3
+ // site keep working after an update.
4
+ //
5
+ // One case so far: an operation with no tag used to be served under
6
+ // "<path>/untagged/<operation>/" and is now at "<path>/<operation>/".
7
+ // generateApiPages() (src/cli/generate-api-pages.js) works the list out
8
+ // from the specs and writes it; astro.config.mjs adds it to the site's
9
+ // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
+ // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
+ // counts the old addresses as existing.
12
+ //
13
+ // Plain JavaScript: read by code that runs under plain Node.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
17
+
18
+ /** Where generateApiPages() writes the list (JSON), when anything moved. */
19
+ export const movedApiPagesFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'moved.json');
20
+
21
+ /** `[{ source: "/api/untagged/get-pets", destination: "/api/get-pets/" }]` -
22
+ * empty when nothing moved, or generateApiPages() hasn't run. */
23
+ export function readMovedApiPages(contentDir) {
24
+ try {
25
+ const list = JSON.parse(fs.readFileSync(movedApiPagesFile(contentDir), 'utf-8'));
26
+ return Array.isArray(list) ? list.filter((r) => typeof r?.source === 'string' && typeof r?.destination === 'string') : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ /** The redirects for one spec's untagged operations. `moved` is
33
+ * `[{ oldSlug, newSlug }]` in the spec's order; `taken` holds every slug a
34
+ * page is served at (an operation tagged "untagged" still lives under
35
+ * that folder - its address isn't a redirect's to take). The folder's own
36
+ * address, which used to lead to its first page, goes to that page's new
37
+ * address. */
38
+ export function untaggedRedirects(pathPrefix, moved, taken) {
39
+ const redirects = [];
40
+ const free = (slug) => !taken.has(slug);
41
+ for (const { oldSlug, newSlug } of moved) {
42
+ if (free(oldSlug)) redirects.push({ source: `/${oldSlug}`, destination: `/${newSlug}/` });
43
+ }
44
+ const folder = `${pathPrefix}/untagged`;
45
+ if (moved.length && free(folder) && ![...taken].some((slug) => slug.startsWith(`${folder}/`))) {
46
+ redirects.push({ source: `/${folder}`, destination: `/${moved[0].newSlug}/` });
47
+ }
48
+ return redirects;
49
+ }
@@ -0,0 +1,33 @@
1
+ // The link-preview cards a site gets (lib/og-image.js draws one), decided in
2
+ // one place for both places that draw them: src/pages/og/[...slug].png.ts,
3
+ // on request in `writedocs dev`, and the build's own step after Astro
4
+ // (src/cli/og-images.js), which draws them all in parallel. Which pages get
5
+ // one, and what's on it - the title, the description, the logo, the color -
6
+ // and where it goes: /og/<page id>.png (ogImagePath() in lib/og-image.js).
7
+ //
8
+ // Plain JavaScript, for scripts/og-images.test.js and the build's threads.
9
+ import { imageFileFor } from './image-size.js';
10
+ import { logoForCard, wantsGeneratedCard } from './og-image.js';
11
+
12
+ /** The cards of a site. `pages` is every page as { id, data, seo }: the
13
+ * collection entry's normalized id (normalizeEntryId() in lib/config.ts),
14
+ * its frontmatter, and the site's `seo` with the page's merged over it
15
+ * (mergeSeo()). What every card shares is said once - the logo is read and
16
+ * encoded once, not once per page. */
17
+ export function ogCardSet(config, pages, contentDir) {
18
+ const logoSetting = config.styles.logo;
19
+ const logoPath = typeof logoSetting === 'string' ? logoSetting : (logoSetting?.light ?? logoSetting?.dark);
20
+ return {
21
+ siteName: config.name,
22
+ primary: config.styles.colors.primary,
23
+ logo: logoForCard(logoPath ? imageFileFor(logoPath, contentDir) : null),
24
+ cards: pages
25
+ .filter(({ data, seo }) => wantsGeneratedCard(seo, data, config.seo))
26
+ .map(({ id, data }) => ({ slug: id, title: data.title, description: data.seo?.description ?? data.description ?? config.description })),
27
+ };
28
+ }
29
+
30
+ /** What ogImagePng() draws for one card of a set. */
31
+ export function ogCardOptions(set, card) {
32
+ return { title: card.title, description: card.description, siteName: set.siteName, primary: set.primary, logo: set.logo };
33
+ }