Skip to content

Commit 78a0392

Browse files
authored
fix(docs): prerender every docs page (#202)
The docs site prerendered only the home page, so opening or refreshing any other URL on a host with a fallback to index.html showed the home page until Angular loaded and swapped in the real page. It now prerenders every page and a 404.html from the route list the sitemap uses, taken from the same fix in NgMd.
1 parent 84837fd commit 78a0392

4 files changed

Lines changed: 158 additions & 134 deletions

File tree

‎apps/docs/api-gen.plugin.ts‎

Lines changed: 107 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -37,106 +37,14 @@ export function apiGenPlugin(): Plugin {
3737
let configMemo: ApiConfig | null | undefined;
3838

3939
function loadConfig(): ApiConfig | null {
40-
if (configMemo === undefined) configMemo = readConfig();
40+
if (configMemo === undefined) configMemo = readApiConfig(root);
4141
return configMemo;
4242
}
4343

44-
function readConfig(): ApiConfig | null {
45-
const path = configPath();
46-
if (!existsSync(path)) return null;
47-
try {
48-
const proj = new Project({
49-
compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext},
50-
});
51-
const sourceFile = proj.addSourceFileAtPath(path);
52-
// We can't trivially evaluate the TS without a runtime; instead lift
53-
// the literal passed to `defineApi(...)` via AST traversal. For the
54-
// skeleton, every supported field is read as a literal so static
55-
// extraction is enough. Read the `export default` expression directly
56-
// rather than the first `CallExpression` in the file — otherwise any
57-
// helper call before the default export (even a harmless one) would
58-
// be parsed as the config.
59-
const exportAssignment = sourceFile.getExportAssignment((ea) => !ea.isExportEquals());
60-
if (!exportAssignment) return null;
61-
const callExpr = exportAssignment.getExpression().asKind(ts.SyntaxKind.CallExpression);
62-
if (!callExpr) return null;
63-
const literal = callExpr.getArguments()[0];
64-
if (!literal || !literal.asKind(ts.SyntaxKind.ObjectLiteralExpression)) return null;
65-
return parseLiteralAsConfig(literal as never);
66-
} catch (err) {
67-
console.warn('[ngmd-api-gen] failed to load ngmd.api.ts:', err);
68-
return null;
69-
}
70-
}
71-
72-
function ensureProject(config: ApiConfig): Project {
73-
if (project) return project;
74-
project = new Project({
75-
tsConfigFilePath: existsSync(join(root, 'tsconfig.json'))
76-
? join(root, 'tsconfig.json')
77-
: undefined,
78-
skipAddingFilesFromTsConfig: true,
79-
});
80-
project.addSourceFilesAtPaths([
81-
...config.scope.map((pattern) => posix.join(root, pattern)),
82-
...(config.exclude ?? []).map((pattern) => '!' + posix.join(root, pattern)),
83-
]);
84-
return project;
85-
}
86-
8744
function extractRecords(config: ApiConfig): SymbolRecord[] {
88-
if (recordsMemo) return recordsMemo;
89-
const proj = ensureProject(config);
90-
const records: SymbolRecord[] = [];
91-
const seen = new Set<string>();
92-
const badgeTags = new Set(config.badgesFromJsDoc ?? []);
93-
94-
for (const sourceFile of proj.getSourceFiles()) {
95-
for (const [exportName, declarations] of sourceFile.getExportedDeclarations()) {
96-
const decls = declarations.filter((d) => symbolKindOf(d));
97-
const first = decls[0];
98-
if (!first) continue;
99-
const declFile = first.getSourceFile();
100-
if (declFile.isInNodeModules() || declFile.isDeclarationFile()) continue;
101-
const kind = symbolKindOf(first)!;
102-
const name =
103-
exportName === 'default'
104-
? ((first as {getName?: () => string | undefined}).getName?.() ?? exportName)
105-
: exportName;
106-
const filePath = posix.relative(root, declFile.getFilePath());
107-
const key = `${filePath}:${first.getStart()}:${name}`;
108-
if (seen.has(key)) continue;
109-
seen.add(key);
110-
111-
const jsDocsPerDecl = decls.map((d) => {
112-
const host = jsDocHostFor(d);
113-
return Node.isJSDocable(host) ? host.getJsDocs() : [];
114-
});
115-
const jsDocs = jsDocsPerDecl.flat();
116-
const description =
117-
jsDocsPerDecl
118-
.find((docs) => docs.length)
119-
?.at(-1)
120-
?.getDescription()
121-
.trim() ?? '';
122-
const tags = jsDocs.flatMap((d) => d.getTags().map((t) => t.getTagName()));
123-
const badges = [...new Set(tags.filter((t) => badgeTags.has(t)))];
124-
125-
records.push({
126-
kind,
127-
name,
128-
filePath,
129-
line: first.getStartLineNumber(),
130-
signature: signatureOf(decls),
131-
description,
132-
badges,
133-
group: groupNameFor(filePath, config.groupBy ?? 'directory', kind),
134-
});
135-
}
136-
}
137-
138-
recordsMemo = records;
139-
return records;
45+
project ??= createApiProject(root, config);
46+
recordsMemo ??= extractApiRecords(root, config, project);
47+
return recordsMemo;
14048
}
14149

14250
return {
@@ -194,6 +102,109 @@ export function apiGenPlugin(): Plugin {
194102
}
195103
}
196104

105+
function readApiConfig(root: string): ApiConfig | null {
106+
const path = posix.join(root, 'ngmd.api.ts');
107+
if (!existsSync(path)) return null;
108+
try {
109+
const proj = new Project({
110+
compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext},
111+
});
112+
const sourceFile = proj.addSourceFileAtPath(path);
113+
// We can't trivially evaluate the TS without a runtime; instead lift
114+
// the literal passed to `defineApi(...)` via AST traversal. For the
115+
// skeleton, every supported field is read as a literal so static
116+
// extraction is enough. Read the `export default` expression directly
117+
// rather than the first `CallExpression` in the file — otherwise any
118+
// helper call before the default export (even a harmless one) would
119+
// be parsed as the config.
120+
const exportAssignment = sourceFile.getExportAssignment((ea) => !ea.isExportEquals());
121+
if (!exportAssignment) return null;
122+
const callExpr = exportAssignment.getExpression().asKind(ts.SyntaxKind.CallExpression);
123+
if (!callExpr) return null;
124+
const literal = callExpr.getArguments()[0];
125+
if (!literal || !literal.asKind(ts.SyntaxKind.ObjectLiteralExpression)) return null;
126+
return parseLiteralAsConfig(literal as never);
127+
} catch (err) {
128+
console.warn('[ngmd-api-gen] failed to load ngmd.api.ts:', err);
129+
return null;
130+
}
131+
}
132+
133+
function createApiProject(root: string, config: ApiConfig): Project {
134+
const project = new Project({
135+
tsConfigFilePath: existsSync(join(root, 'tsconfig.json'))
136+
? join(root, 'tsconfig.json')
137+
: undefined,
138+
skipAddingFilesFromTsConfig: true,
139+
});
140+
project.addSourceFilesAtPaths([
141+
...config.scope.map((pattern) => posix.join(root, pattern)),
142+
...(config.exclude ?? []).map((pattern) => '!' + posix.join(root, pattern)),
143+
]);
144+
return project;
145+
}
146+
147+
export function apiRoutes(root: string): Array<{route: string; file: string}> {
148+
const config = readApiConfig(root);
149+
if (!config) return [];
150+
return extractApiRecords(root, config, createApiProject(root, config)).map((record) => ({
151+
route: `/api/${record.group}/${record.name}`,
152+
file: record.filePath,
153+
}));
154+
}
155+
156+
function extractApiRecords(root: string, config: ApiConfig, proj: Project): SymbolRecord[] {
157+
const records: SymbolRecord[] = [];
158+
const seen = new Set<string>();
159+
const badgeTags = new Set(config.badgesFromJsDoc ?? []);
160+
161+
for (const sourceFile of proj.getSourceFiles()) {
162+
for (const [exportName, declarations] of sourceFile.getExportedDeclarations()) {
163+
const decls = declarations.filter((d) => symbolKindOf(d));
164+
const first = decls[0];
165+
if (!first) continue;
166+
const declFile = first.getSourceFile();
167+
if (declFile.isInNodeModules() || declFile.isDeclarationFile()) continue;
168+
const kind = symbolKindOf(first)!;
169+
const name =
170+
exportName === 'default'
171+
? ((first as {getName?: () => string | undefined}).getName?.() ?? exportName)
172+
: exportName;
173+
const filePath = posix.relative(root, declFile.getFilePath());
174+
const key = `${filePath}:${first.getStart()}:${name}`;
175+
if (seen.has(key)) continue;
176+
seen.add(key);
177+
178+
const jsDocsPerDecl = decls.map((d) => {
179+
const host = jsDocHostFor(d);
180+
return Node.isJSDocable(host) ? host.getJsDocs() : [];
181+
});
182+
const jsDocs = jsDocsPerDecl.flat();
183+
const description =
184+
jsDocsPerDecl
185+
.find((docs) => docs.length)
186+
?.at(-1)
187+
?.getDescription()
188+
.trim() ?? '';
189+
const tags = jsDocs.flatMap((d) => d.getTags().map((t) => t.getTagName()));
190+
const badges = [...new Set(tags.filter((t) => badgeTags.has(t)))];
191+
192+
records.push({
193+
kind,
194+
name,
195+
filePath,
196+
line: first.getStartLineNumber(),
197+
signature: signatureOf(decls),
198+
description,
199+
badges,
200+
group: groupNameFor(filePath, config.groupBy ?? 'directory', kind),
201+
});
202+
}
203+
}
204+
205+
return records;
206+
}
207+
197208
function symbolKindOf(decl: Node): SymbolKind | null {
198209
if (Node.isClassDeclaration(decl)) return 'class';
199210
if (Node.isInterfaceDeclaration(decl)) return 'interface';

‎apps/docs/plugin-utils.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import {execFileSync} from 'node:child_process';
2-
import {readdirSync, realpathSync, statSync} from 'node:fs';
2+
import {readFileSync, readdirSync, realpathSync, statSync} from 'node:fs';
33
import {isAbsolute, join, relative, resolve} from 'node:path';
44
import frontMatter from 'front-matter';
5+
import {apiRoutes} from './api-gen.plugin.ts';
56

67
export {createSlugger, headingText, slugify} from './src/app/utils/heading-slug.ts';
78

@@ -87,6 +88,42 @@ function pageRouteSegments(rel: string): string[] | null {
8788
return trimmed.split(/[/.]/).filter((s) => s !== 'index' && !/^\(.*\)$/.test(s));
8889
}
8990

91+
export interface SiteRoute {
92+
route: string;
93+
file: string;
94+
noIndex: boolean;
95+
}
96+
97+
export function siteRoutes(root: string): SiteRoute[] {
98+
const routes = new Map<string, SiteRoute>();
99+
try {
100+
for (const file of walkPageFiles(join(root, 'src/app/pages'), root)) {
101+
const route = routeFromPagePath(file);
102+
if (route) routes.set(route, {route, file, noIndex: false});
103+
}
104+
} catch {
105+
// src/app/pages missing
106+
}
107+
try {
108+
for (const [file, route] of walkContentFiles(join(root, 'src/content'), root)) {
109+
const noIndex = isNoIndex(
110+
parseFrontmatter(readFileSync(join(root, file), 'utf8')).attributes,
111+
);
112+
if (!noIndex || !routes.has(route)) routes.set(route, {route, file, noIndex});
113+
}
114+
} catch {
115+
// src/content missing
116+
}
117+
for (const {route, file} of apiRoutes(root)) {
118+
if (!routes.has(route)) routes.set(route, {route, file, noIndex: false});
119+
}
120+
return [...routes.values()].sort((a, b) => a.route.localeCompare(b.route));
121+
}
122+
123+
export function prerenderRoutes(root: string): string[] {
124+
return [...siteRoutes(root).map((r) => r.route), '/404.html'];
125+
}
126+
90127
/**
91128
* Last-commit date for `file` (YYYY-MM-DD), via `git log -1 --format=%cs`.
92129
* Falls back to file mtime when the file is uncommitted, and to `''`
@@ -154,6 +191,8 @@ export function withoutCode(markdown: string): string {
154191
.replace(/(`+)[^\n]*?\1/g, ' ');
155192
}
156193

194+
export const siteRoot = import.meta.dirname;
195+
157196
/**
158197
* Resolve `path` against `root`, following symlinks, and throw when the
159198
* real target lies outside the real root.

‎apps/docs/sitemap.plugin.ts‎

Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
1-
import {readFileSync, statSync} from 'node:fs';
2-
import {join} from 'node:path';
31
import type {Plugin} from 'vite';
4-
import {
5-
gitDate,
6-
isNoIndex,
7-
parseFrontmatter,
8-
routeFromPagePath,
9-
walkContentFiles,
10-
walkPageFiles,
11-
} from './plugin-utils.ts';
2+
import {gitDate, siteRoutes} from './plugin-utils.ts';
123

134
/**
145
* Emits `sitemap.xml` and `robots.txt` into the client build output.
156
*
16-
* Discovery mirrors the page-meta plugin: walks `src/app/pages/*.page.ts`
17-
* and `src/content/**\/*.md`, pulls each file's last commit date via
18-
* `git log -1 --format=%cs` to populate `<lastmod>`, falls back to mtime
7+
* Routes come from `siteRoutes` in plugin-utils, the same list the build
8+
* prerenders: `src/app/pages/*.page.ts`, `src/content/**\/*.md` and the API
9+
* symbol pages, minus `noIndex` pages. Each file's last commit date via
10+
* `git log -1 --format=%cs` populates `<lastmod>`, falling back to mtime
1911
* for uncommitted files.
2012
*
2113
* Versioning is per-deployment (each docs version is its own site under the
@@ -47,29 +39,8 @@ export function sitemapPlugin(opts: {siteUrl: string}): Plugin {
4739
},
4840
generateBundle() {
4941
const entries = new Map<string, string>();
50-
51-
try {
52-
const pageFiles = walkPageFiles(join(root, 'src/app/pages'), root);
53-
for (const rel of pageFiles) {
54-
const route = routeFromPagePath(rel);
55-
if (!route) continue;
56-
entries.set(route, gitDate(rel, root, today));
57-
}
58-
} catch {
59-
// src/app/pages missing — fine
60-
}
61-
62-
const contentDir = join(root, 'src/content');
63-
try {
64-
statSync(contentDir);
65-
for (const [rel, route] of walkContentFiles(contentDir, root)) {
66-
if (isNoIndex(parseFrontmatter(readFileSync(join(root, rel), 'utf8')).attributes)) {
67-
continue;
68-
}
69-
entries.set(route, gitDate(rel, root, today));
70-
}
71-
} catch {
72-
// src/content missing — skip
42+
for (const {route, file, noIndex} of siteRoutes(root)) {
43+
if (!noIndex) entries.set(route, gitDate(file, root, today));
7344
}
7445

7546
const urls = [...entries.entries()]

‎apps/docs/vite.config.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {searchIndexPlugin} from './search-index.plugin.ts';
1313
import {rawMdPlugin} from './raw-md.plugin.ts';
1414
import {varsPlugin} from './vars.plugin.ts';
1515
import {apiGenPlugin} from './api-gen.plugin.ts';
16-
import {withoutCode} from './plugin-utils.ts';
16+
import {prerenderRoutes, withoutCode} from './plugin-utils.ts';
1717
import config from './src/ngmd.config.ts';
1818

1919
/**
@@ -90,6 +90,9 @@ export default defineConfig(async () => ({
9090
searchIndexPlugin(),
9191
apiGenPlugin(),
9292
analog({
93+
prerender: {
94+
routes: async () => prerenderRoutes(import.meta.dirname),
95+
},
9396
apiPrefix: '_server',
9497
content: {
9598
highlighter: 'shiki',

0 commit comments

Comments
 (0)