@writedocs/generator 0.12.0 → 0.13.1

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.
@@ -1,189 +1,203 @@
1
- import { defineCollection } from 'astro:content';
2
- import { glob } from 'astro/loaders';
3
- import type { Loader } from 'astro/loaders';
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { pageFrontmatterSchema, findAllPages } from './lib/config';
8
- import { titleFromPath } from './lib/pages.js';
9
- import { writedocsTempDir } from './lib/writedocs-temp-dir.js';
10
-
11
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
12
-
13
- // Astro's glob loader resolves `base` via `new URL(base, root)`. On Windows,
14
- // a raw path string like "C:\foo\docs" gets misparsed by the WHATWG URL
15
- // parser (the drive letter "C:" looks like a URL scheme), which breaks
16
- // downstream `fileURLToPath` calls. Passing an explicit file:// URL sidesteps
17
- // that entirely and works the same on every platform.
18
- //
19
- // Auto-generated OpenAPI stub pages (see generate-api-pages.js) live under
20
- // writedocsTempDir() - an OS-temp-directory location keyed off contentDir,
21
- // not anywhere inside the content directory itself - so they never show up
22
- // mixed in with a site's own hand-written pages, and writedocs never writes
23
- // generated files into a person's own project folder. The same location is
24
- // also where build-time manifests/caches live - see writedocs-temp-dir.js's
25
- // own doc comment. A separate collection (rather than a second base folder
26
- // glued onto `pages` somehow) because Astro's loader API has no supported
27
- // way to point one collection's glob() at two base directories sharing a
28
- // single store without each call's own "delete anything I didn't just see"
29
- // cleanup wiping out the other's entries - [...slug].astro merges both
30
- // collections' entries back into one list at query time instead, which
31
- // sidesteps that entirely.
32
- const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
33
- const generatedDocsBase = pathToFileURL(generatedDocsDir + path.sep);
34
-
35
- // Page frontmatter - defined in lib/config-schema.ts as
36
- // pageFrontmatterSchema, next to writedocs.json's own schema, so
37
- // `writedocs validate` checks every page against exactly the schema the
38
- // build uses (that file compiles to the plain JS validate loads).
39
- const docsSchema = pageFrontmatterSchema;
40
-
41
- /** Wraps another loader so it's skipped entirely - no filesystem scan, no
42
- * "directory doesn't exist"/"no files found" warning - when its own base
43
- * directory doesn't exist yet. Astro requires every collection declared
44
- * in this file to have a loader, but most sites have no OpenAPI groups
45
- * at all (generate-api-pages.js only ever creates a generated-docs/
46
- * directory under writedocsTempDir() when at least one exists), so without this
47
- * the `generatedDocs` collection below would print a spurious warning on
48
- * every single build/dev run for the common case of a site with no
49
- * OpenAPI pages. */
50
- function skipIfMissing(inner: Loader): Loader {
51
- return {
52
- name: inner.name,
53
- load: async (context) => {
54
- if (!fs.existsSync(generatedDocsBase)) return;
55
- return inner.load(withTitleFallback(context));
56
- },
57
- };
58
- }
59
-
60
- // A page with no `title` in its frontmatter gets one from its file name,
61
- // before the schema (which requires `title`) sees it - Mintlify's rule, so
62
- // a migrated page that relied on it builds with the same title. See
63
- // titleFromPath() in lib/pages.js; `writedocs validate` applies the same
64
- // default (lib/content-check.js).
65
- type LoaderContext = Parameters<Loader['load']>[0];
66
- function withTitleFallback(context: LoaderContext): LoaderContext {
67
- return {
68
- ...context,
69
- parseData: (props) =>
70
- context.parseData({
71
- ...props,
72
- data:
73
- typeof props.data?.title === 'string'
74
- ? props.data
75
- : { ...props.data, title: titleFromPath(props.filePath ?? props.id) },
76
- }),
77
- };
78
- }
79
-
80
- const generatedDocs = defineCollection({
81
- loader: skipIfMissing(glob({ pattern: '**/*.{md,mdx}', base: generatedDocsBase })),
82
- schema: docsSchema,
83
- });
84
-
85
- // Every hand-written page in the project, wherever it lives - see
86
- // findAllPages() in lib/config.ts for the exact discovery rule (any
87
- // .md/.mdx file with a frontmatter block, the usual build/dependency
88
- // directories excluded - docs/ has no special status, it's scanned like
89
- // any other folder). A single collection covering the whole content
90
- // directory works here (unlike generatedDocs, which needs its own
91
- // separate collection - see that const's own comment) because there's
92
- // only one base to worry about: the content root itself.
93
- //
94
- // The literal file list (rather than a `**/*.{md,mdx}` pattern) is what
95
- // actually implements the frontmatter-based filter: glob()'s `pattern`
96
- // option takes glob patterns, not a predicate function, so the predicate
97
- // has to run first, here, to produce the list glob() then just matches
98
- // literally. Astro's own default id computation, scoped to this same
99
- // content-root base, is what gives a page under docs/ its "docs/..."
100
- // file id and a page at the root its bare file id - see
101
- // fileIdForEntry()'s own comment in lib/config.ts for the one place that
102
- // id computation needs to be independently recovered (once a page's
103
- // frontmatter `slug` has overridden `entry.id` itself).
104
- const contentRootBase = pathToFileURL(contentDir + path.sep);
105
-
106
- /** Wraps astro's own glob() loader so pages are re-discovered live during
107
- * `astro dev`, not just once when this module first evaluates.
108
- *
109
- * The naive approach - `glob({ pattern: findAllPages(contentDir), base })`,
110
- * computed once at module load, as this used to be - works fine for the
111
- * *first* load, but astro's glob loader's own dev-mode watcher only ever
112
- * matches entries against whatever literal pattern list it was constructed
113
- * with (see matchesGlob() in astro's glob.js, called from its `watcher.on(
114
- * 'add', ...)` handler): a file created after that list was computed can
115
- * never match it, so it silently never becomes a page until the dev server
116
- * is restarted and this module re-evaluates findAllPages() from scratch.
117
- * That's the exact bug this wrapper fixes.
118
- *
119
- * A plain wildcard pattern (`**\/*.{md,mdx}`) doesn't work as a substitute,
120
- * either: whether a given .md/.mdx file counts as a page at all depends on
121
- * its *content* (does it have a frontmatter block? - see findAllPages()'s
122
- * own doc comment, this is what lets e.g. snippets/ partials with no
123
- * frontmatter coexist in the content dir without becoming pages
124
- * themselves), not just its path, and glob()'s `pattern` option only does
125
- * path matching - it can't express that filter. Something has to re-run
126
- * findAllPages() itself, content and all, whenever the file set changes.
127
- *
128
- * So: this re-invokes astro's own glob() loader - reusing all of its real
129
- * parsing/rendering/digest-based caching logic rather than reimplementing
130
- * any of that - with a freshly recomputed literal file list every time
131
- * something relevant changes on disk, instead of once. The inner loader's
132
- * own watcher wiring is deliberately skipped each time (`watcher` is
133
- * stripped from the context passed to it) - this loader keeps exactly one
134
- * watcher subscription of its own instead, covering every case uniformly
135
- * (a new page file appearing, one being deleted, frontmatter being added
136
- * to or removed from an existing file, ordinary content edits) rather than
137
- * relying on the inner loader's add/change/unlink handlers, which - as
138
- * above - are only ever bound to whatever the pattern looked like at the
139
- * moment they were registered. */
140
- function livePages(dir: string, base: URL): Loader {
141
- return {
142
- name: 'writedocs-live-pages',
143
- load: async (context) => {
144
- const { watcher, store, logger } = context;
145
-
146
- async function resync() {
147
- const files = findAllPages(dir);
148
- if (files.length === 0) {
149
- // Mirrors the old skipIfEmpty() wrapper: skip calling the inner
150
- // loader entirely (rather than passing it an empty/impossible
151
- // pattern) so astro doesn't print its own "no files found"
152
- // warning for a freshly-scaffolded project with no content yet -
153
- // but still clear out any previously-synced entries, in case a
154
- // page's last file was just deleted mid dev-session rather than
155
- // this being the initial load of an empty project.
156
- for (const id of store.keys()) store.delete(id);
157
- return;
158
- }
159
- await glob({ pattern: files, base }).load({ ...withTitleFallback(context), watcher: undefined });
160
- }
161
-
162
- await resync();
163
- if (!watcher) return; // no watcher outside `astro dev` (e.g. `astro build`)
164
-
165
- watcher.add(fileURLToPath(base));
166
- let pending: ReturnType<typeof setTimeout> | undefined;
167
- const scheduleResync = (changedPath: string) => {
168
- if (!/\.mdx?$/i.test(changedPath)) return;
169
- clearTimeout(pending);
170
- // Debounced: an editor's "save" can fire several fs events in
171
- // quick succession (e.g. atomic-write = unlink+add), and adding
172
- // several files at once shouldn't trigger a resync per file.
173
- pending = setTimeout(() => {
174
- resync().catch((err) => logger.error(`Failed to reload pages: ${err.message}`));
175
- }, 100);
176
- };
177
- watcher.on('add', scheduleResync);
178
- watcher.on('unlink', scheduleResync);
179
- watcher.on('change', scheduleResync);
180
- },
181
- };
182
- }
183
-
184
- const pages = defineCollection({
185
- loader: livePages(contentDir, contentRootBase),
186
- schema: docsSchema,
187
- });
188
-
189
- export const collections = { pages, generatedDocs };
1
+ import { defineCollection } from 'astro:content';
2
+ import { glob } from 'astro/loaders';
3
+ import type { Loader } from 'astro/loaders';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { pageFrontmatterSchema, findAllPages } from './lib/config';
8
+ import { titleFromPath } from './lib/pages.js';
9
+ import { writedocsTempDir } from './lib/writedocs-temp-dir.js';
10
+
11
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
12
+
13
+ // Astro's glob loader resolves `base` via `new URL(base, root)`. On Windows,
14
+ // a raw path string like "C:\foo\docs" gets misparsed by the WHATWG URL
15
+ // parser (the drive letter "C:" looks like a URL scheme), which breaks
16
+ // downstream `fileURLToPath` calls. Passing an explicit file:// URL sidesteps
17
+ // that entirely and works the same on every platform.
18
+ //
19
+ // Auto-generated OpenAPI stub pages (see generate-api-pages.js) live under
20
+ // writedocsTempDir() - an OS-temp-directory location keyed off contentDir,
21
+ // not anywhere inside the content directory itself - so they never show up
22
+ // mixed in with a site's own hand-written pages, and writedocs never writes
23
+ // generated files into a person's own project folder. The same location is
24
+ // also where build-time manifests/caches live - see writedocs-temp-dir.js's
25
+ // own doc comment. A separate collection (rather than a second base folder
26
+ // glued onto `pages` somehow) because Astro's loader API has no supported
27
+ // way to point one collection's glob() at two base directories sharing a
28
+ // single store without each call's own "delete anything I didn't just see"
29
+ // cleanup wiping out the other's entries - [...slug].astro merges both
30
+ // collections' entries back into one list at query time instead, which
31
+ // sidesteps that entirely.
32
+ const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
33
+ const generatedDocsBase = pathToFileURL(generatedDocsDir + path.sep);
34
+
35
+ // Page frontmatter - defined in lib/config-schema.ts as
36
+ // pageFrontmatterSchema, next to writedocs.json's own schema, so
37
+ // `writedocs validate` checks every page against exactly the schema the
38
+ // build uses (that file compiles to the plain JS validate loads).
39
+ const docsSchema = pageFrontmatterSchema;
40
+
41
+ /** Wraps another loader so it's skipped entirely - no filesystem scan, no
42
+ * "directory doesn't exist"/"no files found" warning - when its own base
43
+ * directory doesn't exist yet. Astro requires every collection declared
44
+ * in this file to have a loader, but most sites have no OpenAPI groups
45
+ * at all (generate-api-pages.js only ever creates a generated-docs/
46
+ * directory under writedocsTempDir() when at least one exists), so without this
47
+ * the `generatedDocs` collection below would print a spurious warning on
48
+ * every single build/dev run for the common case of a site with no
49
+ * OpenAPI pages.
50
+ *
51
+ * Without a watcher, in `writedocs dev` too: the collection is synced when
52
+ * the preview starts and then only when lib/openapi-reload-integration.js
53
+ * asks (refreshContent()), after writing the pages of an edited spec - in
54
+ * the order that keeps the navigation and the pages in step. A watcher of
55
+ * its own would sync each page file as it's written, at its own moment
56
+ * (and each refresh would add another set of its listeners). */
57
+ function skipIfMissing(inner: Loader): Loader {
58
+ return {
59
+ name: inner.name,
60
+ load: async (context) => {
61
+ if (!fs.existsSync(generatedDocsBase)) return;
62
+ // Left empty: the last spec taken out of writedocs.json while
63
+ // `writedocs dev` runs (the folder stays then). glob() would only warn
64
+ // about no files and keep the pages it had.
65
+ if (!fs.readdirSync(generatedDocsBase, { recursive: true }).some((file) => /\.mdx?$/i.test(String(file)))) {
66
+ for (const id of context.store.keys()) context.store.delete(id);
67
+ return;
68
+ }
69
+ return inner.load({ ...withTitleFallback(context), watcher: undefined });
70
+ },
71
+ };
72
+ }
73
+
74
+ // A page with no `title` in its frontmatter gets one from its file name,
75
+ // before the schema (which requires `title`) sees it - Mintlify's rule, so
76
+ // a migrated page that relied on it builds with the same title. See
77
+ // titleFromPath() in lib/pages.js; `writedocs validate` applies the same
78
+ // default (lib/content-check.js).
79
+ type LoaderContext = Parameters<Loader['load']>[0];
80
+ function withTitleFallback(context: LoaderContext): LoaderContext {
81
+ return {
82
+ ...context,
83
+ parseData: (props) =>
84
+ context.parseData({
85
+ ...props,
86
+ data:
87
+ typeof props.data?.title === 'string'
88
+ ? props.data
89
+ : { ...props.data, title: titleFromPath(props.filePath ?? props.id) },
90
+ }),
91
+ };
92
+ }
93
+
94
+ const generatedDocs = defineCollection({
95
+ loader: skipIfMissing(glob({ pattern: '**/*.{md,mdx}', base: generatedDocsBase })),
96
+ schema: docsSchema,
97
+ });
98
+
99
+ // Every hand-written page in the project, wherever it lives - see
100
+ // findAllPages() in lib/config.ts for the exact discovery rule (any
101
+ // .md/.mdx file with a frontmatter block, the usual build/dependency
102
+ // directories excluded - docs/ has no special status, it's scanned like
103
+ // any other folder). A single collection covering the whole content
104
+ // directory works here (unlike generatedDocs, which needs its own
105
+ // separate collection - see that const's own comment) because there's
106
+ // only one base to worry about: the content root itself.
107
+ //
108
+ // The literal file list (rather than a `**/*.{md,mdx}` pattern) is what
109
+ // actually implements the frontmatter-based filter: glob()'s `pattern`
110
+ // option takes glob patterns, not a predicate function, so the predicate
111
+ // has to run first, here, to produce the list glob() then just matches
112
+ // literally. Astro's own default id computation, scoped to this same
113
+ // content-root base, is what gives a page under docs/ its "docs/..."
114
+ // file id and a page at the root its bare file id - see
115
+ // fileIdForEntry()'s own comment in lib/config.ts for the one place that
116
+ // id computation needs to be independently recovered (once a page's
117
+ // frontmatter `slug` has overridden `entry.id` itself).
118
+ const contentRootBase = pathToFileURL(contentDir + path.sep);
119
+
120
+ /** Wraps astro's own glob() loader so pages are re-discovered live during
121
+ * `astro dev`, not just once when this module first evaluates.
122
+ *
123
+ * The naive approach - `glob({ pattern: findAllPages(contentDir), base })`,
124
+ * computed once at module load, as this used to be - works fine for the
125
+ * *first* load, but astro's glob loader's own dev-mode watcher only ever
126
+ * matches entries against whatever literal pattern list it was constructed
127
+ * with (see matchesGlob() in astro's glob.js, called from its `watcher.on(
128
+ * 'add', ...)` handler): a file created after that list was computed can
129
+ * never match it, so it silently never becomes a page until the dev server
130
+ * is restarted and this module re-evaluates findAllPages() from scratch.
131
+ * That's the exact bug this wrapper fixes.
132
+ *
133
+ * A plain wildcard pattern (`**\/*.{md,mdx}`) doesn't work as a substitute,
134
+ * either: whether a given .md/.mdx file counts as a page at all depends on
135
+ * its *content* (does it have a frontmatter block? - see findAllPages()'s
136
+ * own doc comment, this is what lets e.g. snippets/ partials with no
137
+ * frontmatter coexist in the content dir without becoming pages
138
+ * themselves), not just its path, and glob()'s `pattern` option only does
139
+ * path matching - it can't express that filter. Something has to re-run
140
+ * findAllPages() itself, content and all, whenever the file set changes.
141
+ *
142
+ * So: this re-invokes astro's own glob() loader - reusing all of its real
143
+ * parsing/rendering/digest-based caching logic rather than reimplementing
144
+ * any of that - with a freshly recomputed literal file list every time
145
+ * something relevant changes on disk, instead of once. The inner loader's
146
+ * own watcher wiring is deliberately skipped each time (`watcher` is
147
+ * stripped from the context passed to it) - this loader keeps exactly one
148
+ * watcher subscription of its own instead, covering every case uniformly
149
+ * (a new page file appearing, one being deleted, frontmatter being added
150
+ * to or removed from an existing file, ordinary content edits) rather than
151
+ * relying on the inner loader's add/change/unlink handlers, which - as
152
+ * above - are only ever bound to whatever the pattern looked like at the
153
+ * moment they were registered. */
154
+ function livePages(dir: string, base: URL): Loader {
155
+ return {
156
+ name: 'writedocs-live-pages',
157
+ load: async (context) => {
158
+ const { watcher, store, logger } = context;
159
+
160
+ async function resync() {
161
+ const files = findAllPages(dir);
162
+ if (files.length === 0) {
163
+ // Mirrors the old skipIfEmpty() wrapper: skip calling the inner
164
+ // loader entirely (rather than passing it an empty/impossible
165
+ // pattern) so astro doesn't print its own "no files found"
166
+ // warning for a freshly-scaffolded project with no content yet -
167
+ // but still clear out any previously-synced entries, in case a
168
+ // page's last file was just deleted mid dev-session rather than
169
+ // this being the initial load of an empty project.
170
+ for (const id of store.keys()) store.delete(id);
171
+ return;
172
+ }
173
+ await glob({ pattern: files, base }).load({ ...withTitleFallback(context), watcher: undefined });
174
+ }
175
+
176
+ await resync();
177
+ if (!watcher) return; // no watcher outside `astro dev` (e.g. `astro build`)
178
+
179
+ watcher.add(fileURLToPath(base));
180
+ let pending: ReturnType<typeof setTimeout> | undefined;
181
+ const scheduleResync = (changedPath: string) => {
182
+ if (!/\.mdx?$/i.test(changedPath)) return;
183
+ clearTimeout(pending);
184
+ // Debounced: an editor's "save" can fire several fs events in
185
+ // quick succession (e.g. atomic-write = unlink+add), and adding
186
+ // several files at once shouldn't trigger a resync per file.
187
+ pending = setTimeout(() => {
188
+ resync().catch((err) => logger.error(`Failed to reload pages: ${err.message}`));
189
+ }, 100);
190
+ };
191
+ watcher.on('add', scheduleResync);
192
+ watcher.on('unlink', scheduleResync);
193
+ watcher.on('change', scheduleResync);
194
+ },
195
+ };
196
+ }
197
+
198
+ const pages = defineCollection({
199
+ loader: livePages(contentDir, contentRootBase),
200
+ schema: docsSchema,
201
+ });
202
+
203
+ export const collections = { pages, generatedDocs };
@@ -1,20 +1,22 @@
1
- // How writedocs code that runs inside Astro - astro.config.mjs, remark
2
- // plugins, components - tells the author something. Under the writedocs CLI
3
- // the message goes over IPC to the CLI process (src/cli/run-astro.js), which
4
- // prints it in its own format: warnings are listed at the end of a build,
5
- // or as they happen in `writedocs dev`. Anywhere else (Astro run directly,
6
- // a test) it's printed with a [writedocs] prefix.
7
- //
8
- // level: 'warn' - something the author should fix or know about;
9
- // 'info' - a note about how the site was built (shown after a build);
10
- // 'debug' - only with --verbose.
11
- // where: optional "file:line" the message is about, relative to the project.
12
- export function report(level, message, where) {
13
- if (typeof process !== 'undefined' && typeof process.send === 'function' && process.connected) {
14
- process.send({ type: 'report', level, message, where: where ?? null });
15
- return;
16
- }
17
- const text = `[writedocs] ${where ? `${where} - ` : ''}${message}`;
18
- if (level === 'warn') console.warn(text);
19
- else console.log(text);
20
- }
1
+ // How writedocs code that runs inside Astro - astro.config.mjs, remark
2
+ // plugins, components - tells the author something. Under the writedocs CLI
3
+ // the message goes over IPC to the CLI process (src/cli/run-astro.js), which
4
+ // prints it in its own format: warnings are listed at the end of a build,
5
+ // or as they happen in `writedocs dev`. Anywhere else (Astro run directly,
6
+ // a test) it's printed with a [writedocs] prefix.
7
+ //
8
+ // level: 'error' - something broken right now, in `writedocs dev` (an
9
+ // OpenAPI spec that stopped parsing);
10
+ // 'warn' - something the author should fix or know about;
11
+ // 'info' - a note about how the site was built (shown after a build);
12
+ // 'debug' - only with --verbose.
13
+ // where: optional "file:line" the message is about, relative to the project.
14
+ export function report(level, message, where) {
15
+ if (typeof process !== 'undefined' && typeof process.send === 'function' && process.connected) {
16
+ process.send({ type: 'report', level, message, where: where ?? null });
17
+ return;
18
+ }
19
+ const text = `[writedocs] ${where ? `${where} - ` : ''}${message}`;
20
+ if (level === 'warn') console.warn(text);
21
+ else console.log(text);
22
+ }
@@ -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
+ }