Skip to content

Commit b3a6c71

Browse files
committed
fixup!
1 parent 6b744b2 commit b3a6c71

15 files changed

Lines changed: 339 additions & 105 deletions

File tree

‎.changeset/vite-web-generator.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
'@node-core/doc-kit': minor
33
---
44

5-
Rebuild the `web` generator around Vite 8.1
5+
Make the `web` generator bundler-neutral through a custom adapter contract,
6+
with Vite 8.1 provided as the default adapter.

‎src/generators/web/README.md‎

Lines changed: 80 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
# `web` Generator
22

3-
The `web` generator transforms JSX AST entries into complete web bundles. Vite
4-
builds server-rendered HTML and hashed client-side JavaScript, CSS, and imported
5-
assets, then writes the complete static site to `output`. The generator is
6-
output-only and does not return an in-memory copy of its HTML or CSS.
3+
The `web` generator transforms JSX AST entries into complete web bundles. Its
4+
bundler adapter builds server-rendered HTML and client-side JavaScript, CSS, and
5+
imported assets, then writes the complete static site to `output`. Vite is the
6+
default adapter, but projects can supply an adapter for webpack or another
7+
bundler. The generator is output-only and does not return an in-memory copy of
8+
its HTML or CSS.
79

810
## Configuring
911

1012
The `web` generator accepts the following configuration options:
1113

1214
| Name | Type | Default | Description |
1315
| ----------------- | ------------ | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
14-
| `output` | `string` | Required | The directory where HTML and Vite's hashed client output are written |
16+
| `output` | `string` | Required | The directory where HTML and bundled client output are written |
1517
| `templatePath` | `string` | `'template.html'` | Path to the HTML template file |
1618
| `project` | `string` | `'Node.js'` | Project name used in page titles and the version selector |
1719
| `title` | `string` | `'{project} v{version} Documentation'` | Title template for HTML pages (supports `{project}`, `{version}`) |
@@ -21,9 +23,9 @@ The `web` generator accepts the following configuration options:
2123
| `remoteConfigUrl` | `string` | `'https://nodejs.org/site.json'` | URL fetched client-side at runtime for remote site config (currently used to power the announcement banner) |
2224
| `head` | `object` | See below | Configurable `<meta>`, `<link>`, and raw markup for the document head |
2325
| `imports` | `object` | See below | Object mapping `#theme/` aliases to component paths for customization |
24-
| `virtualImports` | `object` | `{}` | Additional virtual module mappings merged into both Vite builds |
26+
| `virtualImports` | `object` | `{}` | Additional virtual module mappings supplied to the server and client builds |
2527
| `components` | `object` | `{}` | Maps JSX tag names to component imports, enabling JSX-in-MDX (see below) |
26-
| `vite` | `UserConfig` | `{}` | Vite configuration merged into the client and SSR builds (see below) |
28+
| `bundler` | `WebBundler` | Vite adapter | Adapter that renders server entries and writes the client and HTML output (see below) |
2729

2830
### `head`
2931

@@ -69,20 +71,74 @@ export default {
6971
> via `head`, including `og:title` (which mirrors the per-page title) and
7072
> `og:type`. The UI stylesheet bundles its fonts locally.
7173
72-
### Custom Vite options
74+
### Bundler adapters
7375

74-
The `vite` object is merged into both production builds. This supports Vite
75-
plugins, aliases, `define`, asset options, and native Lightning CSS settings.
76-
Use `import.meta.env.SSR` inside application code or plugin transforms when
77-
behavior must differ between the SSR and browser builds.
76+
The `bundler` option accepts a small Doc Kit adapter rather than configuration
77+
for a particular build system:
78+
79+
| Method | Responsibility |
80+
| ------------ | ----------------------------------------------------------------------------------------- |
81+
| `getEntryId` | Return the module identifier placed in the populated HTML for an API name |
82+
| `render` | Bundle and execute the server `entries`, returning a `Map` of API name to rendered HTML |
83+
| `build` | Bundle the client `entries`, process the populated `pages`, and write the complete output |
84+
85+
Both `render` and `build` receive `{ entries, virtualImports, config }`; `build`
86+
also receives `pages`. Entry maps use `${api}.jsx` keys, rendered server results
87+
use `api` keys, and page maps use output-relative HTML file names. `config` is
88+
the resolved web configuration.
89+
90+
The adapter must compile the generated Preact JSX and CSS imports and resolve
91+
the supplied theme aliases and virtual modules. The generated `#theme/config`
92+
module exports `server` as `true` for the server build and `false` for the
93+
client build.
94+
95+
A webpack integration can live entirely in project configuration without
96+
adding webpack to Doc Kit:
97+
98+
```js
99+
// webpack-bundler.mjs
100+
export const createWebpackBundler = webpackOptions => ({
101+
getEntryId: api => `virtual:doc-kit/client/${api}.jsx`,
102+
103+
async render({ entries, virtualImports, config }) {
104+
// Materialize or load the in-memory modules, run webpack's server target,
105+
// execute each emitted entry, and return Map<api, renderedHtml>.
106+
},
107+
108+
async build({ entries, virtualImports, pages, config }) {
109+
// Run webpack's browser target, inject its emitted assets into `pages`,
110+
// and write the HTML and assets to config.output.
111+
},
112+
});
113+
```
78114

79115
```js
80116
// doc-kit.config.mjs
117+
import { createWebpackBundler } from './webpack-bundler.mjs';
118+
119+
export default {
120+
web: {
121+
bundler: createWebpackBundler({
122+
// Project-owned webpack configuration.
123+
}),
124+
},
125+
};
126+
```
127+
128+
### Vite adapter
129+
130+
When `bundler` is omitted, the generator imports and uses
131+
`createViteBundler()` automatically. To customize Vite, import the adapter
132+
directly and pass Vite's `UserConfig` to it:
133+
134+
```js
135+
// doc-kit.config.mjs
136+
import { createViteBundler } from '@node-core/doc-kit/src/generators/web/bundlers/vite.mjs';
81137
import myVitePlugin from './my-vite-plugin.mjs';
82138

83139
export default {
84140
web: {
85-
vite: {
141+
bundler: createViteBundler({
86142
plugins: [myVitePlugin()],
87143
define: {
88144
'process.env.ANALYTICS_ID': JSON.stringify('UA-XXXXX'),
@@ -99,7 +155,7 @@ export default {
99155
},
100156
},
101157
},
102-
},
158+
}),
103159
},
104160
};
105161
```
@@ -112,12 +168,13 @@ those fields are replaced after configuration is merged. User plugins are
112168
registered after the generator's virtual-module plugin; other Vite options are
113169
preserved.
114170

115-
Vite manifests are optional. Set `web.vite.build.manifest` to `true` or a file
116-
name when another tool needs one. The generated HTML already references the
117-
correct hashed scripts, stylesheets, imported assets, and module preloads.
171+
Vite manifests are optional. Pass `build: { manifest: true }` or a manifest file
172+
name to `createViteBundler` when another tool needs one. The generated HTML
173+
already references the correct hashed scripts, stylesheets, imported assets,
174+
and module preloads.
118175

119176
Function-valued plugins and hooks are supported because the `web` generator
120-
runs on the main thread and does not serialize this configuration to a worker.
177+
runs on the main thread and does not serialize the bundler to a worker.
121178

122179
### Default `imports`
123180

@@ -218,6 +275,7 @@ All scalar (non-object) configuration values are automatically exported. The def
218275
| `baseURL` | `string` | Base URL for the documentation site (used when `useAbsoluteURLs` is `true`) |
219276
| `languageDisplayNameMap` | `Map<string, string>` | Shiki language alias → display name map for code blocks |
220277
| `remoteConfigUrl` | `string` | Mirrors the configured `remoteConfigUrl` (fetched client-side by `RemoteLoadableBanner` to load announcement banners) |
278+
| `server` | `boolean` | Whether the current bundle is the server build |
221279

222280
### Usage in custom components
223281

@@ -264,7 +322,7 @@ The HTML template file (set via `templatePath`) uses JavaScript template literal
264322
| ------------------ | -------- | ----------------------------------------------------------------- |
265323
| `title` | `string` | Fully resolved page title (e.g. `'File system \| Node.js v22.x'`) |
266324
| `dehydrated` | `string` | Server-rendered HTML for the page content |
267-
| `entrypoint` | `string` | Virtual Vite module for this page's client hydration |
325+
| `entrypoint` | `string` | Adapter-provided module identifier for this page's hydration |
268326
| `speculationRules` | `string` | Speculation rules JSON for prefetching |
269327
| `themeScript` | `string` | Inline script that applies the saved theme before paint |
270328
| `root` | `string` | Relative or absolute path to the site root |
@@ -279,6 +337,6 @@ Since the template supports arbitrary JS expressions, you can use conditionals a
279337
<script type="module" src="${entrypoint}"></script>
280338
```
281339

282-
Vite processes each populated template as an HTML entry. It replaces the
283-
virtual `entrypoint` with the hashed client script and injects that page's
284-
stylesheets and module preloads in their required order.
340+
The configured adapter processes each populated page. It must replace or
341+
resolve `entrypoint`, include that page's scripts and stylesheets, and write the
342+
final HTML.

‎src/generators/web/__tests__/generate.test.mjs‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import assert from 'node:assert/strict';
2-
import { mkdtemp, readFile, rm } from 'node:fs/promises';
2+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
33
import { tmpdir } from 'node:os';
4-
import { join } from 'node:path';
4+
import { dirname, join } from 'node:path';
55
import { describe, it } from 'node:test';
66

77
import { jsx, toJs } from 'estree-util-to-js';
88

99
import { setConfig } from '../../../utils/configuration/index.mjs';
1010
import buildContent from '../../jsx-ast/utils/buildContent.mjs';
1111
import { buildNotFoundPage } from '../../jsx-ast/utils/synthetic/404.mjs';
12+
import { createViteBundler } from '../bundlers/vite.mjs';
1213
import { generate } from '../generate.mjs';
1314

1415
/**
@@ -64,7 +65,7 @@ const createTestConfiguration = async context => {
6465
};
6566

6667
describe('web generate', () => {
67-
it('writes Vite HTML entries and omits View As links for synthetic pages', async context => {
68+
it('writes bundled HTML and omits View As links for synthetic pages', async context => {
6869
const { output } = await createTestConfiguration(context);
6970
const fs = createEntry('fs', 'File system');
7071
fs.path = '/api/fs';
@@ -128,7 +129,7 @@ describe('web generate', () => {
128129

129130
it('applies configured Vite plugins', async context => {
130131
const { config, output } = await createTestConfiguration(context);
131-
config.web.vite = {
132+
config.web.bundler = createViteBundler({
132133
plugins: [
133134
{
134135
name: 'test-html-transform',
@@ -143,12 +144,65 @@ describe('web generate', () => {
143144
},
144145
},
145146
],
146-
};
147+
});
147148

148149
const fs = createEntry('fs', 'File system');
149150
await generate([toCodeItem(await buildContent([fs], fs))]);
150151
const html = await readFile(join(output, 'fs.html'), 'utf8');
151152

152153
assert.match(html, /name=vite-plugin/);
153154
});
155+
156+
it('uses a custom bundler adapter for server and client output', async context => {
157+
const { config, output } = await createTestConfiguration(context);
158+
const calls = [];
159+
160+
config.web.bundler = {
161+
getEntryId(api) {
162+
calls.push(`entry:${api}`);
163+
return `/custom/${api}.js`;
164+
},
165+
166+
async render({ entries, virtualImports, config: receivedConfig }) {
167+
calls.push('server');
168+
assert.strictEqual(receivedConfig, config.web);
169+
assert.ok(entries.has('fs.jsx'));
170+
assert.match(virtualImports['#theme/config'], /export const pages/);
171+
assert.match(
172+
virtualImports['#theme/config'],
173+
/export const server = true;/
174+
);
175+
176+
return new Map([
177+
['fs', '<article data-custom-ssr>Custom SSR</article>'],
178+
]);
179+
},
180+
181+
async build({ entries, virtualImports, pages, config: receivedConfig }) {
182+
calls.push('client');
183+
assert.strictEqual(receivedConfig, config.web);
184+
assert.ok(entries.has('fs.jsx'));
185+
assert.match(
186+
virtualImports['#theme/config'],
187+
/export const server = false;/
188+
);
189+
190+
await Promise.all(
191+
[...pages].map(async ([fileName, html]) => {
192+
const path = join(output, fileName);
193+
await mkdir(dirname(path), { recursive: true });
194+
await writeFile(path, html);
195+
})
196+
);
197+
},
198+
};
199+
200+
const fs = createEntry('fs', 'File system');
201+
await generate([toCodeItem(await buildContent([fs], fs))]);
202+
const html = await readFile(join(output, 'fs.html'), 'utf8');
203+
204+
assert.match(html, /data-custom-ssr/);
205+
assert.match(html, /src="\/custom\/fs\.js"/);
206+
assert.deepStrictEqual(calls, ['server', 'entry:fs', 'client']);
207+
});
154208
});

src/generators/web/utils/__tests__/vite.test.mjs renamed to src/generators/web/bundlers/__tests__/vite.test.mjs

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
import {
1212
createVirtualModulesPlugin,
1313
createViteConfig,
14-
renderServerEntries,
14+
render,
1515
} from '../vite.mjs';
1616

1717
const output = join(tmpdir(), 'doc-kit-vite-test-output');
@@ -49,7 +49,7 @@ describe('Vite virtual modules', () => {
4949

5050
describe('Vite configuration', () => {
5151
it('uses the generated client entries and configured output', () => {
52-
getConfig('web').vite = {
52+
const vite = {
5353
base: '/custom/',
5454
build: {
5555
outDir: 'custom-output',
@@ -65,6 +65,8 @@ describe('Vite configuration', () => {
6565
sources: new Map(),
6666
input,
6767
server: false,
68+
config: getConfig('web'),
69+
vite,
6870
});
6971

7072
assert.strictEqual(config.base, './');
@@ -74,7 +76,7 @@ describe('Vite configuration', () => {
7476
});
7577

7678
it('keeps the temporary SSR build self-contained', () => {
77-
getConfig('web').vite = {
79+
const vite = {
7880
ssr: {
7981
external: ['preact'],
8082
noExternal: false,
@@ -94,6 +96,8 @@ describe('Vite configuration', () => {
9496
input,
9597
server: true,
9698
serverOutDir: serverOutput,
99+
config: getConfig('web'),
100+
vite,
97101
});
98102

99103
assert.strictEqual(config.build.ssr, true);
@@ -107,22 +111,23 @@ describe('Vite configuration', () => {
107111

108112
describe('Vite SSR temporary output', () => {
109113
it('always removes temporary output after a renderer throws', async () => {
110-
getConfig('web').vite = {};
111114
const temporaryDirectory = await mkdtemp(
112115
join(tmpdir(), 'doc-kit-vite-cleanup-test-')
113116
);
114117

115118
await assert.rejects(
116-
renderServerEntries(
117-
new Map([
119+
render({
120+
entries: new Map([
118121
[
119122
'broken.jsx',
120123
'export default () => { throw new Error("render failed"); };',
121124
],
122125
]),
123-
{},
124-
async () => temporaryDirectory
125-
),
126+
virtualImports: {},
127+
config: getConfig('web'),
128+
vite: {},
129+
createTemporaryDirectory: async () => temporaryDirectory,
130+
}),
126131
/render failed/
127132
);
128133

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Returns the configured bundler or lazily creates the default Vite adapter.
3+
*
4+
* @param {import('../types').WebBundler|undefined} bundler
5+
* @returns {Promise<import('../types').WebBundler>}
6+
*/
7+
export const resolveBundler = async bundler => {
8+
if (bundler) {
9+
return bundler;
10+
}
11+
12+
const { createViteBundler } = await import('./vite.mjs');
13+
return createViteBundler();
14+
};

0 commit comments

Comments
 (0)