yaakdoc 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/bin/yaakdoc.js +4 -0
- package/config.schema.json +446 -0
- package/dist/cli.d.ts +5 -0
- package/dist/cli.js +343 -0
- package/dist/index.d.ts +118 -0
- package/dist/index.js +6 -0
- package/dist/open-C4Bh1af9.js +19 -0
- package/dist/preview-Ba1BfVZV.js +659 -0
- package/dist/site-X7q76qYf.js +609 -0
- package/dist/static.d.ts +2 -0
- package/dist/static.js +1 -0
- package/dist/version-Bwv0ibuY.d.ts +133 -0
- package/package.json +92 -3
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
import { a as matchRoute, c as VERSION, h as resolveFrom, i as writeSite, m as ENGINE_DIR, p as ENGINE_ANCHOR, r as withBase, s as resolveContext, t as assertSafeOutDir, u as resolveTheme } from "./site-X7q76qYf.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { build, createServer, isRunnableDevEnvironment, searchForWorkspaceRoot } from "vite";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { createReadStream, existsSync, readFileSync, readdirSync } from "node:fs";
|
|
9
|
+
import { loadConfig } from "@yaakdoc/config/node";
|
|
10
|
+
import { escapeRegExp } from "@yaakdoc/core";
|
|
11
|
+
import { detectExport } from "@yaakdoc/core/node";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { createServer as createServer$1 } from "node:http";
|
|
14
|
+
import { consola } from "consola";
|
|
15
|
+
import colors from "picocolors";
|
|
16
|
+
import { glob } from "tinyglobby";
|
|
17
|
+
import sirv from "sirv";
|
|
18
|
+
//#region src/node/plugin.ts
|
|
19
|
+
const VIRTUAL_SERVER = "virtual:yaakdoc/entry-server";
|
|
20
|
+
/** The SSR entry exports `render` (see `RenderEntry`). */
|
|
21
|
+
const VIRTUAL_CLIENT = "virtual:yaakdoc/entry-client";
|
|
22
|
+
const RESOLVED = (id) => `\0${id}`;
|
|
23
|
+
const isBare = (id) => !id.startsWith(".") && !id.startsWith("/") && !id.startsWith("\0") && !/^[a-z]+:/i.test(id) && !id.startsWith("@/");
|
|
24
|
+
const json = (value) => JSON.stringify(value);
|
|
25
|
+
const REACT_RE = /^react(-dom)?(\/|$)/;
|
|
26
|
+
const CJS_PREFIX = "\0yaakdoc-cjs:";
|
|
27
|
+
const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
|
|
28
|
+
/** ESM module re-exporting a CommonJS module required from yaakdoc's installation. */
|
|
29
|
+
function cjsWrapper(specifier) {
|
|
30
|
+
const mod = createRequire(ENGINE_ANCHOR)(specifier);
|
|
31
|
+
const names = Object.keys(mod).filter((name) => name !== "default" && IDENTIFIER_RE.test(name));
|
|
32
|
+
return [
|
|
33
|
+
`import { createRequire } from "node:module";`,
|
|
34
|
+
`const mod = createRequire(${json(ENGINE_ANCHOR)})(${json(specifier)});`,
|
|
35
|
+
"export default mod;",
|
|
36
|
+
names.length > 0 ? `export const { ${names.join(", ")} } = mod;` : ""
|
|
37
|
+
].join("\n");
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The yaakdoc Vite plugin: virtual SSR/client entries, theme-scoped `@/` alias, and fallback
|
|
41
|
+
* resolution of theme dependencies from the yaakdoc installation (so ejected themes and `npx` work
|
|
42
|
+
* without installing anything in the project).
|
|
43
|
+
*/
|
|
44
|
+
function yaakdocPlugin(getContext, onSsrUpdate) {
|
|
45
|
+
return {
|
|
46
|
+
name: "yaakdoc",
|
|
47
|
+
enforce: "pre",
|
|
48
|
+
async resolveId(source, importer, options) {
|
|
49
|
+
if (source === "virtual:yaakdoc/entry-server" || source === "virtual:yaakdoc/entry-client") return RESOLVED(source);
|
|
50
|
+
const { theme } = getContext();
|
|
51
|
+
if (source.startsWith("@/") && importer?.startsWith(theme.root + sep)) return this.resolve(join(theme.root, "src", source.slice(2)), importer, {
|
|
52
|
+
...options,
|
|
53
|
+
skipSelf: true
|
|
54
|
+
});
|
|
55
|
+
if (!isBare(source)) return null;
|
|
56
|
+
const server = this.environment.config.consumer === "server";
|
|
57
|
+
const finish = (resolved) => {
|
|
58
|
+
if (!resolved) return null;
|
|
59
|
+
if (server) return REACT_RE.test(source) ? {
|
|
60
|
+
...resolved,
|
|
61
|
+
external: true
|
|
62
|
+
} : resolved;
|
|
63
|
+
return optimized(this.environment, resolved, options.scan);
|
|
64
|
+
};
|
|
65
|
+
if (REACT_RE.test(source) && server && this.environment.mode === "dev") return `${CJS_PREFIX}${source}`;
|
|
66
|
+
if (REACT_RE.test(source)) return finish(await this.resolve(source, ENGINE_ANCHOR, {
|
|
67
|
+
...options,
|
|
68
|
+
skipSelf: true
|
|
69
|
+
}));
|
|
70
|
+
if (!(!importer || importer.startsWith("\0"))) {
|
|
71
|
+
const resolved = await this.resolve(source, importer, {
|
|
72
|
+
...options,
|
|
73
|
+
skipSelf: true
|
|
74
|
+
});
|
|
75
|
+
if (resolved) return finish(resolved);
|
|
76
|
+
}
|
|
77
|
+
for (const fallback of [
|
|
78
|
+
ENGINE_ANCHOR,
|
|
79
|
+
...theme.fallbackImporters,
|
|
80
|
+
join(theme.root, "package.json")
|
|
81
|
+
]) {
|
|
82
|
+
const resolved = await this.resolve(source, fallback, {
|
|
83
|
+
...options,
|
|
84
|
+
skipSelf: true
|
|
85
|
+
});
|
|
86
|
+
if (resolved) return finish(resolved);
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
},
|
|
90
|
+
load(id) {
|
|
91
|
+
if (id.startsWith(CJS_PREFIX)) return cjsWrapper(id.slice(13));
|
|
92
|
+
const context = getContext();
|
|
93
|
+
if (id === RESOLVED("virtual:yaakdoc/entry-server")) return [
|
|
94
|
+
`import theme from ${json(context.theme.entry)};`,
|
|
95
|
+
`import { renderPage } from "@yaakdoc/react/server";`,
|
|
96
|
+
"export function render(input) {",
|
|
97
|
+
" return renderPage({ theme, ...input });",
|
|
98
|
+
"}"
|
|
99
|
+
].join("\n");
|
|
100
|
+
if (id === RESOLVED("virtual:yaakdoc/entry-client")) return [
|
|
101
|
+
...styleEntries(context).map((style) => `import ${json(style)};`),
|
|
102
|
+
`import { hydrateIslands } from "@yaakdoc/react/client";`,
|
|
103
|
+
context.theme.client ? `import islands from ${json(context.theme.client)};` : `import { builtinIslands as islands } from "@yaakdoc/react/islands";`,
|
|
104
|
+
"hydrateIslands(islands);"
|
|
105
|
+
].join("\n");
|
|
106
|
+
return null;
|
|
107
|
+
},
|
|
108
|
+
hotUpdate({ modules, file }) {
|
|
109
|
+
if (this.environment.name !== "ssr" || modules.length === 0 || /\.css($|\?)/.test(file)) return;
|
|
110
|
+
onSsrUpdate?.();
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
|
|
115
|
+
const JS_RE = /\.(m?js|cjs)$/;
|
|
116
|
+
/**
|
|
117
|
+
* Dev only: maps a dependency in node_modules to its pre-bundled version.
|
|
118
|
+
*
|
|
119
|
+
* Vite skips dependency discovery for imports coming from inside node_modules – which is where
|
|
120
|
+
* yaakdoc and its theme live when run with `npx`. Such dependencies are registered here by absolute
|
|
121
|
+
* path (reusing an existing entry for the same file), so they are served pre-bundled as ESM.
|
|
122
|
+
*/
|
|
123
|
+
function optimized(environment, resolved, scan) {
|
|
124
|
+
const optimizer = environment.mode === "dev" ? environment.depsOptimizer : void 0;
|
|
125
|
+
if (!optimizer || scan || resolved.external) return resolved;
|
|
126
|
+
const file = resolved.id.split("?")[0];
|
|
127
|
+
if (!NODE_MODULES_RE.test(file) || !JS_RE.test(file) || optimizer.isOptimizedDepFile(file)) return resolved;
|
|
128
|
+
const { optimized: done, discovered } = optimizer.metadata;
|
|
129
|
+
const info = done[file] ?? discovered[file] ?? [...Object.values(done), ...Object.values(discovered)].find((dep) => dep.src === file) ?? optimizer.registerMissingImport(file, file);
|
|
130
|
+
return optimizer.getOptimizedDepId(info);
|
|
131
|
+
}
|
|
132
|
+
/** CSS entries loaded on every page: the theme's styles, then `branding.customCss`. */
|
|
133
|
+
function styleEntries(context) {
|
|
134
|
+
const { customCss } = context.config.branding;
|
|
135
|
+
return [...context.theme.styles, ...customCss ? [customCss] : []];
|
|
136
|
+
}
|
|
137
|
+
const nodeModulesRoot = (file) => {
|
|
138
|
+
const index = file.lastIndexOf(`${sep}node_modules${sep}`);
|
|
139
|
+
return index === -1 ? dirname(file) : file.slice(0, index + `${sep}node_modules`.length);
|
|
140
|
+
};
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/node/vite.ts
|
|
143
|
+
/** Base Vite config shared by the dev server and builds. */
|
|
144
|
+
async function createViteConfig(getContext, mode, extra = {}) {
|
|
145
|
+
const context = getContext();
|
|
146
|
+
const themePlugins = await context.theme.definition.vitePlugins?.() ?? [];
|
|
147
|
+
const publicDir = join(context.root, "public");
|
|
148
|
+
const cacheDir = existsSync(join(context.root, "node_modules")) ? join(context.root, "node_modules", ".vite-yaakdoc") : join(tmpdir(), "yaakdoc-vite", createHash("sha256").update(context.root).digest("hex").slice(0, 12));
|
|
149
|
+
return {
|
|
150
|
+
configFile: false,
|
|
151
|
+
envDir: false,
|
|
152
|
+
root: context.root,
|
|
153
|
+
base: context.config.base,
|
|
154
|
+
mode,
|
|
155
|
+
logLevel: extra.logLevel ?? "warn",
|
|
156
|
+
clearScreen: false,
|
|
157
|
+
publicDir: existsSync(publicDir) ? publicDir : false,
|
|
158
|
+
cacheDir,
|
|
159
|
+
plugins: [yaakdocPlugin(getContext, extra.onSsrUpdate), ...themePlugins],
|
|
160
|
+
resolve: { alias: styleAliases(context) },
|
|
161
|
+
oxc: { jsx: {
|
|
162
|
+
runtime: "automatic",
|
|
163
|
+
importSource: "react"
|
|
164
|
+
} },
|
|
165
|
+
ssr: { noExternal: [
|
|
166
|
+
"@yaakdoc/react",
|
|
167
|
+
/^@yaakdoc\/theme-/,
|
|
168
|
+
/^yaakdoc-theme-/
|
|
169
|
+
] },
|
|
170
|
+
optimizeDeps: { entries: [] },
|
|
171
|
+
build: { rolldownOptions: { onLog(level, log, handler) {
|
|
172
|
+
if (log.code === "MODULE_LEVEL_DIRECTIVE") return;
|
|
173
|
+
handler(level, log);
|
|
174
|
+
} } },
|
|
175
|
+
server: { fs: { allow: [
|
|
176
|
+
searchForWorkspaceRoot(context.root),
|
|
177
|
+
cacheDir,
|
|
178
|
+
context.theme.root,
|
|
179
|
+
nodeModulesRoot(ENGINE_DIR),
|
|
180
|
+
...context.theme.fallbackImporters.map(nodeModulesRoot)
|
|
181
|
+
] } }
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* CSS `@import "pkg"` is resolved by Vite's CSS resolver (aliases only, no plugins). For CSS packages
|
|
186
|
+
* an ejected theme doesn't have installed (e.g. `tailwindcss`), alias them to yaakdoc's copy.
|
|
187
|
+
*/
|
|
188
|
+
function styleAliases(context) {
|
|
189
|
+
const themeAnchor = join(context.theme.root, "package.json");
|
|
190
|
+
const aliases = [];
|
|
191
|
+
const seen = /* @__PURE__ */ new Set();
|
|
192
|
+
for (const fallback of context.theme.fallbackImporters) {
|
|
193
|
+
let dependencies = [];
|
|
194
|
+
try {
|
|
195
|
+
dependencies = Object.keys(JSON.parse(readFileSync(fallback, "utf8")).dependencies ?? {});
|
|
196
|
+
} catch {}
|
|
197
|
+
for (const name of dependencies) {
|
|
198
|
+
if (seen.has(name)) continue;
|
|
199
|
+
seen.add(name);
|
|
200
|
+
if (resolveFrom(`${name}/package.json`, themeAnchor)) continue;
|
|
201
|
+
const pkgJson = resolveFrom(`${name}/package.json`, fallback);
|
|
202
|
+
if (!pkgJson) continue;
|
|
203
|
+
const pkg = JSON.parse(readFileSync(pkgJson, "utf8"));
|
|
204
|
+
const root = pkg.exports?.["."];
|
|
205
|
+
const style = typeof root === "object" && root && "style" in root ? root.style : pkg.style;
|
|
206
|
+
if (typeof style === "string") aliases.push({
|
|
207
|
+
find: new RegExp(`^${escapeRegExp(name)}$`),
|
|
208
|
+
replacement: join(dirname(pkgJson), style)
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return aliases;
|
|
213
|
+
}
|
|
214
|
+
//#endregion
|
|
215
|
+
//#region src/node/build.ts
|
|
216
|
+
const SSR_DIR = ".yaakdoc-ssr";
|
|
217
|
+
/** Builds the static site: client assets, prerendered HTML for every route, Markdown and llms.txt. */
|
|
218
|
+
async function build$1(options = {}) {
|
|
219
|
+
const previousEnv = process.env.NODE_ENV;
|
|
220
|
+
process.env.NODE_ENV = "production";
|
|
221
|
+
try {
|
|
222
|
+
return await buildWithContext(await resolveContext(options));
|
|
223
|
+
} finally {
|
|
224
|
+
if (previousEnv === void 0) delete process.env.NODE_ENV;
|
|
225
|
+
else process.env.NODE_ENV = previousEnv;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async function buildWithContext(context) {
|
|
229
|
+
const outDir = context.config.outDir;
|
|
230
|
+
assertSafeOutDir(outDir, context.root);
|
|
231
|
+
const { assets, ssrEntry } = await bundleTheme(context, outDir);
|
|
232
|
+
const { render } = await import(pathToFileURL(ssrEntry).href);
|
|
233
|
+
const files = await writeSite(context, {
|
|
234
|
+
render,
|
|
235
|
+
assets: withBase(assets, context.config.base)
|
|
236
|
+
});
|
|
237
|
+
await rm(dirname(ssrEntry), {
|
|
238
|
+
recursive: true,
|
|
239
|
+
force: true
|
|
240
|
+
});
|
|
241
|
+
return {
|
|
242
|
+
outDir,
|
|
243
|
+
files,
|
|
244
|
+
context
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Builds the theme with Vite: the island runtime and CSS into `outDir` (emptied first), and the SSR
|
|
249
|
+
* entry, fully bundled so it runs from anywhere. Pass `base: "./"` for client assets that work
|
|
250
|
+
* under any base path (used to precompile the theme bundled into the Yaak plugin).
|
|
251
|
+
*/
|
|
252
|
+
async function bundleTheme(context, outDir, options = {}) {
|
|
253
|
+
const getContext = () => context;
|
|
254
|
+
const base = {
|
|
255
|
+
...await createViteConfig(getContext, "production"),
|
|
256
|
+
...options.base ? { base: options.base } : {}
|
|
257
|
+
};
|
|
258
|
+
await build({
|
|
259
|
+
...base,
|
|
260
|
+
build: {
|
|
261
|
+
outDir,
|
|
262
|
+
emptyOutDir: true,
|
|
263
|
+
manifest: true,
|
|
264
|
+
assetsDir: "_yaakdoc",
|
|
265
|
+
copyPublicDir: true,
|
|
266
|
+
rolldownOptions: {
|
|
267
|
+
...base.build?.rolldownOptions,
|
|
268
|
+
input: { client: VIRTUAL_CLIENT }
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
const ssrOutDir = join(outDir, SSR_DIR);
|
|
273
|
+
await build({
|
|
274
|
+
...base,
|
|
275
|
+
publicDir: false,
|
|
276
|
+
define: { "process.env.NODE_ENV": JSON.stringify("production") },
|
|
277
|
+
ssr: {
|
|
278
|
+
...base.ssr,
|
|
279
|
+
noExternal: true
|
|
280
|
+
},
|
|
281
|
+
build: {
|
|
282
|
+
ssr: true,
|
|
283
|
+
outDir: ssrOutDir,
|
|
284
|
+
emptyOutDir: true,
|
|
285
|
+
copyPublicDir: false,
|
|
286
|
+
rolldownOptions: {
|
|
287
|
+
...base.build?.rolldownOptions,
|
|
288
|
+
input: { "entry-server": VIRTUAL_SERVER },
|
|
289
|
+
output: {
|
|
290
|
+
entryFileNames: "[name].mjs",
|
|
291
|
+
format: "esm"
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
const manifest = JSON.parse(await readFile(join(outDir, ".vite", "manifest.json"), "utf8"));
|
|
297
|
+
await rm(join(outDir, ".vite"), {
|
|
298
|
+
recursive: true,
|
|
299
|
+
force: true
|
|
300
|
+
});
|
|
301
|
+
return {
|
|
302
|
+
assets: assetsFromManifest(manifest),
|
|
303
|
+
ssrEntry: join(ssrOutDir, "entry-server.mjs")
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/** Client assets of the build, relative to the output directory. */
|
|
307
|
+
function assetsFromManifest(manifest) {
|
|
308
|
+
const entry = Object.values(manifest).find((chunk) => chunk.isEntry);
|
|
309
|
+
if (!entry) throw new Error("Client build produced no entry chunk.");
|
|
310
|
+
const collectImports = (keys = [], seen = /* @__PURE__ */ new Set()) => keys.flatMap((key) => {
|
|
311
|
+
if (seen.has(key)) return [];
|
|
312
|
+
seen.add(key);
|
|
313
|
+
const chunk = manifest[key];
|
|
314
|
+
return chunk ? [chunk.file, ...collectImports(chunk.imports, seen)] : [];
|
|
315
|
+
});
|
|
316
|
+
const css = /* @__PURE__ */ new Set([...entry.css ?? []]);
|
|
317
|
+
for (const key of entry.imports ?? []) for (const file of manifest[key]?.css ?? []) css.add(file);
|
|
318
|
+
return {
|
|
319
|
+
styles: [...css],
|
|
320
|
+
scripts: [entry.file],
|
|
321
|
+
inlineStyles: [],
|
|
322
|
+
modulePreloads: collectImports(entry.imports)
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
//#endregion
|
|
326
|
+
//#region src/node/server.ts
|
|
327
|
+
const CONTENT_TYPES = {
|
|
328
|
+
".md": "text/markdown; charset=utf-8",
|
|
329
|
+
".txt": "text/plain; charset=utf-8",
|
|
330
|
+
".json": "application/json; charset=utf-8",
|
|
331
|
+
".svg": "image/svg+xml",
|
|
332
|
+
".png": "image/png",
|
|
333
|
+
".jpg": "image/jpeg",
|
|
334
|
+
".jpeg": "image/jpeg",
|
|
335
|
+
".gif": "image/gif",
|
|
336
|
+
".webp": "image/webp",
|
|
337
|
+
".avif": "image/avif",
|
|
338
|
+
".ico": "image/x-icon",
|
|
339
|
+
".css": "text/css; charset=utf-8",
|
|
340
|
+
".woff2": "font/woff2"
|
|
341
|
+
};
|
|
342
|
+
/** Interface to listen on: a given host, all interfaces (`true`), or localhost. */
|
|
343
|
+
const listenHostname = (host) => typeof host === "string" ? host : host ? "0.0.0.0" : "localhost";
|
|
344
|
+
/** URL to print/open for a server (all-interfaces hosts are shown as localhost). */
|
|
345
|
+
function serverUrl(host, port, base) {
|
|
346
|
+
const hostname = listenHostname(host);
|
|
347
|
+
return `http://${hostname === "0.0.0.0" ? "localhost" : hostname}:${port}${base}`;
|
|
348
|
+
}
|
|
349
|
+
/** Listens on `port`, trying the next ports when it is taken. */
|
|
350
|
+
function listen(server, port, host) {
|
|
351
|
+
const hostname = listenHostname(host);
|
|
352
|
+
return new Promise((resolvePort, reject) => {
|
|
353
|
+
let attempt = 0;
|
|
354
|
+
const tryListen = (candidate) => {
|
|
355
|
+
server.once("error", (error) => {
|
|
356
|
+
if (error.code === "EADDRINUSE" && attempt++ < 20 && port !== 0) tryListen(candidate + 1);
|
|
357
|
+
else reject(error);
|
|
358
|
+
});
|
|
359
|
+
server.listen(candidate, hostname, () => resolvePort(server.address().port));
|
|
360
|
+
};
|
|
361
|
+
tryListen(port);
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
//#endregion
|
|
365
|
+
//#region src/node/dev.ts
|
|
366
|
+
/** Starts the development server with SSR, HMR for theme code/CSS and reload on export changes. */
|
|
367
|
+
async function createDevServer(options = {}) {
|
|
368
|
+
let context = await resolveContext(options);
|
|
369
|
+
const getContext = () => context;
|
|
370
|
+
const httpServer = createServer$1();
|
|
371
|
+
let vite;
|
|
372
|
+
const fullReload = () => vite?.ws.send({
|
|
373
|
+
type: "full-reload",
|
|
374
|
+
path: "*"
|
|
375
|
+
});
|
|
376
|
+
const config = await createViteConfig(getContext, "development", { onSsrUpdate: fullReload });
|
|
377
|
+
vite = await createServer({
|
|
378
|
+
...config,
|
|
379
|
+
appType: "custom",
|
|
380
|
+
server: {
|
|
381
|
+
...config.server,
|
|
382
|
+
middlewareMode: true,
|
|
383
|
+
hmr: { server: httpServer }
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
const ssr = vite.environments.ssr;
|
|
387
|
+
if (!ssr || !isRunnableDevEnvironment(ssr)) throw new Error("The Vite SSR environment is not runnable.");
|
|
388
|
+
const render = async (route, url) => {
|
|
389
|
+
const { render } = await ssr.runner.import(VIRTUAL_SERVER);
|
|
390
|
+
const inlineStyles = await Promise.all(styleEntries(context).map(async (file) => {
|
|
391
|
+
return {
|
|
392
|
+
id: file,
|
|
393
|
+
css: (await ssr.runner.import(`${file}?inline`)).default
|
|
394
|
+
};
|
|
395
|
+
}));
|
|
396
|
+
const html = await render({
|
|
397
|
+
document: context.document,
|
|
398
|
+
site: context.site,
|
|
399
|
+
page: route.page,
|
|
400
|
+
assets: {
|
|
401
|
+
styles: [],
|
|
402
|
+
inlineStyles,
|
|
403
|
+
scripts: [`${context.config.base}@id/__x00__${VIRTUAL_CLIENT}`],
|
|
404
|
+
modulePreloads: []
|
|
405
|
+
}
|
|
406
|
+
});
|
|
407
|
+
return vite.transformIndexHtml(url, html);
|
|
408
|
+
};
|
|
409
|
+
vite.middlewares.use(async (req, res, next) => {
|
|
410
|
+
const url = req.url ?? "/";
|
|
411
|
+
const pathname = decodeURIComponent(url.split(/[?#]/)[0] ?? "/");
|
|
412
|
+
try {
|
|
413
|
+
const assetFile = context.assets.get(pathname);
|
|
414
|
+
if (assetFile && existsSync(assetFile)) {
|
|
415
|
+
res.setHeader("Content-Type", CONTENT_TYPES[extname(assetFile)] ?? "application/octet-stream");
|
|
416
|
+
createReadStream(assetFile).pipe(res);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const route = matchRoute(context, pathname);
|
|
420
|
+
const text = context.textFiles.get(pathname) ?? (route && wantsMarkdown(req) ? context.textFiles.get(route.page.markdownUrl ?? "") : void 0);
|
|
421
|
+
if (text !== void 0) {
|
|
422
|
+
res.setHeader("Content-Type", CONTENT_TYPES[extname(pathname)] ?? CONTENT_TYPES[".md"]);
|
|
423
|
+
res.end(text);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (req.method !== "GET" && req.method !== "HEAD") return next();
|
|
427
|
+
if (route || isHtmlRequest(req, pathname)) {
|
|
428
|
+
const html = await render(route ?? context.notFound, url);
|
|
429
|
+
res.statusCode = route ? 200 : 404;
|
|
430
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
431
|
+
res.end(html);
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
next();
|
|
435
|
+
} catch (error) {
|
|
436
|
+
vite.ssrFixStacktrace(error);
|
|
437
|
+
consola.error(error);
|
|
438
|
+
res.statusCode = 500;
|
|
439
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
440
|
+
res.end(errorPage(error));
|
|
441
|
+
}
|
|
442
|
+
});
|
|
443
|
+
httpServer.on("request", vite.middlewares);
|
|
444
|
+
if (options.watch !== false) {
|
|
445
|
+
const watched = new Set(context.watchFiles.map((file) => resolve(file)));
|
|
446
|
+
vite.watcher.add([...watched]);
|
|
447
|
+
let timer;
|
|
448
|
+
const onChange = (file) => {
|
|
449
|
+
if (!watched.has(resolve(file))) return;
|
|
450
|
+
clearTimeout(timer);
|
|
451
|
+
timer = setTimeout(async () => {
|
|
452
|
+
try {
|
|
453
|
+
const previous = context;
|
|
454
|
+
const next = await resolveContext(options);
|
|
455
|
+
if (next.theme.root !== previous.theme.root || next.config.base !== previous.config.base) consola.warn("The theme or base path changed. Restart yaakdoc to apply it.");
|
|
456
|
+
context = next;
|
|
457
|
+
for (const file of next.watchFiles) if (!watched.has(resolve(file))) {
|
|
458
|
+
watched.add(resolve(file));
|
|
459
|
+
vite.watcher.add(file);
|
|
460
|
+
}
|
|
461
|
+
const mod = ssr.moduleGraph.getModuleById(`\0${VIRTUAL_SERVER}`);
|
|
462
|
+
if (mod) ssr.moduleGraph.invalidateModule(mod);
|
|
463
|
+
consola.success(`Reloaded ${colors.dim(file.replace(`${context.root}/`, ""))}`);
|
|
464
|
+
options.onReload?.(context);
|
|
465
|
+
fullReload();
|
|
466
|
+
} catch (error) {
|
|
467
|
+
consola.error(error.message);
|
|
468
|
+
}
|
|
469
|
+
}, 50);
|
|
470
|
+
};
|
|
471
|
+
vite.watcher.on("change", onChange);
|
|
472
|
+
vite.watcher.on("add", onChange);
|
|
473
|
+
}
|
|
474
|
+
const port = await listen(httpServer, options.port ?? context.config.server.port, options.host ?? context.config.server.host);
|
|
475
|
+
const url = serverUrl(options.host ?? context.config.server.host, port, context.config.base);
|
|
476
|
+
if (options.open ?? context.config.server.open) {
|
|
477
|
+
const { default: openBrowser } = await import("./open-C4Bh1af9.js");
|
|
478
|
+
openBrowser(url);
|
|
479
|
+
}
|
|
480
|
+
return {
|
|
481
|
+
url,
|
|
482
|
+
vite,
|
|
483
|
+
httpServer,
|
|
484
|
+
getContext,
|
|
485
|
+
close: async () => {
|
|
486
|
+
await vite.close();
|
|
487
|
+
await new Promise((done) => httpServer.close(() => done()));
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
function wantsMarkdown(req) {
|
|
492
|
+
const accept = req.headers.accept ?? "";
|
|
493
|
+
return accept.includes("text/markdown") && !accept.includes("text/html");
|
|
494
|
+
}
|
|
495
|
+
function isHtmlRequest(req, pathname) {
|
|
496
|
+
return (req.headers.accept ?? "").includes("text/html") && !extname(pathname);
|
|
497
|
+
}
|
|
498
|
+
const escapeHtml = (value) => value.replace(/[&<>"]/g, (char) => ({
|
|
499
|
+
"&": "&",
|
|
500
|
+
"<": "<",
|
|
501
|
+
">": ">",
|
|
502
|
+
"\"": """
|
|
503
|
+
})[char]);
|
|
504
|
+
function errorPage(error) {
|
|
505
|
+
return `<!doctype html><meta charset="utf-8"><title>yaakdoc error</title><style>body{font:14px/1.5 ui-monospace,monospace;padding:2rem;background:#1e1e2e;color:#f5e0dc}pre{white-space:pre-wrap;color:#f38ba8}</style><h1>Render error</h1><pre>${escapeHtml(error.stack ?? error.message)}</pre><script type="module" src="/@vite/client"><\/script>`;
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/node/fs.ts
|
|
509
|
+
/** Writes pretty-printed JSON with a trailing newline (like editors and formatters do). */
|
|
510
|
+
function writeJson(file, value) {
|
|
511
|
+
return writeFile(file, `${JSON.stringify(value, null, 2)}\n`);
|
|
512
|
+
}
|
|
513
|
+
//#endregion
|
|
514
|
+
//#region src/node/init.ts
|
|
515
|
+
/** `$schema` value for yaakdoc.config.json: local copy when installed, otherwise unpkg. */
|
|
516
|
+
function schemaUrl(cwd) {
|
|
517
|
+
const local = join(cwd, "node_modules", "yaakdoc", "config.schema.json");
|
|
518
|
+
return existsSync(local) ? "./node_modules/yaakdoc/config.schema.json" : `https://unpkg.com/yaakdoc@${VERSION}/config.schema.json`;
|
|
519
|
+
}
|
|
520
|
+
/** Writes a yaakdoc.config.json (with `$schema` for editor autocomplete). */
|
|
521
|
+
async function init(options = {}) {
|
|
522
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
523
|
+
const file = join(cwd, "yaakdoc.config.json");
|
|
524
|
+
if (existsSync(file) && !options.force) throw new Error("yaakdoc.config.json already exists.");
|
|
525
|
+
const config = {
|
|
526
|
+
$schema: schemaUrl(cwd),
|
|
527
|
+
...options.config
|
|
528
|
+
};
|
|
529
|
+
if (!config.export) try {
|
|
530
|
+
config.export = `./${relative(cwd, await detectExport(cwd))}`;
|
|
531
|
+
} catch {}
|
|
532
|
+
await writeJson(file, config);
|
|
533
|
+
return {
|
|
534
|
+
file,
|
|
535
|
+
config
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
//#endregion
|
|
539
|
+
//#region src/node/eject.ts
|
|
540
|
+
const DEFAULT_IGNORE = [
|
|
541
|
+
"node_modules/**",
|
|
542
|
+
"dist/**",
|
|
543
|
+
"package.json",
|
|
544
|
+
"CHANGELOG.md",
|
|
545
|
+
"**/*.test.*",
|
|
546
|
+
"test/**"
|
|
547
|
+
];
|
|
548
|
+
/** Copies the current theme's source into the project so it can be customized freely. */
|
|
549
|
+
async function eject(options = {}) {
|
|
550
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
551
|
+
const { config, configFile, root } = await loadConfig({
|
|
552
|
+
cwd,
|
|
553
|
+
...options.configFile ? { configFile: options.configFile } : {}
|
|
554
|
+
});
|
|
555
|
+
const theme = await resolveTheme(config.theme, {
|
|
556
|
+
root,
|
|
557
|
+
themeOptions: config.themeOptions
|
|
558
|
+
});
|
|
559
|
+
const out = resolve(cwd, options.out ?? "theme");
|
|
560
|
+
if (out === theme.root) throw new Error(`The theme is already located at ${out}.`);
|
|
561
|
+
if (existsSync(out) && readdirSync(out).length > 0 && !options.force) throw new Error(`${relative(cwd, out) || out} already exists and is not empty. Use --force to overwrite.`);
|
|
562
|
+
const files = await glob(theme.definition.eject?.files ?? ["**/*"], {
|
|
563
|
+
cwd: theme.root,
|
|
564
|
+
ignore: DEFAULT_IGNORE,
|
|
565
|
+
dot: false,
|
|
566
|
+
onlyFiles: true
|
|
567
|
+
});
|
|
568
|
+
if (!files.some((file) => resolve(theme.root, file) === theme.manifest)) files.push(relative(theme.root, theme.manifest));
|
|
569
|
+
for (const file of files) {
|
|
570
|
+
const target = join(out, file);
|
|
571
|
+
await mkdir(dirname(target), { recursive: true });
|
|
572
|
+
await copyFile(join(theme.root, file), target);
|
|
573
|
+
}
|
|
574
|
+
let configResult = null;
|
|
575
|
+
if (options.updateConfig !== false) {
|
|
576
|
+
const themePath = `./${relative(configFile ? dirname(configFile) : cwd, out).split("\\").join("/")}`;
|
|
577
|
+
if (configFile && extname(configFile).startsWith(".json")) {
|
|
578
|
+
const json = JSON.parse(await readFile(configFile, "utf8"));
|
|
579
|
+
json.theme = themePath;
|
|
580
|
+
await writeJson(configFile, json);
|
|
581
|
+
configResult = {
|
|
582
|
+
file: configFile,
|
|
583
|
+
updated: true,
|
|
584
|
+
created: false
|
|
585
|
+
};
|
|
586
|
+
} else if (configFile) configResult = {
|
|
587
|
+
file: configFile,
|
|
588
|
+
updated: false,
|
|
589
|
+
created: false
|
|
590
|
+
};
|
|
591
|
+
else {
|
|
592
|
+
const file = join(cwd, "yaakdoc.config.json");
|
|
593
|
+
await writeJson(file, {
|
|
594
|
+
$schema: schemaUrl(cwd),
|
|
595
|
+
theme: themePath
|
|
596
|
+
});
|
|
597
|
+
configResult = {
|
|
598
|
+
file,
|
|
599
|
+
updated: true,
|
|
600
|
+
created: true
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return {
|
|
605
|
+
out,
|
|
606
|
+
files: files.sort(),
|
|
607
|
+
theme: theme.name,
|
|
608
|
+
dependencies: theme.definition.eject?.dependencies ?? [],
|
|
609
|
+
config: configResult
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
//#endregion
|
|
613
|
+
//#region src/node/preview.ts
|
|
614
|
+
/** Serves a built site (like a static host would, including 404.html and base path). */
|
|
615
|
+
async function preview(options = {}) {
|
|
616
|
+
const { config } = await loadConfig({
|
|
617
|
+
cwd: options.cwd ?? process.cwd(),
|
|
618
|
+
...options.configFile ? { configFile: options.configFile } : {}
|
|
619
|
+
});
|
|
620
|
+
const outDir = options.outDir ? resolve(options.cwd ?? process.cwd(), options.outDir) : config.outDir;
|
|
621
|
+
if (!existsSync(join(outDir, "index.html"))) throw new Error(`No build found in ${outDir}. Run \`yaakdoc build\` first.`);
|
|
622
|
+
const serve = sirv(outDir, {
|
|
623
|
+
dev: true,
|
|
624
|
+
etag: true,
|
|
625
|
+
extensions: ["html"],
|
|
626
|
+
setHeaders: (res, pathname) => {
|
|
627
|
+
const type = CONTENT_TYPES[extname(pathname)];
|
|
628
|
+
if (type) res.setHeader("Content-Type", type);
|
|
629
|
+
}
|
|
630
|
+
});
|
|
631
|
+
const notFoundFile = join(outDir, "404.html");
|
|
632
|
+
const base = config.base;
|
|
633
|
+
const server = createServer$1((req, res) => {
|
|
634
|
+
const url = req.url ?? "/";
|
|
635
|
+
if (!url.startsWith(base) && base !== "/") {
|
|
636
|
+
res.writeHead(302, { Location: base });
|
|
637
|
+
res.end();
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
req.url = base === "/" ? url : url.slice(base.length - 1);
|
|
641
|
+
serve(req, res, () => {
|
|
642
|
+
res.statusCode = 404;
|
|
643
|
+
if (existsSync(notFoundFile)) {
|
|
644
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
645
|
+
res.end(readFileSync(notFoundFile));
|
|
646
|
+
} else res.end("Not found");
|
|
647
|
+
});
|
|
648
|
+
});
|
|
649
|
+
const host = options.host ?? config.server.host;
|
|
650
|
+
const url = serverUrl(host, await listen(server, options.port ?? config.server.port, host), base);
|
|
651
|
+
if (options.open) (await import("./open-C4Bh1af9.js")).default(url);
|
|
652
|
+
return {
|
|
653
|
+
url,
|
|
654
|
+
server,
|
|
655
|
+
close: () => new Promise((done) => server.close(() => done()))
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
//#endregion
|
|
659
|
+
export { createDevServer as a, VIRTUAL_CLIENT as c, schemaUrl as i, VIRTUAL_SERVER as l, eject as n, build$1 as o, init as r, bundleTheme as s, preview as t, yaakdocPlugin as u };
|