valaxy 1.0.0-rc.12 → 1.0.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ # unplugin-vue-components
2
+ components.d.ts
3
+
4
+ # vue-router/vite (file-based routing)
5
+ typed-router.d.ts
6
+
7
+ .env.local
@@ -26,7 +26,7 @@ watch(() => props.open, (val) => {
26
26
  else {
27
27
  query.value = ''
28
28
  }
29
- })
29
+ }, { immediate: true })
30
30
 
31
31
  watch(results, () => {
32
32
  selectedIndex.value = 0
@@ -19,7 +19,7 @@ export function useValaxyHead() {
19
19
  if (!/^https?:\/\//.test(siteUrl))
20
20
  return ''
21
21
 
22
- const pagePath = fm.value.url || route.path
22
+ const pagePath = fm.value.canonical || fm.value.url || route.path
23
23
  return resolveSiteUrl(siteUrl, pagePath)
24
24
  })
25
25
 
@@ -13,7 +13,7 @@ export interface LocalSearchResult {
13
13
  export function useLocalSearch(query: Ref<string>) {
14
14
  const results = shallowRef<LocalSearchResult[]>([])
15
15
  const loading = ref(false)
16
- let miniSearch: MiniSearch | null = null
16
+ const miniSearch = shallowRef<MiniSearch | null>(null)
17
17
 
18
18
  async function load(locale = 'root') {
19
19
  loading.value = true
@@ -25,9 +25,9 @@ export function useLocalSearch(query: Ref<string>) {
25
25
  return
26
26
  }
27
27
  const mod = await loader()
28
- const data: string = JSON.parse(mod.default)
28
+ const data: string = mod.default
29
29
  const { default: MiniSearchCtor } = await import('minisearch')
30
- miniSearch = MiniSearchCtor.loadJSON(data, {
30
+ miniSearch.value = MiniSearchCtor.loadJSON(data, {
31
31
  fields: ['title', 'titles', 'text'],
32
32
  storeFields: ['title', 'titles'],
33
33
  })
@@ -38,11 +38,11 @@ export function useLocalSearch(query: Ref<string>) {
38
38
  }
39
39
 
40
40
  watchEffect(() => {
41
- if (!miniSearch || !query.value.trim()) {
41
+ if (!miniSearch.value || !query.value.trim()) {
42
42
  results.value = []
43
43
  return
44
44
  }
45
- results.value = miniSearch.search(query.value, {
45
+ results.value = miniSearch.value.search(query.value, {
46
46
  prefix: true,
47
47
  fuzzy: 0.2,
48
48
  boost: { title: 4, text: 2, titles: 1 },
@@ -18,12 +18,12 @@ declare function startValaxyDev({ root, port, remote, log, open, vite, }: {
18
18
  remote?: boolean;
19
19
  log?: LogLevel;
20
20
  open?: boolean;
21
- /** Final host overrides for programmatic callers such as Valaxy Desktop. */
21
+ /** Final host overrides for programmatic callers such as desktop hosts. */
22
22
  vite?: InlineConfig;
23
23
  }): Promise<ViteDevServer>;
24
24
  declare function registerDevCommand(cli: Argv): void;
25
25
 
26
- /** Programmatic lifecycle contract supported by Valaxy Desktop. */
26
+ /** Programmatic lifecycle contract supported by desktop hosts. */
27
27
  declare const desktopRuntimeVersion = 1;
28
28
  interface CreateCliOptions {
29
29
  userRoot?: string;
@@ -2,7 +2,7 @@ import 'node:path';
2
2
  import 'node:process';
3
3
  import 'yargs';
4
4
  import 'yargs/helpers';
5
- export { c as createCli, s as desktopRuntimeVersion, u as execBuild, N as registerDevCommand, a0 as run, a2 as startValaxyDev } from '../../shared/valaxy.gZBECESB.mjs';
5
+ export { c as createCli, s as desktopRuntimeVersion, u as execBuild, O as registerDevCommand, a1 as run, a3 as startValaxyDev } from '../../shared/valaxy.DzzDX_BR.mjs';
6
6
  import 'node:os';
7
7
  import 'consola';
8
8
  import 'consola/utils';
@@ -23,13 +23,13 @@ import 'cross-spawn';
23
23
  import 'mlly';
24
24
  import 'resolve-global';
25
25
  import '@valaxyjs/utils';
26
+ import 'node:fs';
26
27
  import 'node:fs/promises';
27
28
  import 'dayjs';
28
29
  import 'feed';
29
30
  import 'markdown-exit';
30
31
  import 'table';
31
32
  import 'hookable';
32
- import 'node:fs';
33
33
  import '@intlify/unplugin-vue-i18n/vite';
34
34
  import '@unhead/bundler/vite';
35
35
  import 'unplugin-vue-components/vite';
@@ -39,6 +39,7 @@ import 'p-map';
39
39
  import 'node:buffer';
40
40
  import 'minisearch';
41
41
  import '@shikijs/transformers';
42
+ import 'lru-cache';
42
43
  import 'shiki';
43
44
  import 'css-i18n';
44
45
  import 'markdown-it-anchor';
@@ -53,7 +54,6 @@ import 'katex';
53
54
  import 'katex/contrib/mhchem';
54
55
  import 'unplugin-vue-markdown/vite';
55
56
  import 'js-base64';
56
- import 'lru-cache';
57
57
  import 'jiti';
58
58
  import 'unocss';
59
59
  import 'pascalcase';
@@ -1,5 +1,5 @@
1
1
  import { UserConfig, InlineConfig, ViteDevServer, PluginOption, Plugin } from 'vite';
2
- import { S as SiteConfig, D as DefaultTheme, R as RuntimeConfig, a as RedirectItem, V as ValaxyConfig, P as PartialDeep, b as ValaxyAddon, U as UserSiteConfig } from '../shared/valaxy.VM_duYKy.mjs';
2
+ import { S as SiteConfig, D as DefaultTheme, R as RuntimeConfig, a as RedirectItem, V as ValaxyConfig, P as PartialDeep, b as ValaxyAddon, U as UserSiteConfig } from '../shared/valaxy.BxsKyIbS.mjs';
3
3
  import Vue from '@vitejs/plugin-vue';
4
4
  import { Hookable } from 'hookable';
5
5
  import { PluginVisualizerOptions } from 'rollup-plugin-visualizer';
@@ -352,6 +352,12 @@ interface MarkdownAnchorOptions {
352
352
  * @zh 扩展 Markdown 配置,包含代码高亮、Markdown-it 和插件配置
353
353
  */
354
354
  interface MarkdownOptions extends MarkdownRendererOptions {
355
+ /**
356
+ * Cache repeated highlighted code blocks (up to 8 MiB per highlighter).
357
+ * Enabled for built-in transforms. Custom codeTransformers/shikiSetup must
358
+ * opt in only when their output depends solely on the code, language and attrs.
359
+ */
360
+ highlightCache?: boolean;
355
361
  /**
356
362
  * Setup markdown-it instance before applying plugins
357
363
  */
@@ -547,7 +553,11 @@ interface ContentLoaderContext {
547
553
  }
548
554
  interface ContentLoader {
549
555
  name: string;
556
+ /** Validate the complete output before writing; fail production builds on errors. */
557
+ strict?: boolean;
550
558
  load: (ctx: ContentLoaderContext) => Promise<ContentItem[]> | ContentItem[];
559
+ /** Publish associated metadata only after content has been validated and written. */
560
+ onLoaded?: (ctx: ContentLoaderContext) => void | Promise<void>;
551
561
  /**
552
562
  * Polling interval (ms) for dev mode.
553
563
  * undefined = no polling
@@ -808,7 +818,7 @@ interface ValaxyExtendConfig {
808
818
  * - `true` (default): all pages render KaTeX, unless `frontmatter.katex: false`
809
819
  * - `false`: no pages render KaTeX by default, but individual pages can opt-in via `frontmatter.katex: true`
810
820
  *
811
- * @see [Example | Valaxy](https://valaxy.site/examples/katex)
821
+ * @see [Example | Valaxy](https://valaxy.site/examples/math)
812
822
  * @see https://katex.org/
813
823
  * @default true
814
824
  */
@@ -1225,6 +1235,12 @@ declare const GLOBAL_STATE: {
1225
1235
  server: ViteDevServer | undefined;
1226
1236
  };
1227
1237
 
1238
+ /**
1239
+ * Load content from all loaders and write .md files to cache directory.
1240
+ * Uses digest-based incremental caching to skip unchanged files.
1241
+ */
1242
+ declare function loadAllContent(loaders: ContentLoader[], ctx: ContentLoaderContext): Promise<void>;
1243
+
1228
1244
  /**
1229
1245
  * Post process valaxyOptions
1230
1246
  * @param valaxyOptions
@@ -1309,5 +1325,5 @@ declare function toAtFS(path: string): string;
1309
1325
  declare function resolveImportPath(importName: string, ensure?: true): Promise<string>;
1310
1326
  declare function resolveImportPath(importName: string, ensure?: boolean): Promise<string | undefined>;
1311
1327
 
1312
- export { $t, ALL_ROUTE, EXCERPT_SEPARATOR, GLOBAL_STATE, PATHNAME_PROTOCOL_RE, StateManager, ViteValaxyPlugins, build, createContentService, createMemoryReleasePlugin, createServer, createValaxyNode, createValaxyPlugin, customElements, defaultSiteConfig, defaultValaxyConfig, defaultViteConfig, defineAddon, defineConfig, defineContentLoader, defineSiteConfig, defineTheme, defineUnoSetup, defineValaxyAddon, defineValaxyConfig, defineValaxyTheme, encryptContent, generateClientRedirects, getGitTimestamp, getIndexHtml, getServerInfoText, isExternal, isInstalledGlobally, isKatexEnabled, isKatexPluginNeeded, isMathJaxEnabled, isPath, loadConfigFromFile, mergeValaxyConfig, mergeViteConfigs, postProcessForSSG, processValaxyOptions, resolveAddonsConfig, resolveImportPath, resolveImportUrl, resolveOptions, resolveSiteConfig, resolveSiteConfigFromRoot, resolveThemeConfigFromRoot, resolveThemeValaxyConfig, resolveUserThemeConfig, resolveValaxyConfig, resolveValaxyConfigFromRoot, ssgBuild, toAtFS, transformObject, version };
1328
+ export { $t, ALL_ROUTE, EXCERPT_SEPARATOR, GLOBAL_STATE, PATHNAME_PROTOCOL_RE, StateManager, ViteValaxyPlugins, build, createContentService, createMemoryReleasePlugin, createServer, createValaxyNode, createValaxyPlugin, customElements, defaultSiteConfig, defaultValaxyConfig, defaultViteConfig, defineAddon, defineConfig, defineContentLoader, defineSiteConfig, defineTheme, defineUnoSetup, defineValaxyAddon, defineValaxyConfig, defineValaxyTheme, encryptContent, generateClientRedirects, getGitTimestamp, getIndexHtml, getServerInfoText, isExternal, isInstalledGlobally, isKatexEnabled, isKatexPluginNeeded, isMathJaxEnabled, isPath, loadAllContent, loadConfigFromFile, mergeValaxyConfig, mergeViteConfigs, postProcessForSSG, processValaxyOptions, resolveAddonsConfig, resolveImportPath, resolveImportUrl, resolveOptions, resolveSiteConfig, resolveSiteConfigFromRoot, resolveThemeConfigFromRoot, resolveThemeValaxyConfig, resolveUserThemeConfig, resolveValaxyConfig, resolveValaxyConfigFromRoot, ssgBuild, toAtFS, transformObject, version };
1313
1329
  export type { CdnModule, ContentCheckResult, ContentDiagnostic, ContentItem, ContentLoader, ContentLoaderContext, ContentPageInfo, ContentServiceOptions, GroupIconOptions, GroupIconValue, HookResult, LoadConfigFromFileOptions, MdAfterRenderContext, ResolvedConfig, ResolvedValaxyOptions, UnoSetup, UserInputConfig, UserValaxyNodeConfig, ValaxyAddonCliContext, ValaxyAddonExport, ValaxyAddonExtendCli, ValaxyAddonFn, ValaxyAddonLike, ValaxyAddonResolver, ValaxyAddons, ValaxyApp, ValaxyConfigExport, ValaxyConfigExtendKey, ValaxyConfigFn, ValaxyEntryOptions, ValaxyExtendConfig, ValaxyFileInfo, ValaxyHooks, ValaxyNode, ValaxyNodeAddon, ValaxyNodeConfig, ValaxyPickConfig, ValaxyServerOptions, ValaxyTheme };
@@ -1,4 +1,4 @@
1
- export { A as ALL_ROUTE, E as EXCERPT_SEPARATOR, G as GLOBAL_STATE, P as PATHNAME_PROTOCOL_RE, S as StateManager, V as ViteValaxyPlugins, b as build, c as createCli, a as createContentService, d as createMemoryReleasePlugin, e as createServer, f as createValaxyNode, g as createValaxyPlugin, h as customElements, i as defaultSiteConfig, j as defaultValaxyConfig, k as defaultViteConfig, l as defineAddon, m as defineConfig, n as defineSiteConfig, o as defineTheme, p as defineValaxyAddon, q as defineValaxyConfig, r as defineValaxyTheme, s as desktopRuntimeVersion, t as encryptContent, u as execBuild, v as generateClientRedirects, w as getGitTimestamp, x as getIndexHtml, y as getServerInfoText, z as isExternal, B as isInstalledGlobally, C as isKatexEnabled, D as isKatexPluginNeeded, F as isMathJaxEnabled, H as isPath, I as loadConfigFromFile, J as mergeValaxyConfig, K as mergeViteConfigs, L as postProcessForSSG, M as processValaxyOptions, N as registerDevCommand, O as resolveAddonsConfig, Q as resolveImportPath, R as resolveImportUrl, T as resolveOptions, U as resolveSiteConfig, W as resolveSiteConfigFromRoot, X as resolveThemeConfigFromRoot, Y as resolveThemeValaxyConfig, Z as resolveUserThemeConfig, _ as resolveValaxyConfig, $ as resolveValaxyConfigFromRoot, a0 as run, a1 as ssgBuild, a2 as startValaxyDev, a3 as toAtFS, a4 as transformObject, a5 as version } from '../shared/valaxy.gZBECESB.mjs';
1
+ export { A as ALL_ROUTE, E as EXCERPT_SEPARATOR, G as GLOBAL_STATE, P as PATHNAME_PROTOCOL_RE, S as StateManager, V as ViteValaxyPlugins, b as build, c as createCli, a as createContentService, d as createMemoryReleasePlugin, e as createServer, f as createValaxyNode, g as createValaxyPlugin, h as customElements, i as defaultSiteConfig, j as defaultValaxyConfig, k as defaultViteConfig, l as defineAddon, m as defineConfig, n as defineSiteConfig, o as defineTheme, p as defineValaxyAddon, q as defineValaxyConfig, r as defineValaxyTheme, s as desktopRuntimeVersion, t as encryptContent, u as execBuild, v as generateClientRedirects, w as getGitTimestamp, x as getIndexHtml, y as getServerInfoText, z as isExternal, B as isInstalledGlobally, C as isKatexEnabled, D as isKatexPluginNeeded, F as isMathJaxEnabled, H as isPath, I as loadAllContent, J as loadConfigFromFile, K as mergeValaxyConfig, L as mergeViteConfigs, M as postProcessForSSG, N as processValaxyOptions, O as registerDevCommand, Q as resolveAddonsConfig, R as resolveImportPath, T as resolveImportUrl, U as resolveOptions, W as resolveSiteConfig, X as resolveSiteConfigFromRoot, Y as resolveThemeConfigFromRoot, Z as resolveThemeValaxyConfig, _ as resolveUserThemeConfig, $ as resolveValaxyConfig, a0 as resolveValaxyConfigFromRoot, a1 as run, a2 as ssgBuild, a3 as startValaxyDev, a4 as toAtFS, a5 as transformObject, a6 as version } from '../shared/valaxy.DzzDX_BR.mjs';
2
2
  import 'node:path';
3
3
  import 'consola';
4
4
  import 'fs-extra';
@@ -23,13 +23,13 @@ import 'cross-spawn';
23
23
  import 'mlly';
24
24
  import 'resolve-global';
25
25
  import '@valaxyjs/utils';
26
+ import 'node:fs';
26
27
  import 'node:fs/promises';
27
28
  import 'dayjs';
28
29
  import 'feed';
29
30
  import 'markdown-exit';
30
31
  import 'table';
31
32
  import 'hookable';
32
- import 'node:fs';
33
33
  import '@intlify/unplugin-vue-i18n/vite';
34
34
  import '@unhead/bundler/vite';
35
35
  import 'unplugin-vue-components/vite';
@@ -39,6 +39,7 @@ import 'p-map';
39
39
  import 'node:buffer';
40
40
  import 'minisearch';
41
41
  import '@shikijs/transformers';
42
+ import 'lru-cache';
42
43
  import 'shiki';
43
44
  import 'css-i18n';
44
45
  import 'markdown-it-anchor';
@@ -53,7 +54,6 @@ import 'katex';
53
54
  import 'katex/contrib/mhchem';
54
55
  import 'unplugin-vue-markdown/vite';
55
56
  import 'js-base64';
56
- import 'lru-cache';
57
57
  import 'jiti';
58
58
  import 'unocss';
59
59
  import 'pascalcase';
@@ -92,6 +92,8 @@ interface Photo {
92
92
  desc: string;
93
93
  }
94
94
  interface BaseFrontMatter extends Record<string, any> {
95
+ /** Canonical URL or site-relative path, independent of the current route alias. */
96
+ canonical?: string;
95
97
  /**
96
98
  * Title
97
99
  * @description 文章标题
@@ -955,7 +957,7 @@ interface ValaxyConfig<ThemeConfig = DefaultTheme.Config> {
955
957
  /**
956
958
  * @en Site **info** config. This affects info displayed on the site, and is independent of themes.
957
959
  * @zh 站点**信息**配置,这部分内容面向站点展示,且在不同主题中也是通用的格式
958
- * @see [站点配置 | Valaxy](https://valaxy.site/guide/config#%E7%AB%99%E7%82%B9%E9%85%8D%E7%BD%AE)
960
+ * @see [站点配置 | Valaxy](https://valaxy.site/zh/guide/config#site-config)
959
961
  * @see [Site Config | Valaxy](https://valaxy.site/guide/config#site-config)
960
962
  */
961
963
  siteConfig: SiteConfig;
@@ -1,4 +1,4 @@
1
- import path, { join, dirname, resolve as resolve$1, isAbsolute, relative as relative$1 } from 'node:path';
1
+ import path, { join, dirname, resolve as resolve$1, isAbsolute as isAbsolute$1, relative as relative$1 } from 'node:path';
2
2
  import process from 'node:process';
3
3
  import yargs from 'yargs';
4
4
  import { hideBin } from 'yargs/helpers';
@@ -12,7 +12,7 @@ import * as yaml from 'js-yaml';
12
12
  import { dump, load, CORE_SCHEMA } from 'js-yaml';
13
13
  import { ensurePrefix, slash, uniq, isFunction, isObject, ensureSuffix } from '@antfu/utils';
14
14
  import _debug from 'debug';
15
- import path$1, { resolve, join as join$1, relative, normalize, isAbsolute as isAbsolute$1, dirname as dirname$1 } from 'pathe';
15
+ import path$1, { relative, isAbsolute, resolve, join as join$1, dirname as dirname$1, normalize } from 'pathe';
16
16
  import defu, { createDefu } from 'defu';
17
17
  import { loadConfigFromFile as loadConfigFromFile$1, mergeConfig, searchForWorkspaceRoot, build as build$3, createServer as createServer$1 } from 'vite';
18
18
  import { webcrypto, createHash } from 'node:crypto';
@@ -23,13 +23,13 @@ import { spawn } from 'cross-spawn';
23
23
  import { resolvePath } from 'mlly';
24
24
  import { resolveGlobal } from 'resolve-global';
25
25
  import { normalizeRepositoryUrl } from '@valaxyjs/utils';
26
+ import { existsSync, readFileSync } from 'node:fs';
26
27
  import { readFile, mkdir, writeFile, rm, stat, realpath } from 'node:fs/promises';
27
28
  import dayjs from 'dayjs';
28
29
  import { Feed } from 'feed';
29
30
  import { createMarkdownExit } from 'markdown-exit';
30
31
  import { table, getBorderCharacters } from 'table';
31
32
  import { createHooks } from 'hookable';
32
- import { existsSync, readFileSync } from 'node:fs';
33
33
  import VueI18n from '@intlify/unplugin-vue-i18n/vite';
34
34
  import { Unhead } from '@unhead/bundler/vite';
35
35
  import Components from 'unplugin-vue-components/vite';
@@ -39,6 +39,7 @@ import pMap from 'p-map';
39
39
  import { Buffer as Buffer$1 } from 'node:buffer';
40
40
  import MiniSearch from 'minisearch';
41
41
  import { transformerNotationDiff, transformerNotationFocus, transformerNotationHighlight, transformerNotationErrorLevel, transformerCompactLineOptions } from '@shikijs/transformers';
42
+ import { LRUCache } from 'lru-cache';
42
43
  import { createHighlighter, addClassToHast, isSpecialLang } from 'shiki';
43
44
  import { cssI18nContainer } from 'css-i18n';
44
45
  import anchorPlugin from 'markdown-it-anchor';
@@ -53,7 +54,6 @@ import katex from 'katex';
53
54
  import 'katex/contrib/mhchem';
54
55
  import Markdown from 'unplugin-vue-markdown/vite';
55
56
  import * as base64 from 'js-base64';
56
- import { LRUCache } from 'lru-cache';
57
57
  import { createJiti } from 'jiti';
58
58
  import { transformerDirectives, transformerVariantGroup, presetWind4, presetAttributify, presetIcons, presetTypography } from 'unocss';
59
59
  import pascalCase from 'pascalcase';
@@ -71,7 +71,7 @@ import * as readline from 'node:readline';
71
71
  import qrcode from 'qrcode';
72
72
  import ejs from 'ejs';
73
73
 
74
- const version = "1.0.0-rc.12";
74
+ const version = "1.0.0-rc.14";
75
75
 
76
76
  const GLOBAL_STATE = {
77
77
  valaxyApp: void 0,
@@ -299,16 +299,55 @@ async function callHookWithLog(hookName, valaxyApp) {
299
299
  s.succeed(`${hookNameStr} done.`);
300
300
  }
301
301
 
302
+ function getPageRoots(userRoot) {
303
+ return [resolve(userRoot, "pages"), resolve(userRoot, ".valaxy/content/pages")];
304
+ }
305
+ function getPagePath(file, userRoot) {
306
+ for (const root of getPageRoots(userRoot)) {
307
+ const page = relative(root, file);
308
+ if (page && !isAbsolute(page) && page !== ".." && !page.startsWith("../"))
309
+ return page;
310
+ }
311
+ }
312
+ function resolvePageFile(page, userRoot) {
313
+ if (isAbsolute(page) || page.includes("\\"))
314
+ return;
315
+ for (const root of getPageRoots(userRoot)) {
316
+ const file = resolve(root, page);
317
+ const rel = relative(root, file);
318
+ if (!rel || rel === ".." || rel.startsWith("../") || isAbsolute(rel))
319
+ return;
320
+ if (existsSync(file))
321
+ return file;
322
+ }
323
+ }
324
+ function pagePathToRoute(page) {
325
+ return page.replace(/\.(?:md|html)$/, "").replace(/(^|\/)index$/, "");
326
+ }
327
+ async function discoverPageFiles(userRoot, include = ["**/*.md"]) {
328
+ const pages = /* @__PURE__ */ new Map();
329
+ for (const root of getPageRoots(userRoot)) {
330
+ const files = await fg(include, { cwd: root, ignore: ["**/node_modules/**"], onlyFiles: true });
331
+ for (const page of files.sort()) {
332
+ if (!pages.has(page))
333
+ pages.set(page, resolve(root, page));
334
+ }
335
+ }
336
+ return pages;
337
+ }
338
+
302
339
  const debug$3 = _debug("valaxy:group-icons");
303
340
  const codeBlockTitleRE = /^[ \t]{0,3}`{3}[^\n[]*\[((?:[^[\]]|\[[^[\]]*\])*)\]/gm;
304
341
  async function scanCodeBlockTitles(options) {
305
- const pagesDir = resolve(options.userRoot, "pages");
306
342
  const titles = /* @__PURE__ */ new Set();
307
343
  await pMap(
308
344
  options.pages,
309
345
  async (page) => {
310
346
  try {
311
- const content = await readFile(resolve(pagesDir, page), "utf-8");
347
+ const file = resolvePageFile(page, options.userRoot);
348
+ if (!file)
349
+ return;
350
+ const content = await readFile(file, "utf-8");
312
351
  extractCodeBlockTitles(content, titles);
313
352
  } catch (error) {
314
353
  debug$3("Failed to read %s: %O", page, error);
@@ -1320,9 +1359,7 @@ const matterOptions = {
1320
1359
  };
1321
1360
 
1322
1361
  async function scanPageFiles(userRoot, include) {
1323
- const pagesPattern = fg.convertPathToPattern(path.join(userRoot, "pages"));
1324
- const patterns = include.map((p) => `${pagesPattern}/${p}`);
1325
- return fg(patterns);
1362
+ return [...(await discoverPageFiles(userRoot, include)).values()];
1326
1363
  }
1327
1364
  async function readPostFiles(files) {
1328
1365
  return Promise.all(files.map(async (filePath) => {
@@ -1335,7 +1372,7 @@ function filterPublicPosts(posts) {
1335
1372
  return posts.filter(({ data }) => !data.password && !data.draft && !data.hide);
1336
1373
  }
1337
1374
  function filePathToUrlPath(filePath, userRoot) {
1338
- const relativePath = path.relative(path.join(userRoot, "pages"), filePath);
1375
+ const relativePath = getPagePath(filePath, userRoot) || path.relative(path.join(userRoot, "pages"), filePath);
1339
1376
  const normalized = `/${relativePath.replace(/\\/g, "/")}`;
1340
1377
  if (normalized.endsWith("/index.md"))
1341
1378
  return normalized.slice(0, -"/index.md".length);
@@ -1627,18 +1664,8 @@ async function collectPosts(options, lang) {
1627
1664
  return posts;
1628
1665
  }
1629
1666
  async function resolveRawMd(url, options) {
1630
- const pagesDir = path.resolve(options.userRoot, "pages");
1631
- const safePath = path.resolve(pagesDir, url.slice(1));
1632
- if (!safePath.startsWith(pagesDir + path.sep))
1633
- return null;
1634
- const directPath = safePath;
1635
- const stem = safePath.slice(0, -".md".length);
1636
- const indexPath = path.join(stem, "index.md");
1637
- let filePath = null;
1638
- if (await fs.pathExists(directPath))
1639
- filePath = directPath;
1640
- else if (await fs.pathExists(indexPath))
1641
- filePath = indexPath;
1667
+ const page = url.slice(1);
1668
+ const filePath = resolvePageFile(page, options.userRoot) || resolvePageFile(`${page.slice(0, -3)}/index.md`, options.userRoot);
1642
1669
  if (!filePath)
1643
1670
  return null;
1644
1671
  const raw = await fs.readFile(filePath, "utf-8");
@@ -1858,8 +1885,17 @@ async function highlight(theme, options, logger = console) {
1858
1885
  const lineNoStartRE = /=(\d*)/;
1859
1886
  const lineNoRE = /:(no-)?line-numbers(=\d*)?$/;
1860
1887
  const mustacheRE = /\{\{.*?\}\}/g;
1888
+ const cache = options.highlightCache ?? (!userTransformers.length && !options.shikiSetup) ? new LRUCache({
1889
+ max: 1024,
1890
+ maxSize: 8 * 1024 * 1024,
1891
+ sizeCalculation: (value) => Buffer$1.byteLength(value)
1892
+ }) : void 0;
1861
1893
  return [
1862
1894
  async (str, lang, attrs) => {
1895
+ const key = cache && createHash("sha256").update(JSON.stringify([str, lang, attrs])).digest("base64url");
1896
+ const cached = key ? cache?.get(key) : void 0;
1897
+ if (cached !== void 0)
1898
+ return cached;
1863
1899
  const vPre = vueRE.test(lang) ? "" : "v-pre";
1864
1900
  lang = lang.replace(lineNoStartRE, "").replace(lineNoRE, "").replace(vueRE, "").toLowerCase() || defaultLang;
1865
1901
  try {
@@ -1930,9 +1966,15 @@ The language '${lang}' is not loaded, falling back to '${defaultLang}' for synta
1930
1966
  },
1931
1967
  ...typeof theme === "object" && "light" in theme && "dark" in theme ? { themes: theme, defaultColor: false } : { theme }
1932
1968
  });
1933
- return restoreMustache(highlighted);
1969
+ const result = restoreMustache(highlighted);
1970
+ if (key)
1971
+ cache?.set(key, result);
1972
+ return result;
1934
1973
  },
1935
- highlighter.dispose
1974
+ () => {
1975
+ cache?.clear();
1976
+ highlighter.dispose();
1977
+ }
1936
1978
  ];
1937
1979
  }
1938
1980
 
@@ -3036,6 +3078,44 @@ async function setupMarkdownPlugins(md, options, base = options?.config.vite?.ba
3036
3078
  return md;
3037
3079
  }
3038
3080
 
3081
+ function cacheMarkdownRender(md, state, base, fileInfoFor) {
3082
+ const cache = new LRUCache({
3083
+ max: 2048,
3084
+ maxSize: 32 * 1024 * 1024,
3085
+ sizeCalculation: (item) => item.bytes
3086
+ });
3087
+ const log = _debug("valaxy:md");
3088
+ const getBase = createMarkdownBaseResolver(base);
3089
+ const render = md.renderAsync.bind(md);
3090
+ let active = true;
3091
+ state.onDispose(() => {
3092
+ active = false;
3093
+ cache.clear();
3094
+ });
3095
+ md.renderAsync = async (source, env = {}) => {
3096
+ if (!active || !env.id || Object.keys(env).some((key2) => key2 !== "id"))
3097
+ return render(source, env);
3098
+ const key = createHash("sha256").update(env.id).update("\0").update(getBase()).update("\0").update(source).digest("base64url");
3099
+ const cached = cache.get(key);
3100
+ if (cached) {
3101
+ const snapshot = structuredClone({ env: cached.env, fileInfo: cached.fileInfo });
3102
+ Object.assign(env, snapshot.env);
3103
+ if (snapshot.fileInfo)
3104
+ state.set(snapshot.fileInfo);
3105
+ log(`[parser cache hit] ${env.id}`);
3106
+ return cached.html;
3107
+ }
3108
+ const html = await render(source, env);
3109
+ try {
3110
+ const snapshot = structuredClone({ env, fileInfo: fileInfoFor(env) });
3111
+ const bytes = Buffer$1.byteLength(html) + Buffer$1.byteLength(JSON.stringify(snapshot));
3112
+ cache.set(key, { html, ...snapshot, bytes });
3113
+ } catch {
3114
+ }
3115
+ return html;
3116
+ };
3117
+ }
3118
+
3039
3119
  const KNOWN_EXTENSIONS = /* @__PURE__ */ new Set();
3040
3120
  function treatAsHtml(filename) {
3041
3121
  if (KNOWN_EXTENSIONS.size === 0) {
@@ -3165,21 +3245,30 @@ async function createMarkdownPlugin(options, base, state = Valaxy.state) {
3165
3245
  await setupMarkdownPlugins(mdIt, options, base);
3166
3246
  await setupUserMarkdown?.(mdIt);
3167
3247
  setupMarkdownPageMetadata(mdIt, options);
3248
+ const environments = /* @__PURE__ */ new WeakMap();
3249
+ const recordEnvironment = (env) => {
3250
+ if (!env.id)
3251
+ return;
3252
+ const fileInfo = {
3253
+ id: env.id,
3254
+ title: env.title ?? "",
3255
+ // Link renderer rules append after the core metadata rule runs.
3256
+ // Share the same array so first-pass dead-link validation sees them.
3257
+ links: env.links ?? (env.links = []),
3258
+ headers: env.headers ?? [],
3259
+ frontmatter: env.frontmatter ?? {}
3260
+ };
3261
+ environments.set(env, fileInfo);
3262
+ state.set(fileInfo);
3263
+ };
3168
3264
  function initEnv(md) {
3169
3265
  md.core.ruler.push("valaxy_md_env", (mdState) => {
3170
- const env = mdState.env;
3171
- if (!env.id)
3172
- return;
3173
- state.set({
3174
- id: env.id,
3175
- title: env.title ?? "",
3176
- links: env.links ?? [],
3177
- headers: env.headers ?? [],
3178
- frontmatter: env.frontmatter ?? {}
3179
- });
3266
+ recordEnvironment(mdState.env);
3180
3267
  });
3181
3268
  }
3182
3269
  mdIt.use(initEnv);
3270
+ if (options.mode === "build")
3271
+ cacheMarkdownRender(mdIt, state, base || options.config.vite?.base || "/", (env) => environments.get(env));
3183
3272
  },
3184
3273
  transforms: {
3185
3274
  before(code, id) {
@@ -3265,17 +3354,17 @@ async function localSearchPlugin(options, base) {
3265
3354
  };
3266
3355
  }
3267
3356
  const srcDir = path.resolve(options.userRoot, "pages");
3268
- const originalPages = options.pages;
3269
3357
  const md = await createLightMarkdownRenderer(options, base);
3270
3358
  async function render(file) {
3271
3359
  if (!fs.existsSync(file))
3272
- return "";
3273
- const relativePath = slash(path.relative(srcDir, file));
3360
+ return { html: "", shared: false };
3361
+ const relativePath = getPagePath(file, options.userRoot) || slash(path.relative(srcDir, file));
3274
3362
  const env = { path: file, relativePath };
3275
3363
  const mdRaw = await fs.promises.readFile(file, "utf-8");
3276
- const mdSrc = processIncludes(srcDir, mdRaw, file);
3364
+ const { data: fm, content } = matter(mdRaw, matterOptions);
3365
+ const mdSrc = processIncludes(srcDir, content, file);
3277
3366
  const html = await md.renderAsync(mdSrc, env);
3278
- return env.frontmatter?.search === false ? "" : html;
3367
+ return { html: fm?.search === false || fm?.draft || fm?.hide || fm?.password ? "" : html, shared: fm?.sharedLocale === true };
3279
3368
  }
3280
3369
  const indexByLocales = /* @__PURE__ */ new Map();
3281
3370
  const fileToDocIds = /* @__PURE__ */ new Map();
@@ -3313,10 +3402,10 @@ async function localSearchPlugin(options, base) {
3313
3402
  }
3314
3403
  }
3315
3404
  function getDocId(file) {
3316
- const relFile = slash(path.relative(srcDir, file));
3405
+ const relFile = getPagePath(file, options.userRoot) || slash(path.relative(srcDir, file));
3317
3406
  let id = slash(path.join("/", relFile));
3318
3407
  id = id.replace(/(^|\/)index\.md$/, "$1");
3319
- id = id.replace(/\.md$/, ".html");
3408
+ id = id.replace(/\.md$/, "");
3320
3409
  return id;
3321
3410
  }
3322
3411
  function getLocaleForPath(page) {
@@ -3328,11 +3417,13 @@ async function localSearchPlugin(options, base) {
3328
3417
  return "root";
3329
3418
  }
3330
3419
  async function indexFile(page) {
3331
- const file = path.join(srcDir, page);
3420
+ const file = resolvePageFile(page, options.userRoot);
3421
+ if (!file)
3422
+ return;
3332
3423
  const fileId = getDocId(file);
3333
- const locale = getLocaleForPath(page);
3334
- const index = getIndexByLocale(locale);
3335
- const html = await render(file);
3424
+ const { html, shared } = await render(file);
3425
+ const locales = shared ? [.../* @__PURE__ */ new Set(["root", ...siteConfig.languages || []])] : [getLocaleForPath(page)];
3426
+ const indexes = locales.map(getIndexByLocale);
3336
3427
  const sections = splitPageIntoSections(html);
3337
3428
  const docIds = [];
3338
3429
  for (const section of sections) {
@@ -3341,21 +3432,25 @@ async function localSearchPlugin(options, base) {
3341
3432
  const { anchor, text, titles } = section;
3342
3433
  const id = anchor ? [fileId, anchor].join("#") : fileId;
3343
3434
  docIds.push(id);
3344
- index.add({
3435
+ const record = {
3345
3436
  id,
3346
3437
  text,
3347
3438
  title: titles.at(-1),
3348
3439
  titles: titles.slice(0, -1)
3349
- });
3440
+ };
3441
+ for (const index of indexes)
3442
+ index.add(record);
3350
3443
  }
3351
- fileToDocIds.set(page, { locale, ids: docIds });
3444
+ fileToDocIds.set(page, { locales, ids: docIds });
3352
3445
  }
3353
3446
  function discardFile(page) {
3354
3447
  const entry = fileToDocIds.get(page);
3355
3448
  if (!entry)
3356
3449
  return true;
3357
- const index = indexByLocales.get(entry.locale);
3358
- if (index) {
3450
+ for (const locale of entry.locales) {
3451
+ const index = indexByLocales.get(locale);
3452
+ if (!index)
3453
+ continue;
3359
3454
  for (const id of entry.ids) {
3360
3455
  try {
3361
3456
  index.discard(id);
@@ -3372,11 +3467,30 @@ async function localSearchPlugin(options, base) {
3372
3467
  debug$2("Indexing files for search...");
3373
3468
  indexByLocales.clear();
3374
3469
  fileToDocIds.clear();
3375
- await pMap(originalPages, indexFile, {
3470
+ await pMap([...(await discoverPageFiles(options.userRoot)).keys()], indexFile, {
3376
3471
  concurrency: 10
3377
3472
  });
3378
3473
  debug$2("Indexing finished..., %d locales", indexByLocales.size);
3379
3474
  }
3475
+ let pendingUpdate = Promise.resolve();
3476
+ const changedPages = /* @__PURE__ */ new Set();
3477
+ let timer;
3478
+ function flushUpdates() {
3479
+ clearTimeout(timer);
3480
+ const pages = [...changedPages];
3481
+ changedPages.clear();
3482
+ pendingUpdate = pendingUpdate.catch((error) => server?.config.logger.error(String(error))).then(async () => {
3483
+ for (const page of pages) {
3484
+ if (!discardFile(page)) {
3485
+ await scanForBuild();
3486
+ break;
3487
+ }
3488
+ await indexFile(page);
3489
+ }
3490
+ onIndexUpdated();
3491
+ });
3492
+ return pendingUpdate;
3493
+ }
3380
3494
  return {
3381
3495
  name: "valaxy:local-search",
3382
3496
  config: () => ({
@@ -3390,6 +3504,21 @@ async function localSearchPlugin(options, base) {
3390
3504
  }),
3391
3505
  async configureServer(_server) {
3392
3506
  server = _server;
3507
+ const onPageChange = (file) => {
3508
+ const page = getPagePath(file, options.userRoot);
3509
+ if (file.endsWith(".md") && page) {
3510
+ changedPages.add(page);
3511
+ clearTimeout(timer);
3512
+ timer = setTimeout(() => {
3513
+ void flushUpdates().catch((error) => server?.config.logger.error(String(error)));
3514
+ }, 100);
3515
+ }
3516
+ };
3517
+ server.watcher.on("add", onPageChange).on("unlink", onPageChange);
3518
+ server.httpServer?.once("close", () => {
3519
+ clearTimeout(timer);
3520
+ server?.watcher.off("add", onPageChange).off("unlink", onPageChange);
3521
+ });
3393
3522
  await scanForBuild();
3394
3523
  onIndexUpdated();
3395
3524
  },
@@ -3422,16 +3551,10 @@ async function localSearchPlugin(options, base) {
3422
3551
  },
3423
3552
  async handleHotUpdate({ file }) {
3424
3553
  if (file.endsWith(".md")) {
3425
- const relPath = slash(path.relative(srcDir, file));
3554
+ const relPath = getPagePath(file, options.userRoot) || slash(path.relative(srcDir, file));
3426
3555
  if (!relPath.startsWith("..")) {
3427
- if (discardFile(relPath)) {
3428
- await indexFile(relPath);
3429
- debug$2("Updated index for %s", relPath);
3430
- } else {
3431
- debug$2("Discard failed for %s, rebuilding full index", relPath);
3432
- await scanForBuild();
3433
- }
3434
- onIndexUpdated();
3556
+ changedPages.add(relPath);
3557
+ await flushUpdates();
3435
3558
  }
3436
3559
  }
3437
3560
  }
@@ -3504,6 +3627,8 @@ function createScanDeadLinks(options) {
3504
3627
  const { links = [] } = fileInfo || {};
3505
3628
  const fileOrig = id;
3506
3629
  const file = id;
3630
+ const logicalFile = getPagePath(file, options.userRoot) || path$1.relative(srcDir, file);
3631
+ const routes = new Set(options.pages.map(pagePathToRoute));
3507
3632
  const deadLinks = [];
3508
3633
  const recordDeadLink = (url) => {
3509
3634
  deadLinks.push({ url, file: path$1.relative(srcDir, fileOrig) });
@@ -3536,11 +3661,11 @@ function createScanDeadLinks(options) {
3536
3661
  url += `index`;
3537
3662
  const resolved = decodeURIComponent(
3538
3663
  slash(
3539
- url.startsWith("/") ? url.slice(1) : path$1.relative(srcDir, path$1.resolve(dir, url))
3664
+ url.startsWith("/") ? url.slice(1) : path$1.normalize(path$1.join(path$1.dirname(logicalFile), url))
3540
3665
  )
3541
3666
  // /index => /
3542
- ).replace(/\/index$/, "");
3543
- if (!options.pages.includes(resolved) && !fs.existsSync(path$1.resolve(dir, publicDir, `${resolved}.html`)) && !shouldIgnoreDeadLink(url)) {
3667
+ ).replace(/(^|\/)index$/, "");
3668
+ if (!routes.has(resolved) && !fs.existsSync(path$1.resolve(dir, publicDir, `${resolved}.html`)) && !shouldIgnoreDeadLink(url)) {
3544
3669
  recordDeadLink(url);
3545
3670
  }
3546
3671
  }
@@ -3767,7 +3892,7 @@ async function generatePageData(code, context, options) {
3767
3892
  relativePath,
3768
3893
  filePath: id
3769
3894
  };
3770
- if (options.config.siteConfig.lastUpdated)
3895
+ if (options.config.siteConfig.lastUpdated && fm.lastUpdated !== false)
3771
3896
  pageData.lastUpdated = await getGitTimestamp(id);
3772
3897
  return pageData;
3773
3898
  }
@@ -3777,7 +3902,11 @@ const caches = /* @__PURE__ */ new WeakMap();
3777
3902
  function getMarkdownCache(state) {
3778
3903
  let cache = caches.get(state);
3779
3904
  if (!cache) {
3780
- cache = new LRUCache({ max: 128 });
3905
+ cache = new LRUCache({
3906
+ max: 2048,
3907
+ maxSize: 32 * 1024 * 1024,
3908
+ sizeCalculation: (result) => Buffer$1.byteLength(result.code) + Buffer$1.byteLength(JSON.stringify(result.pageData))
3909
+ });
3781
3910
  caches.set(state, cache);
3782
3911
  }
3783
3912
  return cache;
@@ -3819,7 +3948,6 @@ function getValaxyMain(mainContentMd) {
3819
3948
  `;
3820
3949
  }
3821
3950
  async function createMarkdownToVueRenderFn(options, state = Valaxy.state) {
3822
- options.pages = options.pages.map((p) => p.replace(/\.md$/, "").replace(/\/index$/, ""));
3823
3951
  const transformCodeBlock = createTransformCodeBlock(options);
3824
3952
  const transformMarkdown = createTransformMarkdown(options);
3825
3953
  const transformEncrypt = createTransformEncrypt(options);
@@ -4667,7 +4795,7 @@ async function createValaxyPlugin(options, serverOptions = {}, state = Valaxy.st
4667
4795
  const endCount = countPerformanceTime();
4668
4796
  const content = await read();
4669
4797
  const { code, pageData } = await markdownToVue(content, file);
4670
- const path = `/${relative(`${options.userRoot}/pages`, file)}`;
4798
+ const path = `/${getPagePath(file, options.userRoot) || relative(`${options.userRoot}/pages`, file)}`;
4671
4799
  const payload = {
4672
4800
  path,
4673
4801
  pageData
@@ -5129,6 +5257,18 @@ async function ViteValaxyPlugins(valaxyApp, serverOptions = {}, viteConfig = {},
5129
5257
  return plugins;
5130
5258
  }
5131
5259
 
5260
+ async function profileBuildPhase(phase, run) {
5261
+ if (!process.env.VALAXY_BUILD_PROFILE)
5262
+ return run();
5263
+ const started = performance.now();
5264
+ try {
5265
+ return await run();
5266
+ } finally {
5267
+ process.stdout.write(`[valaxy:build] ${JSON.stringify({ phase, durationMs: performance.now() - started, rssMiB: process.memoryUsage().rss / 1024 / 1024 })}
5268
+ `);
5269
+ }
5270
+ }
5271
+
5132
5272
  async function renderPage(opts) {
5133
5273
  let template = opts.template;
5134
5274
  if (opts.onBeforePageRender) {
@@ -5284,11 +5424,11 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
5284
5424
  }
5285
5425
  }
5286
5426
  const configOutDir = viteConfig.build?.outDir || "dist";
5287
- const outDir = isAbsolute(configOutDir) ? configOutDir : resolve$1(options.userRoot, configOutDir);
5427
+ const outDir = isAbsolute$1(configOutDir) ? configOutDir : resolve$1(options.userRoot, configOutDir);
5288
5428
  const ssgTemp = resolve$1(outDir, ".vite-ssg-temp");
5289
5429
  const defaultConfig = {
5290
5430
  ...defaultViteConfig,
5291
- plugins: await ViteValaxyPlugins(valaxyApp, {}, viteConfig, 2),
5431
+ plugins: await profileBuildPhase("plugins", () => ViteValaxyPlugins(valaxyApp, {}, viteConfig, 2)),
5292
5432
  // `ssr.noExternal` only affects the server build (step 2) — the client build
5293
5433
  // ignores it. See `getSsgSsrConfig` for why everything is bundled.
5294
5434
  ssr: getSsgSsrConfig(),
@@ -5302,17 +5442,19 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
5302
5442
  const inlineConfig = mergeConfig(defaultConfig, viteConfig);
5303
5443
  try {
5304
5444
  consola.info("Building client bundle...");
5305
- await build$3(mergeConfig(inlineConfig, {
5445
+ await profileBuildPhase("client-bundle", () => build$3(mergeConfig(inlineConfig, {
5306
5446
  build: {
5307
5447
  ssrManifest: true,
5308
5448
  outDir
5309
5449
  }
5310
- }));
5450
+ })));
5311
5451
  consola.info("Building server bundle...");
5312
- await build$3(mergeConfig(inlineConfig, {
5452
+ await profileBuildPhase("server-bundle", () => build$3(mergeConfig(inlineConfig, {
5313
5453
  build: {
5314
5454
  ssr: resolve$1(options.clientRoot, "entry-ssr.ts"),
5315
5455
  outDir: ssgTemp,
5456
+ // This temporary bundle is executed locally, never served to browsers.
5457
+ reportCompressedSize: false,
5316
5458
  minify: false,
5317
5459
  cssCodeSplit: false,
5318
5460
  rolldownOptions: {
@@ -5321,11 +5463,11 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
5321
5463
  }
5322
5464
  }
5323
5465
  }
5324
- }));
5466
+ })));
5325
5467
  consola.info("Releasing build resources...");
5326
5468
  tryGC();
5327
5469
  const entryPath = resolve$1(ssgTemp, "entry-ssr.mjs");
5328
- const { render, routes } = await import(pathToFileURL(entryPath).href);
5470
+ const { render, routes } = await profileBuildPhase("server-load", () => import(pathToFileURL(entryPath).href));
5329
5471
  let routePaths;
5330
5472
  if (userSsgOptions.includedRoutes) {
5331
5473
  routePaths = await userSsgOptions.includedRoutes(routesToPaths(routes), routes);
@@ -5347,7 +5489,7 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
5347
5489
  );
5348
5490
  const concurrency = userSsgOptions.concurrency ?? 20;
5349
5491
  consola.info(`Rendering ${colors.yellow(routePaths.length)} pages (concurrency: ${colors.yellow(concurrency)})...`);
5350
- await pMap(
5492
+ await profileBuildPhase("render-pages", () => pMap(
5351
5493
  routePaths,
5352
5494
  (route) => renderPage({
5353
5495
  render,
@@ -5359,7 +5501,7 @@ async function ssgBuild(valaxyApp, viteConfig = {}, userSsgOptions = {}) {
5359
5501
  onPageRendered: userSsgOptions.onPageRendered
5360
5502
  }),
5361
5503
  { concurrency }
5362
- );
5504
+ ));
5363
5505
  consola.success(`${routePaths.length} pages rendered.`);
5364
5506
  } finally {
5365
5507
  await rm(ssgTemp, { recursive: true, force: true }).catch(() => {
@@ -5423,6 +5565,13 @@ async function generateFuseList(options) {
5423
5565
  const pattern = path.resolve(options.userRoot, options.config.siteConfig.fuse.pattern || "pages/**/*.md");
5424
5566
  const finalPattern = isWindows ? fg.convertPathToPattern(pattern) : pattern;
5425
5567
  const files = await fg(finalPattern);
5568
+ const fusePattern = options.config.siteConfig.fuse.pattern || "pages/**/*.md";
5569
+ if (fusePattern.startsWith("pages/")) {
5570
+ for (const file of (await discoverPageFiles(options.userRoot, [fusePattern.slice(6)])).values()) {
5571
+ if (!files.includes(file))
5572
+ files.push(file);
5573
+ }
5574
+ }
5426
5575
  if (files.length > 0) {
5427
5576
  consola.success(`Found ${colors.dim(files.length.toString())} markdown files for fuse search.`);
5428
5577
  } else {
@@ -5444,7 +5593,7 @@ async function generateFuseList(options) {
5444
5593
  if (fmData.password)
5445
5594
  continue;
5446
5595
  const extendKeys = options.config.fuse?.extendKeys || [];
5447
- const relativeLink = path.join(options.config.vite?.base || "/", path.relative(path.resolve(options.userRoot, "pages"), i)).replace(/\\/g, "/");
5596
+ const relativeLink = path.join(options.config.vite?.base || "/", getPagePath(i, options.userRoot) || path.relative(path.resolve(options.userRoot, "pages"), i)).replace(/\\/g, "/");
5448
5597
  const link = i.endsWith("index.md") ? relativeLink.replace(/\/index\.md$/, "") : relativeLink.replace(/\.md$/, "");
5449
5598
  const fuseListItem = {
5450
5599
  title: fmData.title || "",
@@ -5909,7 +6058,51 @@ function shouldResolveAddonCli(argv) {
5909
6058
  const command = getRequestedCommand(argv);
5910
6059
  if (!command || CORE_CLI_COMMANDS.has(command))
5911
6060
  return false;
5912
- return command !== "." && !command.startsWith("./") && !command.startsWith("../") && !isAbsolute(command);
6061
+ return command !== "." && !command.startsWith("./") && !command.startsWith("../") && !isAbsolute$1(command);
6062
+ }
6063
+
6064
+ async function recoverContentTransaction(directory) {
6065
+ const journal = resolve(directory, "journal.json");
6066
+ if (!await fs.pathExists(journal))
6067
+ return;
6068
+ const backups = await fs.readJson(journal);
6069
+ for (const [index, backup] of backups.entries()) {
6070
+ if (backup.existed) {
6071
+ fs.ensureDirSync(dirname$1(backup.path));
6072
+ fs.copyFileSync(resolve(directory, `${index}.backup`), backup.path);
6073
+ } else {
6074
+ fs.removeSync(backup.path);
6075
+ }
6076
+ }
6077
+ await fs.remove(directory);
6078
+ }
6079
+ async function publishContentTransaction(directory, changes) {
6080
+ await fs.ensureDir(directory);
6081
+ const backups = [];
6082
+ for (const [index, change] of changes.entries()) {
6083
+ const existed = await fs.pathExists(change.path);
6084
+ backups.push({ path: change.path, existed });
6085
+ if (existed)
6086
+ await fs.copyFile(change.path, resolve(directory, `${index}.backup`));
6087
+ if (change.content !== void 0)
6088
+ await fs.writeFile(resolve(directory, `${index}.next`), change.content);
6089
+ await fs.ensureDir(dirname$1(change.path));
6090
+ }
6091
+ await fs.writeJson(resolve(directory, "journal.tmp"), backups);
6092
+ await fs.rename(resolve(directory, "journal.tmp"), resolve(directory, "journal.json"));
6093
+ try {
6094
+ for (const [index, change] of changes.entries()) {
6095
+ if (change.content === void 0)
6096
+ fs.removeSync(change.path);
6097
+ else
6098
+ fs.renameSync(resolve(directory, `${index}.next`), change.path);
6099
+ }
6100
+ fs.removeSync(resolve(directory, "journal.json"));
6101
+ } catch (error) {
6102
+ await recoverContentTransaction(directory);
6103
+ throw error;
6104
+ }
6105
+ await fs.remove(directory);
5913
6106
  }
5914
6107
 
5915
6108
  function computeDigest(content) {
@@ -5926,9 +6119,6 @@ async function readManifest(manifestPath) {
5926
6119
  return {};
5927
6120
  }
5928
6121
  }
5929
- async function writeManifest(manifestPath, manifest) {
5930
- await fs.writeJson(manifestPath, manifest, { spaces: 2 });
5931
- }
5932
6122
  async function loadAllContent(loaders, ctx) {
5933
6123
  const pagesDir = resolve(ctx.cacheDir, "pages");
5934
6124
  await fs.ensureDir(pagesDir);
@@ -5936,59 +6126,86 @@ async function loadAllContent(loaders, ctx) {
5936
6126
  const loaderLabel = colors.cyan(loader.name);
5937
6127
  consola.start(`[content-loader] Loading content from ${loaderLabel}...`);
5938
6128
  const manifestPath = getManifestPath(ctx.cacheDir, loader.name);
6129
+ const transaction = `${manifestPath}.transaction`;
6130
+ await recoverContentTransaction(transaction);
5939
6131
  const prevManifest = await readManifest(manifestPath);
5940
6132
  const nextManifest = {};
5941
- let items;
6133
+ const items = [];
6134
+ const routePaths = /* @__PURE__ */ new Set();
5942
6135
  try {
5943
- items = await loader.load(ctx);
5944
- } catch (e) {
5945
- consola.error(`[content-loader] Failed to load content from ${loaderLabel}:`, e);
6136
+ for (const original of await loader.load(ctx)) {
6137
+ let item;
6138
+ try {
6139
+ item = loader.transform ? await loader.transform(original) : original;
6140
+ const normalizedPath = normalize(item.path);
6141
+ const route = pagePathToRoute(normalizedPath).replace(/\/$/, "");
6142
+ if (isAbsolute(normalizedPath) || normalizedPath.startsWith("..") || item.path.includes("\\") || !normalizedPath.endsWith(".md"))
6143
+ throw new Error(`Invalid content path: ${item.path}`);
6144
+ if (routePaths.has(route))
6145
+ throw new Error(`Duplicate content route: ${item.path}`);
6146
+ for (const candidate of [normalizedPath, `${route}.md`, route ? `${route}/index.md` : "index.md"]) {
6147
+ if (!prevManifest[candidate] && await fs.pathExists(resolve(pagesDir, candidate)))
6148
+ throw new Error(`Content path is owned by another loader: ${item.path}`);
6149
+ }
6150
+ if (ctx.node.options.userRoot) {
6151
+ const userPages = resolve(ctx.node.options.userRoot, "pages");
6152
+ if (await fs.pathExists(resolve(userPages, `${route}.md`)) || await fs.pathExists(resolve(userPages, route, "index.md")))
6153
+ throw new Error(`Content route conflicts with a user page: ${item.path}`);
6154
+ }
6155
+ routePaths.add(route);
6156
+ items.push({ ...item, path: normalizedPath });
6157
+ } catch (error) {
6158
+ if (loader.strict)
6159
+ throw error;
6160
+ consola.warn(`[content-loader] Skipping ${original.path}:`, error);
6161
+ }
6162
+ }
6163
+ } catch (error) {
6164
+ consola.error(`[content-loader] Failed to load content from ${loaderLabel}:`, error);
6165
+ if (loader.strict && ctx.mode === "build")
6166
+ throw error;
5946
6167
  continue;
5947
6168
  }
5948
6169
  let written = 0;
5949
6170
  let cached = 0;
5950
- for (let item of items) {
5951
- if (loader.transform) {
5952
- try {
5953
- item = await loader.transform(item);
5954
- } catch (e) {
5955
- consola.error(`[content-loader] Failed to transform ${colors.dim(item.path)}:`, e);
5956
- continue;
5957
- }
5958
- }
5959
- const normalizedPath = normalize(item.path);
5960
- if (isAbsolute$1(normalizedPath) || normalizedPath.startsWith("..") || !normalizedPath.endsWith(".md")) {
5961
- consola.warn(`[content-loader] Skipping invalid path: ${colors.dim(item.path)}`);
5962
- continue;
5963
- }
6171
+ const changes = [];
6172
+ for (const item of items) {
6173
+ const normalizedPath = item.path;
5964
6174
  const filePath = resolve(pagesDir, normalizedPath);
5965
- if (!filePath.startsWith(pagesDir)) {
5966
- consola.warn(`[content-loader] Skipping path escaping cache directory: ${colors.dim(item.path)}`);
5967
- continue;
5968
- }
5969
6175
  const digest = item.digest || computeDigest(item.content);
5970
6176
  nextManifest[normalizedPath] = { digest };
5971
6177
  if (prevManifest[normalizedPath]?.digest === digest && await fs.pathExists(filePath)) {
5972
6178
  cached++;
5973
6179
  continue;
5974
6180
  }
5975
- await fs.ensureDir(dirname$1(filePath));
5976
- await fs.writeFile(filePath, item.content, "utf-8");
6181
+ changes.push({ path: filePath, content: item.content });
5977
6182
  written++;
5978
6183
  }
5979
6184
  const staleKeys = Object.keys(prevManifest).filter((key) => !(key in nextManifest));
5980
6185
  for (const key of staleKeys) {
5981
6186
  const stalePath = resolve(pagesDir, normalize(key));
5982
6187
  if (stalePath.startsWith(pagesDir) && await fs.pathExists(stalePath)) {
5983
- await fs.remove(stalePath);
5984
- consola.info(`[content-loader] Removed stale: ${colors.dim(key)}`);
6188
+ changes.push({ path: stalePath });
5985
6189
  }
5986
6190
  }
5987
- await writeManifest(manifestPath, nextManifest);
6191
+ changes.push({ path: manifestPath, content: JSON.stringify(nextManifest, null, 2) });
6192
+ try {
6193
+ await publishContentTransaction(transaction, changes);
6194
+ } catch (error) {
6195
+ consola.error(`[content-loader] Failed to publish ${loaderLabel}; previous content restored:`, error);
6196
+ if (loader.strict && ctx.mode === "build")
6197
+ throw error;
6198
+ continue;
6199
+ }
6200
+ await loader.onLoaded?.(ctx);
5988
6201
  consola.success(
5989
6202
  `[content-loader] ${loaderLabel}: ${colors.green(String(written))} written, ${colors.dim(String(cached))} cached, ${colors.dim(String(staleKeys.length))} removed`
5990
6203
  );
5991
6204
  }
6205
+ if (ctx.node.options.userRoot && ctx.node.options.pages) {
6206
+ const pages = [...(await discoverPageFiles(ctx.node.options.userRoot)).keys()].sort();
6207
+ ctx.node.options.pages.splice(0, ctx.node.options.pages.length, ...pages);
6208
+ }
5992
6209
  }
5993
6210
  const contentModule = defineValaxyModule({
5994
6211
  setup(node) {
@@ -6218,6 +6435,7 @@ async function createServer(valaxyApp, viteConfig = {}, serverOptions = {}) {
6218
6435
  vueDevtools.default(),
6219
6436
  valaxyDevtools.default({
6220
6437
  userRoot: options.userRoot,
6438
+ getAddons: () => valaxyApp.options.addons.map((addon) => ({ name: addon.name, version: addon.pkg.version })),
6221
6439
  plugins: options.addons.filter((addon) => addon.enable && addon.devtools).map((addon) => async () => addon.devtools({
6222
6440
  userRoot: options.userRoot,
6223
6441
  addonRoot: addon.root,
@@ -6317,7 +6535,7 @@ async function execBuild({ ssg, root, output, log, siteUrl }) {
6317
6535
  if (!await isPagesDirExist(root))
6318
6536
  throw new Error(`Pages directory not found: ${root}`);
6319
6537
  const userRoot = path.resolve(root);
6320
- const options = await resolveOptions({ userRoot }, "build");
6538
+ const options = await profileBuildPhase("resolve-options", () => resolveOptions({ userRoot }, "build"));
6321
6539
  if (siteUrl)
6322
6540
  options.config.siteConfig.url = siteUrl;
6323
6541
  setTimezone(options.config.siteConfig.timezone);
@@ -6352,7 +6570,7 @@ async function execBuild({ ssg, root, output, log, siteUrl }) {
6352
6570
  }
6353
6571
  );
6354
6572
  await callHookWithLog("config:init", valaxyApp);
6355
- await callHookWithLog("build:before", valaxyApp);
6573
+ await profileBuildPhase("build-before", () => callHookWithLog("build:before", valaxyApp));
6356
6574
  await validateTaxonomyI18n(options);
6357
6575
  consola.box("\u{1F320} Start building...");
6358
6576
  try {
@@ -6367,7 +6585,7 @@ async function execBuild({ ssg, root, output, log, siteUrl }) {
6367
6585
  await build$1(valaxyApp, viteConfig);
6368
6586
  }
6369
6587
  } finally {
6370
- await callHookWithLog("build:after", valaxyApp);
6588
+ await profileBuildPhase("build-after", () => callHookWithLog("build:after", valaxyApp));
6371
6589
  }
6372
6590
  }
6373
6591
  function registerBuildCommand(cli) {
@@ -6473,7 +6691,7 @@ const safeMatterOptions = {
6473
6691
  };
6474
6692
  function inside(root, file) {
6475
6693
  const path = relative(root, file);
6476
- return path !== ".." && !path.startsWith("../") && !isAbsolute$1(path);
6694
+ return path !== ".." && !path.startsWith("../") && !isAbsolute(path);
6477
6695
  }
6478
6696
  function normalizeRoute(path) {
6479
6697
  return new URL(path, "http://valaxy.local").pathname.replace(/\/$/, "") || "/";
@@ -6506,7 +6724,7 @@ function createContentService(app, settings = {}) {
6506
6724
  throw new Error("Page unavailable under the MCP visibility policy.");
6507
6725
  }
6508
6726
  async function read(path) {
6509
- if (isAbsolute$1(path) || !path.startsWith("pages/") || path.includes("\\") || path.split("/").includes("..") || !path.endsWith(".md"))
6727
+ if (isAbsolute(path) || !path.startsWith("pages/") || path.includes("\\") || path.split("/").includes("..") || !path.endsWith(".md"))
6510
6728
  throw new Error("Use a site-relative Markdown path beginning with pages/, without parent directory segments.");
6511
6729
  const file = resolve(userRoot, path);
6512
6730
  const [realRoot, realPages, realFile] = await Promise.all([realpath(userRoot), realpath(pagesRoot), realpath(file)]);
@@ -7324,4 +7542,4 @@ async function run(argv = hideBin(process.argv), options = {}) {
7324
7542
  await cli.parseAsync();
7325
7543
  }
7326
7544
 
7327
- export { resolveValaxyConfigFromRoot as $, ALL_ROUTE as A, isInstalledGlobally as B, isKatexEnabled as C, isKatexPluginNeeded as D, EXCERPT_SEPARATOR as E, isMathJaxEnabled as F, GLOBAL_STATE as G, isPath as H, loadConfigFromFile as I, mergeValaxyConfig as J, mergeViteConfigs as K, postProcessForSSG as L, processValaxyOptions as M, registerDevCommand as N, resolveAddonsConfig as O, PATHNAME_PROTOCOL_RE as P, resolveImportPath as Q, resolveImportUrl as R, StateManager as S, resolveOptions as T, resolveSiteConfig as U, ViteValaxyPlugins as V, resolveSiteConfigFromRoot as W, resolveThemeConfigFromRoot as X, resolveThemeValaxyConfig as Y, resolveUserThemeConfig as Z, resolveValaxyConfig as _, createContentService as a, run as a0, ssgBuild as a1, startValaxyDev as a2, toAtFS as a3, transformObject as a4, version as a5, build$1 as b, createCli as c, createMemoryReleasePlugin as d, createServer as e, createValaxyNode as f, createValaxyPlugin as g, customElements as h, defaultSiteConfig as i, defaultValaxyConfig as j, defaultViteConfig as k, defineAddon as l, defineConfig as m, defineSiteConfig as n, defineTheme as o, defineValaxyAddon as p, defineValaxyConfig as q, defineValaxyTheme as r, desktopRuntimeVersion as s, encryptContent as t, execBuild as u, generateClientRedirects as v, getGitTimestamp as w, getIndexHtml as x, getServerInfoText as y, isExternal as z };
7545
+ export { resolveValaxyConfig as $, ALL_ROUTE as A, isInstalledGlobally as B, isKatexEnabled as C, isKatexPluginNeeded as D, EXCERPT_SEPARATOR as E, isMathJaxEnabled as F, GLOBAL_STATE as G, isPath as H, loadAllContent as I, loadConfigFromFile as J, mergeValaxyConfig as K, mergeViteConfigs as L, postProcessForSSG as M, processValaxyOptions as N, registerDevCommand as O, PATHNAME_PROTOCOL_RE as P, resolveAddonsConfig as Q, resolveImportPath as R, StateManager as S, resolveImportUrl as T, resolveOptions as U, ViteValaxyPlugins as V, resolveSiteConfig as W, resolveSiteConfigFromRoot as X, resolveThemeConfigFromRoot as Y, resolveThemeValaxyConfig as Z, resolveUserThemeConfig as _, createContentService as a, resolveValaxyConfigFromRoot as a0, run as a1, ssgBuild as a2, startValaxyDev as a3, toAtFS as a4, transformObject as a5, version as a6, build$1 as b, createCli as c, createMemoryReleasePlugin as d, createServer as e, createValaxyNode as f, createValaxyPlugin as g, customElements as h, defaultSiteConfig as i, defaultValaxyConfig as j, defaultViteConfig as k, defineAddon as l, defineConfig as m, defineSiteConfig as n, defineTheme as o, defineValaxyAddon as p, defineValaxyConfig as q, defineValaxyTheme as r, desktopRuntimeVersion as s, encryptContent as t, execBuild as u, generateClientRedirects as v, getGitTimestamp as w, getIndexHtml as x, getServerInfoText as y, isExternal as z };
@@ -1,5 +1,5 @@
1
- import { c as Post } from '../shared/valaxy.VM_duYKy.mjs';
2
- export { A as Album, B as BaseFrontMatter, D as DefaultTheme, E as ExcerptType, F as FuseListItem, d as Page, e as PageFrontMatter, P as PartialDeep, f as Photo, g as Pkg, h as PostFrontMatter, a as RedirectItem, i as RedirectRule, R as RuntimeConfig, S as SiteConfig, j as SocialLink, U as UserSiteConfig, k as UserValaxyConfig, b as ValaxyAddon, V as ValaxyConfig } from '../shared/valaxy.VM_duYKy.mjs';
1
+ import { c as Post } from '../shared/valaxy.BxsKyIbS.mjs';
2
+ export { A as Album, B as BaseFrontMatter, D as DefaultTheme, E as ExcerptType, F as FuseListItem, d as Page, e as PageFrontMatter, P as PartialDeep, f as Photo, g as Pkg, h as PostFrontMatter, a as RedirectItem, i as RedirectRule, R as RuntimeConfig, S as SiteConfig, j as SocialLink, U as UserSiteConfig, k as UserValaxyConfig, b as ValaxyAddon, V as ValaxyConfig } from '../shared/valaxy.BxsKyIbS.mjs';
3
3
  import { Header } from '@valaxyjs/utils';
4
4
  import '@vueuse/integrations/useFuse';
5
5
  import 'medium-zoom';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "valaxy",
3
3
  "type": "module",
4
- "version": "1.0.0-rc.12",
4
+ "version": "1.0.0-rc.14",
5
5
  "description": "📄 Vite & Vue powered static blog generator.",
6
6
  "author": {
7
7
  "email": "me@yunyoujun.cn",
@@ -74,6 +74,8 @@
74
74
  "@unhead/bundler": "^3.4.1",
75
75
  "@unhead/schema-org": "^3.4.1",
76
76
  "@unhead/vue": "^3.4.1",
77
+ "@valaxyjs/devtools": "1.0.0-rc.14",
78
+ "@valaxyjs/utils": "1.0.0-rc.14",
77
79
  "@vitejs/devtools": "0.7.5",
78
80
  "@vitejs/plugin-vue": "^6.0.9",
79
81
  "@vueuse/core": "^15.0.0",
@@ -96,10 +98,10 @@
96
98
  "hookable": "^6.1.2",
97
99
  "html-to-text": "^10.0.1",
98
100
  "jiti": "^2.7.0",
99
- "js-base64": "^3.9.3",
101
+ "js-base64": "^3.9.4",
100
102
  "js-yaml": "^5.4.2",
101
103
  "katex": "^0.18.7",
102
- "lru-cache": "^11.5.2",
104
+ "lru-cache": "^11.5.3",
103
105
  "markdown-exit": "^1.3.0",
104
106
  "markdown-it": "^15.0.2",
105
107
  "markdown-it-anchor": "^10.0.0",
@@ -130,7 +132,7 @@
130
132
  "unhead": "^3.4.1",
131
133
  "unocss": "66.10.5",
132
134
  "unplugin-vue-components": "28.0.0",
133
- "unplugin-vue-markdown": "^32.0.0",
135
+ "unplugin-vue-markdown": "^32.1.1",
134
136
  "vanilla-lazyload": "^19.1.3",
135
137
  "vite": "^8.3.0",
136
138
  "vite-plugin-vue-devtools": "^8.2.1",
@@ -138,9 +140,7 @@
138
140
  "vite-ssg-sitemap": "^0.10.0",
139
141
  "vitepress-plugin-group-icons": "^1.7.6",
140
142
  "vue-i18n": "^11.4.12",
141
- "yargs": "^18.1.0",
142
- "@valaxyjs/utils": "1.0.0-rc.12",
143
- "@valaxyjs/devtools": "1.0.0-rc.12"
143
+ "yargs": "^18.1.0"
144
144
  },
145
145
  "devDependencies": {
146
146
  "@mdit-vue/plugin-component": "^3.0.2",
package/types/config.ts CHANGED
@@ -509,7 +509,7 @@ export interface ValaxyConfig<ThemeConfig = DefaultTheme.Config> {
509
509
  /**
510
510
  * @en Site **info** config. This affects info displayed on the site, and is independent of themes.
511
511
  * @zh 站点**信息**配置,这部分内容面向站点展示,且在不同主题中也是通用的格式
512
- * @see [站点配置 | Valaxy](https://valaxy.site/guide/config#%E7%AB%99%E7%82%B9%E9%85%8D%E7%BD%AE)
512
+ * @see [站点配置 | Valaxy](https://valaxy.site/zh/guide/config#site-config)
513
513
  * @see [Site Config | Valaxy](https://valaxy.site/guide/config#site-config)
514
514
  */
515
515
  siteConfig: SiteConfig
@@ -28,6 +28,8 @@ export interface Photo {
28
28
  }
29
29
 
30
30
  export interface BaseFrontMatter extends Record<string, any> {
31
+ /** Canonical URL or site-relative path, independent of the current route alias. */
32
+ canonical?: string
31
33
  /**
32
34
  * Title
33
35
  * @description 文章标题