@ubean/build 0.6.5 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- export { d as BUILTIN_PRESETS, t as CODEGEN_CONTRACT_VERSION, n as CODEGEN_FILES, r as CODEGEN_NON_CONTRACT_FILES, p as HONO_OPENAPI_PRESET, m as UBEAN_CLIENT_PRESET, h as UBEAN_SERVER_PRESET, g as VUE_I18N_PRESET, _ as VUE_MACROS_PRESET, v as VUE_PRESET, y as VUE_ROUTER_PRESET, b as generateAutoImports, l as generateI18nTypes, x as generateImportsTransform, a as generateOpenApiTypes, o as generateOpenApiTypesFromServer, s as generatePageTypes, c as generateRouteTypes, i as generateTypes, S as getAutoImportPresets, C as getBuiltinComposables, w as getUbeanAutoImportConfig, T as getUbeanComponentsConfig, u as messagesToTsType, E as resolveAutoImportsConfig, D as resolveComponentsConfig, O as toArray } from "../codegen-BL0s5Pyq.js";
1
+ export { d as BUILTIN_PRESETS, t as CODEGEN_CONTRACT_VERSION, n as CODEGEN_FILES, r as CODEGEN_NON_CONTRACT_FILES, p as HONO_OPENAPI_PRESET, m as UBEAN_CLIENT_PRESET, h as UBEAN_SERVER_PRESET, g as VUE_I18N_PRESET, _ as VUE_MACROS_PRESET, v as VUE_PRESET, y as VUE_ROUTER_PRESET, b as generateAutoImports, l as generateI18nTypes, x as generateImportsTransform, a as generateOpenApiTypes, o as generateOpenApiTypesFromServer, s as generatePageTypes, c as generateRouteTypes, i as generateTypes, S as getAutoImportPresets, C as getBuiltinComposables, w as getUbeanAutoImportConfig, T as getUbeanComponentsConfig, u as messagesToTsType, E as resolveAutoImportsConfig, D as resolveComponentsConfig, O as toArray } from "../codegen-CUlE95gB.js";
@@ -810,6 +810,8 @@ async function generatePageTypes(result, options) {
810
810
  " filePath: string;",
811
811
  " layout?: string;",
812
812
  " reuseTarget?: string;",
813
+ " /** 是否参与路由注册(false = 只进页面清单)。 */",
814
+ " routable?: boolean;",
813
815
  " }",
814
816
  "",
815
817
  " export interface LayoutInfo {",
@@ -819,7 +821,7 @@ async function generatePageTypes(result, options) {
819
821
  " }",
820
822
  ""
821
823
  ];
822
- const pageNames = pages.map((p) => JSON.stringify(p.name));
824
+ const pageNames = pages.filter((p) => p.routable !== false).map((p) => JSON.stringify(p.name));
823
825
  if (pageNames.length > 0) {
824
826
  lines.push(" export type RouteName =");
825
827
  lines.push(pageNames.map((n) => ` | ${n}`).join("\n"));
@@ -834,6 +836,7 @@ async function generatePageTypes(result, options) {
834
836
  } else lines.push(" export type LayoutName = string;");
835
837
  lines.push("");
836
838
  lines.push(" export const pages: Record<RouteName, PageInfo>;");
839
+ lines.push(" export const pageEntries: Record<string, PageInfo>;");
837
840
  lines.push(" export const layouts: Record<LayoutName, LayoutInfo>;");
838
841
  lines.push("}");
839
842
  const content = `${lines.join("\n")}\n`;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { a as VirtualModuleTransform, c as defineVirtualModulePrefix, i as VirtualModuleResolver, l as resetVirtualRegistry, n as VirtualModuleContext, o as createVirtualRegistry, r as VirtualModuleRegistry, s as defineVirtualModule, t as VirtualModule, u as useVirtualRegistry } from "./virtual-registry-CaU8k-YP.js";
2
+ import "@ubean/vue/vite";
2
3
  import { CompiledLayout, CompiledMiddleware, CompiledPage, CompiledRoute } from "@ubean/routes";
3
4
  import { ScannedApiRoute, ScannedLocale, ScannedMiddleware, ScannedPageRoute } from "@ubean/scan";
4
5
  //#region src/macros.d.ts
@@ -49,6 +50,21 @@ export declare function registerCssImport(cssPath: string): void;
49
50
  * Called by `createClientEntryVirtualModule` to prepend CSS imports.
50
51
  */
51
52
  export declare function getCssImports(): string[];
53
+ /**
54
+ * Register an inline `<script>` to be injected as the first element of `<head>`.
55
+ * e.g. `@ubean/integrations/ui` registers `@vean/theme`'s first-paint script so a
56
+ * project using `ui: true` needs no manual `useHead()` injection.
57
+ *
58
+ * The script must be self-contained and must run **before** any blocking
59
+ * stylesheet: the three injection points (`transformIndexHtml`, the fullstack
60
+ * server entry and the ssg static entry) all prepend it right after `<head>`.
61
+ */
62
+ export declare function registerHeadScript(script: string): void;
63
+ /**
64
+ * Get all registered head scripts, joined in registration order.
65
+ * Called by the dev HTML transform and the build-time server/ssg entries.
66
+ */
67
+ export declare function getHeadScripts(): string;
52
68
  /**
53
69
  * Reset the registry (for testing).
54
70
  * @internal
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { _ as resetVirtualRegistry, a as ssrSingletonProdOptimizeExclude, c as getComponentResolvers, d as registerCssImport, f as resetModuleRegistry, g as defineVirtualModulePrefix, h as defineVirtualModule, i as ssrSingletonDevPolicy, l as getCssImports, m as createVirtualRegistry, n as SSR_SINGLETON_OPTIMIZE_EXCLUDE, o as ssrSingletonProdSsr, p as VirtualModuleRegistry, r as SSR_SINGLETON_PACKAGES, t as SSR_SINGLETON_DEDUPE, u as registerComponentResolver, v as useVirtualRegistry } from "./ssr-singleton-Bbds29jS.js";
2
- import { a as createRoutingVirtualModule, i as createPagesVirtualModule, n as createLocalesVirtualModule, o as stripMacros, r as createMetaVirtualModule, s as transformMacros, t as createAppVirtualModule } from "./virtual-modules-BK0L1Op-.js";
3
- export { SSR_SINGLETON_DEDUPE, SSR_SINGLETON_OPTIMIZE_EXCLUDE, SSR_SINGLETON_PACKAGES, VirtualModuleRegistry, createAppVirtualModule, createLocalesVirtualModule, createMetaVirtualModule, createPagesVirtualModule, createRoutingVirtualModule, createVirtualRegistry, defineVirtualModule, defineVirtualModulePrefix, getComponentResolvers, getCssImports, registerComponentResolver, registerCssImport, resetModuleRegistry, resetVirtualRegistry, ssrSingletonDevPolicy, ssrSingletonProdOptimizeExclude, ssrSingletonProdSsr, stripMacros, transformMacros, useVirtualRegistry };
1
+ import { _ as defineVirtualModule, a as ssrSingletonProdOptimizeExclude, b as useVirtualRegistry, c as getComponentResolvers, d as registerComponentResolver, f as registerCssImport, g as createVirtualRegistry, h as VirtualModuleRegistry, i as ssrSingletonDevPolicy, l as getCssImports, m as resetModuleRegistry, n as SSR_SINGLETON_OPTIMIZE_EXCLUDE, o as ssrSingletonProdSsr, p as registerHeadScript, r as SSR_SINGLETON_PACKAGES, t as SSR_SINGLETON_DEDUPE, u as getHeadScripts, v as defineVirtualModulePrefix, y as resetVirtualRegistry } from "./ssr-singleton-CUHZLgiO.js";
2
+ import { a as createRoutingVirtualModule, i as createPagesVirtualModule, n as createLocalesVirtualModule, o as stripMacros, r as createMetaVirtualModule, s as transformMacros, t as createAppVirtualModule } from "./virtual-modules-B3aE-Fmn.js";
3
+ export { SSR_SINGLETON_DEDUPE, SSR_SINGLETON_OPTIMIZE_EXCLUDE, SSR_SINGLETON_PACKAGES, VirtualModuleRegistry, createAppVirtualModule, createLocalesVirtualModule, createMetaVirtualModule, createPagesVirtualModule, createRoutingVirtualModule, createVirtualRegistry, defineVirtualModule, defineVirtualModulePrefix, getComponentResolvers, getCssImports, getHeadScripts, registerComponentResolver, registerCssImport, registerHeadScript, resetModuleRegistry, resetVirtualRegistry, ssrSingletonDevPolicy, ssrSingletonProdOptimizeExclude, ssrSingletonProdSsr, stripMacros, transformMacros, useVirtualRegistry };
package/dist/prerender.js CHANGED
@@ -65,6 +65,7 @@ function collectPrerenderRoutes(pages, options = {}) {
65
65
  ];
66
66
  const allPageRoutes = [];
67
67
  for (const page of pages) {
68
+ if (page.routable === false) continue;
68
69
  const path = normalizePagePath(page.path);
69
70
  if (!isDynamicPath(path)) allPageRoutes.push(path);
70
71
  }
@@ -1 +1 @@
1
- export { T as buildWithEnvironments, v as createIslandsSsrStubPlugin, y as generateCloudflareWorkerEntry, b as generateNodeServerEntry, x as generateStandardHandlerEntry, S as generateVirtualModulesToDisk, C as getPresetBuildConfig, w as serializePagesForEntry } from "./vite-CmtXmVIm.js";
1
+ export { T as buildWithEnvironments, v as createIslandsSsrStubPlugin, y as generateCloudflareWorkerEntry, b as generateNodeServerEntry, x as generateStandardHandlerEntry, S as generateVirtualModulesToDisk, C as getPresetBuildConfig, w as serializePagesForEntry } from "./vite--HujaLpA.js";
@@ -101,7 +101,8 @@ function getRegistry() {
101
101
  const g = globalThis;
102
102
  if (!g[REGISTRY_KEY]) g[REGISTRY_KEY] = {
103
103
  componentResolvers: [],
104
- cssImports: []
104
+ cssImports: [],
105
+ headScripts: []
105
106
  };
106
107
  return g[REGISTRY_KEY];
107
108
  }
@@ -136,6 +137,27 @@ function getCssImports() {
136
137
  return [...getRegistry().cssImports];
137
138
  }
138
139
  /**
140
+ * Register an inline `<script>` to be injected as the first element of `<head>`.
141
+ * e.g. `@ubean/integrations/ui` registers `@vean/theme`'s first-paint script so a
142
+ * project using `ui: true` needs no manual `useHead()` injection.
143
+ *
144
+ * The script must be self-contained and must run **before** any blocking
145
+ * stylesheet: the three injection points (`transformIndexHtml`, the fullstack
146
+ * server entry and the ssg static entry) all prepend it right after `<head>`.
147
+ */
148
+ function registerHeadScript(script) {
149
+ if (!script) return;
150
+ const reg = getRegistry();
151
+ if (!reg.headScripts.includes(script)) reg.headScripts.push(script);
152
+ }
153
+ /**
154
+ * Get all registered head scripts, joined in registration order.
155
+ * Called by the dev HTML transform and the build-time server/ssg entries.
156
+ */
157
+ function getHeadScripts() {
158
+ return getRegistry().headScripts.join("\n");
159
+ }
160
+ /**
139
161
  * Reset the registry (for testing).
140
162
  * @internal
141
163
  */
@@ -143,6 +165,7 @@ function resetModuleRegistry() {
143
165
  const reg = getRegistry();
144
166
  reg.componentResolvers.length = 0;
145
167
  reg.cssImports.length = 0;
168
+ reg.headScripts.length = 0;
146
169
  }
147
170
  //#endregion
148
171
  //#region src/ssr-singleton.ts
@@ -215,4 +238,4 @@ function ssrSingletonProdOptimizeExclude(extra = []) {
215
238
  return [...SSR_SINGLETON_OPTIMIZE_EXCLUDE, ...extra];
216
239
  }
217
240
  //#endregion
218
- export { resetVirtualRegistry as _, ssrSingletonProdOptimizeExclude as a, getComponentResolvers as c, registerCssImport as d, resetModuleRegistry as f, defineVirtualModulePrefix as g, defineVirtualModule as h, ssrSingletonDevPolicy as i, getCssImports as l, createVirtualRegistry as m, SSR_SINGLETON_OPTIMIZE_EXCLUDE as n, ssrSingletonProdSsr as o, VirtualModuleRegistry as p, SSR_SINGLETON_PACKAGES as r, ssr_singleton_exports as s, SSR_SINGLETON_DEDUPE as t, registerComponentResolver as u, useVirtualRegistry as v, __exportAll as y };
241
+ export { defineVirtualModule as _, ssrSingletonProdOptimizeExclude as a, useVirtualRegistry as b, getComponentResolvers as c, registerComponentResolver as d, registerCssImport as f, createVirtualRegistry as g, VirtualModuleRegistry as h, ssrSingletonDevPolicy as i, getCssImports as l, resetModuleRegistry as m, SSR_SINGLETON_OPTIMIZE_EXCLUDE as n, ssrSingletonProdSsr as o, registerHeadScript as p, SSR_SINGLETON_PACKAGES as r, ssr_singleton_exports as s, SSR_SINGLETON_DEDUPE as t, getHeadScripts as u, defineVirtualModulePrefix as v, __exportAll as x, resetVirtualRegistry as y };
@@ -57,7 +57,10 @@ export interface StaticSsgRendererI18nInit {
57
57
  defaultLocale?: string;
58
58
  locales?: Array<string | {
59
59
  code: string;
60
+ path?: string;
60
61
  }>;
62
+ /** Locale code → URL segment override. See `LocaleRoutingConfig.paths`. */
63
+ paths?: Record<string, string>;
61
64
  }
62
65
  export interface StaticSsgRendererInit {
63
66
  /** 扫描得到的页面(含动态路由模式,供具象 URL 匹配) */
@@ -144,13 +144,14 @@ function expandRoutesForLocales(routes, i18n) {
144
144
  const strategy = i18n.strategy || "prefix_except_default";
145
145
  if (strategy === "no_prefix") return dedupeRoutes(routes);
146
146
  const defaultLocale = i18n.defaultLocale || localeCodes[0] || "";
147
+ const seg = (code) => segmentOf(code, i18n.paths);
147
148
  const expanded = [];
148
149
  for (const route of routes) {
149
150
  if (route === "/__ubean_404__") {
150
151
  expanded.push(route);
151
152
  continue;
152
153
  }
153
- const { locale } = extractLocaleFromPath(route, localeCodes);
154
+ const { locale } = extractLocaleFromPath(route, localeCodes, i18n.paths);
154
155
  if (locale) {
155
156
  expanded.push(route);
156
157
  continue;
@@ -158,22 +159,26 @@ function expandRoutesForLocales(routes, i18n) {
158
159
  const suffix = route === "/" || route === "" ? "" : route;
159
160
  switch (strategy) {
160
161
  case "prefix":
161
- for (const code of localeCodes) expanded.push(`/${code}${suffix}`);
162
+ for (const code of localeCodes) expanded.push(`/${seg(code)}${suffix}`);
162
163
  break;
163
164
  case "prefix_and_default":
164
165
  expanded.push(route || "/");
165
- for (const code of localeCodes) expanded.push(`/${code}${suffix}`);
166
+ for (const code of localeCodes) expanded.push(`/${seg(code)}${suffix}`);
166
167
  break;
167
168
  default:
168
169
  expanded.push(route || "/");
169
170
  for (const code of localeCodes) {
170
171
  if (code === defaultLocale) continue;
171
- expanded.push(`/${code}${suffix}`);
172
+ expanded.push(`/${seg(code)}${suffix}`);
172
173
  }
173
174
  }
174
175
  }
175
176
  return dedupeRoutes(expanded);
176
177
  }
178
+ /** URL segment for a locale code (`paths` override, else the code). */
179
+ function segmentOf(code, paths) {
180
+ return paths?.[code] ?? code;
181
+ }
177
182
  /**
178
183
  * 加载构建产物中的静态 entry(`dist/server/entry.mjs`),返回静态渲染器。
179
184
  *
@@ -210,7 +215,8 @@ async function createStaticSsgRenderer(cwd, manifest, init) {
210
215
  enabled: i18nEnabled,
211
216
  strategy,
212
217
  defaultLocale,
213
- locales: localeCodes
218
+ locales: localeCodes,
219
+ paths: init.i18n?.paths
214
220
  }),
215
221
  fetcher: async (url) => {
216
222
  const u = new URL(url, "http://ubean.local");
@@ -231,7 +237,7 @@ async function createStaticSsgRenderer(cwd, manifest, init) {
231
237
  let pathToMatch = pathname;
232
238
  let locale = defaultLocale;
233
239
  if (usePrefix) {
234
- const { locale: extracted, pathWithoutLocale } = extractLocaleFromPath(pathname, localeCodes);
240
+ const { locale: extracted, pathWithoutLocale } = extractLocaleFromPath(pathname, localeCodes, init.i18n?.paths);
235
241
  if (extracted) {
236
242
  locale = extracted;
237
243
  pathToMatch = pathWithoutLocale;
@@ -1,98 +1,82 @@
1
- import { h as defineVirtualModule } from "./ssr-singleton-Bbds29jS.js";
1
+ import { _ as defineVirtualModule } from "./ssr-singleton-CUHZLgiO.js";
2
+ import { extractScriptBlocks, parseScriptAst, statementCall } from "@ubean/vue/vite";
2
3
  import { isAbsolute, relative } from "pathe";
3
4
  //#region src/macros.ts
5
+ /**
6
+ * 宏剥除(`definePage` 等编译期宏从产物中移除)。
7
+ *
8
+ * 实现方式:解析成 AST 后,按节点 `start` / `end` 区间**删除整条语句**。
9
+ *
10
+ * 此前是手写的括号平衡扫描 + 字符串切片,有两个静默故障面:
11
+ *
12
+ * 1. 提到宏的字符串/注释被一起切掉 —— `const doc = "definePage({...})"`
13
+ * 变成 `const doc = ""`,`// 用法:definePage({...})` 变成 `// 用法:`;
14
+ * 2. 正则字面量里的括号让括号计数错位(`const re = /\\(/g`)。
15
+ *
16
+ * 区间删除天然不会碰到这两种情况:拼接出的字符串里不存在 `definePage` 这个词,
17
+ * 注释与正则都只存在于 AST 之外。
18
+ *
19
+ * 解析器来自 `@ubean/vue/vite`(基于 `vue/compiler-sfc` 的 `babelParse`),与
20
+ * `definePage` 元数据提取共用同一份实现 —— 一处解析,两个消费者。
21
+ */
4
22
  const MACRO_NAMES = ["definePage"];
5
- function findBalancedCall(code, funcName, startSearch = 0) {
6
- const pattern = new RegExp(`\\b${funcName}\\s*\\(`, "g");
7
- pattern.lastIndex = startSearch;
8
- const match = pattern.exec(code);
9
- if (!match) return null;
10
- const startIdx = match.index;
11
- const parenStart = match.index + match[0].length;
12
- let depth = 1;
13
- let i = parenStart;
14
- let inString = null;
15
- let escaped = false;
16
- let inTemplateExpr = 0;
17
- while (i < code.length && depth > 0) {
18
- const ch = code[i];
19
- if (escaped) {
20
- escaped = false;
21
- i++;
22
- continue;
23
- }
24
- if (ch === "\\") {
25
- escaped = true;
26
- i++;
27
- continue;
28
- }
29
- if (inString) {
30
- if (inString === "`" && ch === "$" && code[i + 1] === "{") {
31
- inTemplateExpr++;
32
- i += 2;
33
- continue;
34
- }
35
- if (inString === "`" && ch === "}" && inTemplateExpr > 0) {
36
- inTemplateExpr--;
37
- i++;
38
- continue;
39
- }
40
- if (ch === inString) inString = null;
41
- i++;
42
- continue;
43
- }
44
- if (ch === "\"" || ch === "'" || ch === "`") {
45
- inString = ch;
46
- i++;
47
- continue;
48
- }
49
- if (ch === "/" && code[i + 1] === "/") {
50
- while (i < code.length && code[i] !== "\n") i++;
51
- continue;
52
- }
53
- if (ch === "/" && code[i + 1] === "*") {
54
- i += 2;
55
- while (i < code.length && !(code[i] === "*" && code[i + 1] === "/")) i++;
56
- i += 2;
57
- continue;
58
- }
59
- if (ch === "(" || ch === "{" || ch === "[") depth++;
60
- else if (ch === ")" || ch === "}" || ch === "]") {
61
- depth--;
62
- if (depth === 0 && ch === ")") return {
63
- start: startIdx,
64
- end: i + 1
65
- };
66
- }
67
- i++;
23
+ /**
24
+ * 判断一条**顶层语句**是否需要整条删除,返回其源码区间。
25
+ *
26
+ * 支持三种形状:
27
+ * - `definePage({...});` → `ExpressionStatement`
28
+ * - `export default definePage({...});` → `ExportDefaultDeclaration`
29
+ * (`.reuse.ts` / `.meta.ts` 的写法;只删 `definePage(...)` 会留下悬空的
30
+ * `export default`,语法错误)
31
+ * - 语句外的包裹(如 `if (x) definePage(...)`)不删 —— 那意味着宏写在条件分支里,
32
+ * 属于用户错误,整条删掉会连带删掉条件本身。
33
+ */
34
+ function macroStatementRange(statement, macro) {
35
+ if (!statementCall(statement, macro)) return null;
36
+ const start = statement.start;
37
+ const end = statement.end;
38
+ if (typeof start !== "number" || typeof end !== "number") return null;
39
+ return {
40
+ start,
41
+ end
42
+ };
43
+ }
44
+ /**
45
+ * 删除源码中给定区间,额外吞掉紧邻的空白与一个尾随分号。
46
+ *
47
+ * 之所以要吞分号:`ExpressionStatement` 的 `end` 在 babel 里**不含**尾随
48
+ * 分号(它属于 `statement.start`..`expression.end` 之外的 extra 信息),
49
+ * 不吞就会在产物里留下一个孤立的 `;`。
50
+ */
51
+ function spliceOut(code, ranges) {
52
+ const sorted = [...ranges].sort((a, b) => b.start - a.start);
53
+ let result = code;
54
+ for (const { start, end } of sorted) {
55
+ let from = start;
56
+ let to = end;
57
+ let cursor = to;
58
+ while (cursor < result.length && (result[cursor] === " " || result[cursor] === " ")) cursor++;
59
+ if (result[cursor] === ";") to = cursor + 1;
60
+ while (from > 0 && (result[from - 1] === " " || result[from - 1] === " ")) from--;
61
+ result = result.slice(0, from) + result.slice(to);
68
62
  }
69
- return null;
63
+ return result;
70
64
  }
71
- function stripStatement(code, callStart, callEnd) {
72
- let start = callStart;
73
- let end = callEnd;
74
- while (start > 0 && /[ \t]/.test(code[start - 1])) start--;
75
- const exportDefaultMatch = code.slice(0, start).match(/export\s+default\s*$/);
76
- if (exportDefaultMatch) {
77
- start -= exportDefaultMatch[0].length;
78
- while (start > 0 && /[ \t\n\r]/.test(code[start - 1])) start--;
65
+ /** 在单个脚本块内剥除宏。 */
66
+ function stripMacrosFromCode(code, macros, fileName = "page.ts") {
67
+ if (macros.length === 0) return code;
68
+ const ast = parseScriptAst(code, fileName);
69
+ if (!ast) return code;
70
+ const body = ast.program.body ?? [];
71
+ const ranges = [];
72
+ for (const statement of body) for (const macro of macros) {
73
+ const range = macroStatementRange(statement, macro);
74
+ if (range) ranges.push(range);
79
75
  }
80
- if (code[end] === ";") end++;
81
- while (end < code.length && /[ \t]/.test(code[end])) end++;
82
- return code.slice(0, start) + code.slice(end);
76
+ return ranges.length > 0 ? spliceOut(code, ranges) : code;
83
77
  }
84
78
  function stripMacros(code, macros = MACRO_NAMES) {
85
- let result = code;
86
- for (const macro of macros) {
87
- let offset = 0;
88
- while (true) {
89
- const found = findBalancedCall(result, macro, offset);
90
- if (!found) break;
91
- result = stripStatement(result, found.start, found.end);
92
- offset = found.start;
93
- }
94
- }
95
- return result;
79
+ return stripMacrosFromCode(code, macros);
96
80
  }
97
81
  function transformMacros(code, id) {
98
82
  if (!(id.includes("/src/pages/") || id.includes("/src/routes/") || id.includes("/src/middleware/"))) return null;
@@ -114,12 +98,32 @@ const PLAIN_SCRIPT_RE = /<script(?![^>]*\bsetup\b)[^>]*>/;
114
98
  * 而 `definePage` 是宏、必被剥掉 —— 一个只有 loader 的页面正好落在坑里。
115
99
  */
116
100
  const EMPTY_SETUP_KEEP_ALIVE = "\n// ubean: 宏已剥离,保留此块以维持组件的默认导出(见 builder/src/macros.ts)\n";
101
+ /**
102
+ * SFC 宏剥除。
103
+ *
104
+ * 用 `extractScriptBlocks`(即 `@vue/compiler-sfc` 的 `parse`)拿到每个 `<script>`
105
+ * 块在**原文件**中的精确区间,逐块删除后按偏移倒序回写 —— 而不是用
106
+ * `/<script([^>]*)>([\s\S]*?)<\/script>/g` 猜标签边界(该正则在 `<script>` 出现在
107
+ * 字符串或注释里时会错位)。
108
+ */
117
109
  function transformVueMacros(code) {
110
+ const blocks = extractScriptBlocks(code, "page.vue");
111
+ if (!blocks || blocks.length === 0) return code;
118
112
  const hasPlainScript = PLAIN_SCRIPT_RE.test(code);
119
- return code.replace(/<script([^>]*)>([\s\S]*?)<\/script>/g, (_match, attrs, content) => {
120
- const stripped = stripMacros(content);
121
- return `<script${attrs}>${/\bsetup\b/.test(attrs) && hasPlainScript && !stripped.trim() ? EMPTY_SETUP_KEEP_ALIVE : stripped}<\/script>`;
122
- });
113
+ const edits = [];
114
+ for (const block of blocks) {
115
+ const stripped = stripMacrosFromCode(block.content, MACRO_NAMES, `page.${block.lang || "ts"}`);
116
+ const keepAlive = block.setup && hasPlainScript && !stripped.trim() ? EMPTY_SETUP_KEEP_ALIVE : stripped;
117
+ if (keepAlive !== block.content) edits.push({
118
+ start: block.start,
119
+ end: block.end,
120
+ text: keepAlive
121
+ });
122
+ }
123
+ if (edits.length === 0) return code;
124
+ let result = code;
125
+ for (const edit of [...edits].sort((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
126
+ return result;
123
127
  }
124
128
  //#endregion
125
129
  //#region src/virtual-modules.ts
@@ -145,7 +149,7 @@ function createRoutingVirtualModule(routes, middlewares, cwd) {
145
149
  }
146
150
  function createPagesVirtualModule(pages, layouts, cwd) {
147
151
  return defineVirtualModule("ubean:pages", () => {
148
- return `export const pages = {\n${pages.map((p) => ` ${JSON.stringify(p.name)}: { name: ${JSON.stringify(p.name)}, path: ${JSON.stringify(p.path)}, filePath: ${JSON.stringify(toPortableFilePath(p.filePath, cwd))}, layout: ${JSON.stringify(p.layout)}, reuseTarget: ${JSON.stringify(p.reuseTarget)} }`).join(",\n")}\n};\nexport const layouts = {\n${layouts.map((l) => ` ${JSON.stringify(l.name)}: { name: ${JSON.stringify(l.name)}, filePath: ${JSON.stringify(toPortableFilePath(l.filePath, cwd))}, isDefault: ${l.isDefault} }`).join(",\n")}\n};\nexport type RouteName = ${pages.map((p) => JSON.stringify(p.name)).join(" | ") || "string"};\nexport type LayoutName = ${layouts.map((l) => JSON.stringify(l.name)).join(" | ") || "string"};\nexport default { pages, layouts };`;
152
+ return `export const pages = {\n${pages.map((p) => ` ${JSON.stringify(p.name)}: { name: ${JSON.stringify(p.name)}, path: ${JSON.stringify(p.path)}, filePath: ${JSON.stringify(toPortableFilePath(p.filePath, cwd))}, layout: ${JSON.stringify(p.layout)}, reuseTarget: ${JSON.stringify(p.reuseTarget)}, routable: ${p.routable !== false}, pageMeta: ${JSON.stringify(p.pageMeta ?? null)} }`).join(",\n")}\n};\nexport const pageEntries = pages;\nexport const layouts = {\n${layouts.map((l) => ` ${JSON.stringify(l.name)}: { name: ${JSON.stringify(l.name)}, filePath: ${JSON.stringify(toPortableFilePath(l.filePath, cwd))}, isDefault: ${l.isDefault} }`).join(",\n")}\n};\nexport type RouteName = ${pages.filter((p) => p.routable !== false).map((p) => JSON.stringify(p.name)).join(" | ") || "string"};\nexport type LayoutName = ${layouts.map((l) => JSON.stringify(l.name)).join(" | ") || "string"};\nexport default { pages, layouts, pageEntries };`;
149
153
  });
150
154
  }
151
155
  function createMetaVirtualModule() {
@@ -171,6 +175,8 @@ function createAppVirtualModule(apiRoutes, middlewares, pages, srcDir) {
171
175
  name: p.name,
172
176
  route: p.route,
173
177
  isReuse: p.isReuse,
178
+ isMeta: p.isMeta,
179
+ routable: p.routable,
174
180
  layout: p.layout
175
181
  }));
176
182
  const viteSrcDir = toVitePath(srcDir);
@@ -287,12 +293,16 @@ if (import.meta.env.SSR) {
287
293
  }
288
294
 
289
295
  async function collectMessages(code) {
290
- const localeData = { messages: {}, options: { isDefault: false, name: undefined, dir: 'ltr', language: undefined } };
296
+ const localeData = {
297
+ messages: {},
298
+ options: { isDefault: false, name: undefined, path: undefined, dir: 'ltr', language: undefined }
299
+ };
291
300
  const configLoc = i18nConfig && i18nConfig.locales
292
301
  ? i18nConfig.locales.find(l => (typeof l === 'string' ? l : l.code) === code)
293
302
  : undefined;
294
303
  if (configLoc && typeof configLoc === 'object') {
295
304
  localeData.options.name = configLoc.name;
305
+ localeData.options.path = configLoc.path;
296
306
  localeData.options.dir = configLoc.dir || 'ltr';
297
307
  localeData.options.language = configLoc.language;
298
308
  localeData.options.isDefault = configLoc.code === (i18nConfig && i18nConfig.defaultLocale);
@@ -1,13 +1,13 @@
1
- import { a as ssrSingletonProdOptimizeExclude, m as createVirtualRegistry, o as ssrSingletonProdSsr, y as __exportAll } from "./ssr-singleton-Bbds29jS.js";
2
- import { a as createRoutingVirtualModule, i as createPagesVirtualModule, n as createLocalesVirtualModule, r as createMetaVirtualModule, s as transformMacros, t as createAppVirtualModule } from "./virtual-modules-BK0L1Op-.js";
3
- import { a as generateOpenApiTypes, i as generateTypes } from "./codegen-BL0s5Pyq.js";
4
- import { _ as toWebRequest, a as createVueAppEntryVirtualModule, b as getDevScanCoordinator, g as sendWebResponse, i as createServerEntryVirtualModule, n as ubeanVite, o as createVuePagesVirtualModule, r as createClientEntryVirtualModule, u as ensureDevApp } from "./vue-15_4jzH7.js";
1
+ import { a as ssrSingletonProdOptimizeExclude, g as createVirtualRegistry, o as ssrSingletonProdSsr, x as __exportAll } from "./ssr-singleton-CUHZLgiO.js";
2
+ import { a as createRoutingVirtualModule, i as createPagesVirtualModule, n as createLocalesVirtualModule, r as createMetaVirtualModule, s as transformMacros, t as createAppVirtualModule } from "./virtual-modules-B3aE-Fmn.js";
3
+ import { a as generateOpenApiTypes, i as generateTypes } from "./codegen-CUlE95gB.js";
4
+ import { _ as sendWebResponse, a as createServerEntryVirtualModule, d as ensureDevApp, i as createClientEntryVirtualModule, n as ubeanVite, o as createVueAppEntryVirtualModule, r as composeHeadScripts, s as createVuePagesVirtualModule, v as toWebRequest, x as getDevScanCoordinator } from "./vue-Z4wVSxSE.js";
5
5
  import { createStaticSsgRenderer } from "./static-render.js";
6
6
  import { prerender, resolvePrerenderStaticDir } from "./prerender.js";
7
7
  import { dirname, isAbsolute, join, relative, resolve } from "pathe";
8
8
  import * as nodeFs from "node:fs";
9
9
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
10
- import { checkProjectDependenciesOnce, loadUbeanConfig, resolveModules, resolvePrerenderConfig, tryGetConfig } from "@ubean/config";
10
+ import { checkProjectDependenciesOnce, loadUbeanConfig, localePathsOf, resolveModules, resolvePrerenderConfig, tryGetConfig } from "@ubean/config";
11
11
  import { isEphemeralCachePreset, registerBuiltinPresets, resolvePresetByName, resolveProductionCacheStore } from "@ubean/preset";
12
12
  import { createServerRouter } from "@ubean/routes";
13
13
  import { scanProject } from "@ubean/scan";
@@ -30,7 +30,8 @@ function localeVueParamFromI18n(config) {
30
30
  return getVueLocaleParam({
31
31
  defaultLocale: config.defaultLocale,
32
32
  locales: config.locales.map((l) => l.code),
33
- strategy: config.strategy
33
+ strategy: config.strategy,
34
+ paths: localePathsOf(config)
34
35
  }) || void 0;
35
36
  }
36
37
  //#endregion
@@ -86,6 +87,8 @@ const _pageToRoute = p => {
86
87
 
87
88
  const _routeGroups = new Map();
88
89
  for (const _p of _pages) {
90
+ // routable: false 的页面不建路由(与客户端 virtual:ubean-pages 同形)。
91
+ if (_p.routable === false) continue;
89
92
  const _key = _p.route;
90
93
  const _group = _routeGroups.get(_key) || { slots: [] };
91
94
  if (_p.slot) _group.slots.push(_p);
@@ -285,7 +288,8 @@ export async function renderStaticPage(input) {
285
288
  renderContext.routing = {
286
289
  defaultLocale: _i18nConfig.defaultLocale || 'en',
287
290
  locales: _localeCodes,
288
- strategy: _i18nConfig.strategy || 'prefix_except_default'
291
+ strategy: _i18nConfig.strategy || 'prefix_except_default',
292
+ ...(_i18nConfig.paths ? { paths: _i18nConfig.paths } : {})
289
293
  };
290
294
  const cookieName =
291
295
  _i18nConfig.detectBrowserLanguage && _i18nConfig.detectBrowserLanguage.cookieName;
@@ -738,14 +742,15 @@ async function writeClientIndexHtml(virtualDir) {
738
742
  * manifest、同一套标签规则,避免出现第二种「入口长什么样」的定义。
739
743
  */
740
744
  async function writeSpaIndexHtml(options) {
741
- const { outDirs, tags } = options;
745
+ const { outDirs, tags, headScript } = options;
742
746
  const target = join(outDirs.public, "index.html");
747
+ const favicon = tags.favicon ?? "/favicon.svg";
743
748
  const html = `<!DOCTYPE html>
744
749
  <html>
745
- <head>
750
+ <head>${headScript ? `\n ${headScript}` : ""}
746
751
  <meta charset="UTF-8" />
747
752
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
748
- <link rel="icon" href="${tags.favicon ?? "/favicon.svg"}" type="image/svg+xml" />
753
+ <link rel="icon" href="${favicon}" type="image/svg+xml" />
749
754
  <title>Ubean App</title>
750
755
  ${tags.css ? ` ${tags.css.split("\n").join("\n ")}\n` : ""}</head>
751
756
  <body>
@@ -1250,10 +1255,7 @@ async function prepareBuild(ctx, manifestRef = { current: null }) {
1250
1255
  mode: ctx.mode,
1251
1256
  ssrEnabled: ctx.ssrEnabled
1252
1257
  });
1253
- logger$2.info("Generating virtual modules...");
1254
1258
  const virtualRegistry = createVirtualRegistry();
1255
- await generateVirtualModulesToDisk(cwd, config, scanResult, outDirs.virtual, preset, virtualRegistry, contentSnapshot);
1256
- if (hasPages) await writeClientIndexHtml(outDirs.virtual);
1257
1259
  const userViteConfig = findUserViteConfig(cwd);
1258
1260
  const builtinPlugins = [];
1259
1261
  if (!userViteConfig) {
@@ -1277,6 +1279,9 @@ async function prepareBuild(ctx, manifestRef = { current: null }) {
1277
1279
  builtinPlugins
1278
1280
  });
1279
1281
  if (hasServer) plugins.push(perEnvironmentPlugin("ubean", () => createIslandsSsrStubPlugin()));
1282
+ logger$2.info("Generating virtual modules...");
1283
+ await generateVirtualModulesToDisk(cwd, config, scanResult, outDirs.virtual, preset, virtualRegistry, contentSnapshot);
1284
+ if (hasPages) await writeClientIndexHtml(outDirs.virtual);
1280
1285
  return {
1281
1286
  ...ctx,
1282
1287
  plugins,
@@ -1316,7 +1321,8 @@ async function runEnvBuilds(builder, prepared) {
1316
1321
  css: tags.css,
1317
1322
  body: tags.body,
1318
1323
  favicon: prepared.config.favicon
1319
- }
1324
+ },
1325
+ headScript: composeHeadScripts(prepared.config.colorMode !== false ? getColorModeScript(resolveColorModeConfig(prepared.config.colorMode)) : "")
1320
1326
  });
1321
1327
  }
1322
1328
  const builtManifest = await writeBuildManifest({
@@ -1429,6 +1435,8 @@ function serializePagesForEntry(pages) {
1429
1435
  layout: p.layout,
1430
1436
  cache: p.cache,
1431
1437
  isReuse: p.isReuse,
1438
+ isMeta: p.isMeta,
1439
+ routable: p.routable,
1432
1440
  isMarkdown: p.isMarkdown,
1433
1441
  reuseTarget: p.reuseTarget,
1434
1442
  pageMeta: p.pageMeta,
@@ -1528,7 +1536,7 @@ async function generateVirtualModulesToDisk(cwd, config, scanResult, virtualDir,
1528
1536
  layout: scanResult.notFoundPage.layout,
1529
1537
  pageMeta: scanResult.notFoundPage.pageMeta
1530
1538
  } : null);
1531
- const colorModeScript = config.colorMode !== false ? getColorModeScript(resolveColorModeConfig(config.colorMode)) : "";
1539
+ const colorModeScript = composeHeadScripts(config.colorMode !== false ? getColorModeScript(resolveColorModeConfig(config.colorMode)) : "");
1532
1540
  const rendererImport = ssrEnabled ? `import { createVueRenderer } from 'ubean/ssr';` : "";
1533
1541
  const prodLocaleVueParam = localeVueParamFromI18n(config.i18n) || "";
1534
1542
  const rendererSetup = buildRendererSetup({
@@ -2482,7 +2490,7 @@ async function buildEnvironmentsForConfig(config) {
2482
2490
  Promise.resolve().then(() => build_configs_exports),
2483
2491
  import("./production.js"),
2484
2492
  import("@ubean/preset"),
2485
- import("./ssr-singleton-Bbds29jS.js").then((n) => n.s)
2493
+ import("./ssr-singleton-CUHZLgiO.js").then((n) => n.s)
2486
2494
  ]);
2487
2495
  registerBuiltinPresets();
2488
2496
  const outDirs = getBuildOutDirsForConfig(config);
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { m as createVirtualRegistry } from "./ssr-singleton-Bbds29jS.js";
2
- import { A as toVueRouterPagePath, C as bootstrapDevApp, D as resolveLocaleVueParam, E as resolveDevSecurityHeaders, O as enhanceDevApp, S as peekDevScanCoordinator, T as createDevAppReady, _ as toWebRequest, b as getDevScanCoordinator, c as collectDevCssLinks, d as getDevApp, f as injectStylesheetLinks, g as sendWebResponse, h as ubeanDevRequestPlugin, k as buildDevSsrRoutes, l as createUbeanRequestHandlers, m as isViteResourceRequest, p as isFrameworkHtmlPage, s as DEVTOOLS_PASS_THROUGH_PREFIXES, u as ensureDevApp, v as DEV_SCAN_DIRS, w as createDevApp, x as onDevScan, y as createDevScanCoordinator } from "./vue-15_4jzH7.js";
3
- import { D as createCloudflarePreviewRunner, E as MINIFLARE_INSTALL_HINT, O as defaultLoadMiniflare, _ as ubeanPreviewPlugin, a as createEnvRunnerTransport, c as getDevWorkerEntrySource, d as attachPreviewMiddleware, f as createPreviewMiddleware, g as sendPreviewStatus, h as sendPreviewFile, i as bridgeEnvRunnerInvokes, k as readCompatibilityDate, l as invalidateDevWorkerModules, m as resolvePreviewFile, n as UBEAN_DEV_ENV_NAME, o as createUbeanDevEnvironmentFactory, p as previewMimeType, r as UbeanDevEnvironment, s as DEV_WORKER_FILE, t as ubeanPlugin, u as writeDevWorkerEntry } from "./vite-CmtXmVIm.js";
1
+ import { g as createVirtualRegistry } from "./ssr-singleton-CUHZLgiO.js";
2
+ import { A as buildDevSsrRoutes, C as peekDevScanCoordinator, D as resolveDevSecurityHeaders, E as createDevAppReady, O as resolveLocaleVueParam, S as onDevScan, T as createDevApp, _ as sendWebResponse, b as createDevScanCoordinator, c as DEVTOOLS_PASS_THROUGH_PREFIXES, d as ensureDevApp, f as getDevApp, g as ubeanDevRequestPlugin, h as isViteResourceRequest, j as toVueRouterPagePath, k as enhanceDevApp, l as collectDevCssLinks, m as isFrameworkHtmlPage, p as injectStylesheetLinks, u as createUbeanRequestHandlers, v as toWebRequest, w as bootstrapDevApp, x as getDevScanCoordinator, y as DEV_SCAN_DIRS } from "./vue-Z4wVSxSE.js";
3
+ import { D as createCloudflarePreviewRunner, E as MINIFLARE_INSTALL_HINT, O as defaultLoadMiniflare, _ as ubeanPreviewPlugin, a as createEnvRunnerTransport, c as getDevWorkerEntrySource, d as attachPreviewMiddleware, f as createPreviewMiddleware, g as sendPreviewStatus, h as sendPreviewFile, i as bridgeEnvRunnerInvokes, k as readCompatibilityDate, l as invalidateDevWorkerModules, m as resolvePreviewFile, n as UBEAN_DEV_ENV_NAME, o as createUbeanDevEnvironmentFactory, p as previewMimeType, r as UbeanDevEnvironment, s as DEV_WORKER_FILE, t as ubeanPlugin, u as writeDevWorkerEntry } from "./vite--HujaLpA.js";
4
4
  export { DEVTOOLS_PASS_THROUGH_PREFIXES, DEV_SCAN_DIRS, DEV_WORKER_FILE, MINIFLARE_INSTALL_HINT, UBEAN_DEV_ENV_NAME, UbeanDevEnvironment, attachPreviewMiddleware, bootstrapDevApp, bridgeEnvRunnerInvokes, buildDevSsrRoutes, collectDevCssLinks, createCloudflarePreviewRunner, createDevApp, createDevAppReady, createDevScanCoordinator, createEnvRunnerTransport, createPreviewMiddleware, createUbeanDevEnvironmentFactory, createUbeanRequestHandlers, createVirtualRegistry, defaultLoadMiniflare, enhanceDevApp, ensureDevApp, getDevApp, getDevScanCoordinator, getDevWorkerEntrySource, injectStylesheetLinks, invalidateDevWorkerModules, isFrameworkHtmlPage, isViteResourceRequest, onDevScan, peekDevScanCoordinator, previewMimeType, readCompatibilityDate, resolveDevSecurityHeaders, resolveLocaleVueParam, resolvePreviewFile, sendPreviewFile, sendPreviewStatus, sendWebResponse, toVueRouterPagePath, toWebRequest, ubeanDevRequestPlugin, ubeanPlugin, ubeanPreviewPlugin, writeDevWorkerEntry };
@@ -1,9 +1,10 @@
1
- import { c as getComponentResolvers, h as defineVirtualModule, i as ssrSingletonDevPolicy, l as getCssImports, m as createVirtualRegistry } from "./ssr-singleton-Bbds29jS.js";
2
- import { D as resolveComponentsConfig, E as resolveAutoImportsConfig, O as toArray, S as getAutoImportPresets, f as COMPONENT_HALF_GLOBS } from "./codegen-BL0s5Pyq.js";
1
+ import { _ as defineVirtualModule, c as getComponentResolvers, g as createVirtualRegistry, i as ssrSingletonDevPolicy, l as getCssImports, u as getHeadScripts } from "./ssr-singleton-CUHZLgiO.js";
2
+ import { D as resolveComponentsConfig, E as resolveAutoImportsConfig, O as toArray, S as getAutoImportPresets, f as COMPONENT_HALF_GLOBS } from "./codegen-CUlE95gB.js";
3
3
  import { createRequire } from "node:module";
4
+ import { generatePagesModuleSource } from "@ubean/vue/vite";
4
5
  import { isAbsolute, join, normalize, relative, resolve } from "pathe";
5
6
  import { existsSync } from "node:fs";
6
- import { loadUbeanConfig } from "@ubean/config";
7
+ import { loadUbeanConfig, localePathsOf } from "@ubean/config";
7
8
  import { scanProject } from "@ubean/scan";
8
9
  import { applyServerConfig, createUbeanApp } from "@ubean/app";
9
10
  import { getVueLocaleParam, toVueRouterLocalePath } from "@ubean/i18n";
@@ -16,7 +17,6 @@ import AutoImport from "unplugin-auto-import/vite";
16
17
  import { ubeanMdxPlugin } from "@ubean/markdown";
17
18
  import { renderFaviconLink } from "@ubean/pages";
18
19
  import VueI18nPlugin from "@intlify/unplugin-vue-i18n/vite";
19
- import { generatePagesModuleSource } from "@ubean/vue/vite";
20
20
  //#region src/dev/dev-ssr-routes.ts
21
21
  /**
22
22
  * dev/SSR 路由表(RM-V11 的组成部件,从 CLI dev server 抽出)。
@@ -49,9 +49,10 @@ function toVueRouterPagePath(route) {
49
49
  function buildDevSsrRoutes(options) {
50
50
  const { pages, layouts, loadComponent, localeVueParam, notFoundPage } = options;
51
51
  const defaultLayout = layouts.find((l) => l.isDefault)?.name ?? null;
52
+ const routablePages = pages.filter((p) => p.routable !== false);
52
53
  const withLocale = (path) => localeVueParam ? toVueRouterLocalePath(path, localeVueParam) : path;
53
54
  const pageByName = /* @__PURE__ */ new Map();
54
- for (const page of pages) pageByName.set(page.name, page);
55
+ for (const page of routablePages) pageByName.set(page.name, page);
55
56
  const componentFor = (page) => {
56
57
  const fullPath = (page.isReuse && page.reuseTarget ? pageByName.get(page.reuseTarget) : void 0)?.fullPath || page.fullPath;
57
58
  return async () => await loadComponent(fullPath);
@@ -67,7 +68,7 @@ function buildDevSsrRoutes(options) {
67
68
  }
68
69
  });
69
70
  const grouped = /* @__PURE__ */ new Map();
70
- for (const page of pages) {
71
+ for (const page of routablePages) {
71
72
  const group = grouped.get(page.route) ?? { slots: [] };
72
73
  if (page.slot) group.slots.push(page);
73
74
  else if (!group.default) group.default = page;
@@ -391,7 +392,8 @@ function resolveLocaleVueParam(config) {
391
392
  return getVueLocaleParam({
392
393
  defaultLocale: i18n.defaultLocale,
393
394
  locales: i18n.locales.map((l) => l.code),
394
- strategy: i18n.strategy
395
+ strategy: i18n.strategy,
396
+ paths: localePathsOf(i18n)
395
397
  });
396
398
  }
397
399
  //#endregion
@@ -1213,6 +1215,7 @@ if (_i18nConfig && _i18nConfig.enabled !== false) {
1213
1215
  fallbackLocale: _i18nConfig.fallbackLocale || _i18nConfig.defaultLocale,
1214
1216
  cookieName: (_i18nConfig.detectBrowserLanguage && _i18nConfig.detectBrowserLanguage.cookieName) || 'ubean_locale',
1215
1217
  baseUrl: _i18nConfig.baseUrl || '',
1218
+ paths: _i18nConfig.paths,
1216
1219
  vueI18n: _i18nConfig.vueI18n
1217
1220
  },
1218
1221
  loadLocale: _loadLocale,
@@ -1465,6 +1468,21 @@ export const rootId = 'app';
1465
1468
  `.trim()}\n`;
1466
1469
  });
1467
1470
  }
1471
+ /**
1472
+ * 合并首帧 `<head>` 脚本的两个来源,去重后返回。
1473
+ *
1474
+ * 通常只有一个源生效:`ui` 接管时配置层强制把 `colorMode` 置 false,所以两边不会同时非空。
1475
+ * 两个源合成一个字符串后,三条注入路径(dev `transformIndexHtml`、fullstack 服务端入口、
1476
+ * ssg 静态入口)只需要一个 `colorModeScript` 字段,不必各自改签名。
1477
+ *
1478
+ * @param colorModeScript - 已渲染的 ubean color-mode 脚本(`getColorModeScript()` 产物)
1479
+ */
1480
+ function composeHeadScripts(colorModeScript) {
1481
+ const headScripts = getHeadScripts();
1482
+ if (!headScripts) return colorModeScript;
1483
+ if (!colorModeScript) return headScripts;
1484
+ return `${headScripts}\n${colorModeScript}`;
1485
+ }
1468
1486
  function createClientEntryVirtualModule() {
1469
1487
  return defineVirtualModule("virtual:ubean-client-entry", () => {
1470
1488
  return `${`
@@ -1570,7 +1588,8 @@ function localeVueParamFromConfig(config) {
1570
1588
  return getVueLocaleParam({
1571
1589
  defaultLocale: config.i18n.defaultLocale,
1572
1590
  locales: codes,
1573
- strategy: config.i18n.strategy
1591
+ strategy: config.i18n.strategy,
1592
+ paths: localePathsOf(config.i18n)
1574
1593
  }) || void 0;
1575
1594
  }
1576
1595
  function ubeanVite(options) {
@@ -1695,11 +1714,8 @@ function ubeanVite(options) {
1695
1714
  transformIndexHtml(html, ctx) {
1696
1715
  if (ctx?.path && isFrameworkHtmlPage(ctx.path)) return html;
1697
1716
  let result = html;
1698
- const colorModeConfig = ubeanConfig.colorMode;
1699
- if (colorModeConfig !== false) {
1700
- const script = getColorModeScript(resolveColorModeConfig(colorModeConfig));
1701
- result = result.replace("<head>", `<head>\n ${script}`);
1702
- }
1717
+ const headScript = composeHeadScripts(ubeanConfig.colorMode !== false ? getColorModeScript(resolveColorModeConfig(ubeanConfig.colorMode)) : "");
1718
+ if (headScript) result = result.replace("<head>", `<head>\n ${headScript}`);
1703
1719
  const partyTownConfig = ubeanConfig.partyTown;
1704
1720
  if (partyTownConfig !== false && partyTownConfig !== void 0) {
1705
1721
  const resolved = resolvePartyTownConfig(partyTownConfig === true ? { enabled: true } : partyTownConfig);
@@ -1872,4 +1888,4 @@ async function runPagefindIndexing(ubeanConfig, searchConfig) {
1872
1888
  });
1873
1889
  }
1874
1890
  //#endregion
1875
- export { toVueRouterPagePath as A, bootstrapDevApp as C, resolveLocaleVueParam as D, resolveDevSecurityHeaders as E, enhanceDevApp as O, peekDevScanCoordinator as S, createDevAppReady as T, toWebRequest as _, createVueAppEntryVirtualModule as a, getDevScanCoordinator as b, collectDevCssLinks as c, getDevApp as d, injectStylesheetLinks as f, sendWebResponse as g, ubeanDevRequestPlugin as h, createServerEntryVirtualModule as i, buildDevSsrRoutes as k, createUbeanRequestHandlers as l, isViteResourceRequest as m, ubeanVite as n, createVuePagesVirtualModule as o, isFrameworkHtmlPage as p, createClientEntryVirtualModule as r, DEVTOOLS_PASS_THROUGH_PREFIXES as s, VUE_PLUGIN_INCLUDE as t, ensureDevApp as u, DEV_SCAN_DIRS as v, createDevApp as w, onDevScan as x, createDevScanCoordinator as y };
1891
+ export { buildDevSsrRoutes as A, peekDevScanCoordinator as C, resolveDevSecurityHeaders as D, createDevAppReady as E, resolveLocaleVueParam as O, onDevScan as S, createDevApp as T, sendWebResponse as _, createServerEntryVirtualModule as a, createDevScanCoordinator as b, DEVTOOLS_PASS_THROUGH_PREFIXES as c, ensureDevApp as d, getDevApp as f, ubeanDevRequestPlugin as g, isViteResourceRequest as h, createClientEntryVirtualModule as i, toVueRouterPagePath as j, enhanceDevApp as k, collectDevCssLinks as l, isFrameworkHtmlPage as m, ubeanVite as n, createVueAppEntryVirtualModule as o, injectStylesheetLinks as p, composeHeadScripts as r, createVuePagesVirtualModule as s, VUE_PLUGIN_INCLUDE as t, createUbeanRequestHandlers as u, toWebRequest as v, bootstrapDevApp as w, getDevScanCoordinator as x, DEV_SCAN_DIRS as y };
package/dist/vue.d.ts CHANGED
@@ -36,6 +36,16 @@ export declare function ubeanVite(options: UbeanViteOptions): Plugin[];
36
36
  */
37
37
  export declare function createVuePagesVirtualModule(pages: ScannedPageRoute[], layouts: ScannedLayout[], notFoundPage?: ScannedPageRoute, loadingPage?: ScannedPageRoute, errorPage?: ScannedPageRoute, localeVueParam?: string): VirtualModule;
38
38
  export declare function createVueAppEntryVirtualModule(appEntry?: ScannedAppEntry): VirtualModule;
39
+ /**
40
+ * 合并首帧 `<head>` 脚本的两个来源,去重后返回。
41
+ *
42
+ * 通常只有一个源生效:`ui` 接管时配置层强制把 `colorMode` 置 false,所以两边不会同时非空。
43
+ * 两个源合成一个字符串后,三条注入路径(dev `transformIndexHtml`、fullstack 服务端入口、
44
+ * ssg 静态入口)只需要一个 `colorModeScript` 字段,不必各自改签名。
45
+ *
46
+ * @param colorModeScript - 已渲染的 ubean color-mode 脚本(`getColorModeScript()` 产物)
47
+ */
48
+ export declare function composeHeadScripts(colorModeScript: string): string;
39
49
  export declare function createClientEntryVirtualModule(): VirtualModule;
40
50
  export declare function createServerEntryVirtualModule(serverEntry?: ScannedServerEntry): VirtualModule;
41
51
  //#endregion
package/dist/vue.js CHANGED
@@ -1 +1 @@
1
- export { t as VUE_PLUGIN_INCLUDE, r as createClientEntryVirtualModule, i as createServerEntryVirtualModule, a as createVueAppEntryVirtualModule, o as createVuePagesVirtualModule, n as default, n as ubeanVite } from "./vue-15_4jzH7.js";
1
+ export { t as VUE_PLUGIN_INCLUDE, r as composeHeadScripts, i as createClientEntryVirtualModule, a as createServerEntryVirtualModule, o as createVueAppEntryVirtualModule, s as createVuePagesVirtualModule, n as default, n as ubeanVite } from "./vue-Z4wVSxSE.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ubean/build",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
4
4
  "description": "Vite plugins, production build, SSG prerender, type codegen, and Server Actions plugin for ubean",
5
5
  "files": [
6
6
  "dist"
@@ -48,20 +48,20 @@
48
48
  }
49
49
  },
50
50
  "dependencies": {
51
- "@intlify/unplugin-vue-i18n": "11.2.6",
52
- "@ubean/app": "0.6.5",
53
- "@ubean/client": "0.6.5",
54
- "@ubean/config": "0.6.5",
55
- "@ubean/i18n": "0.6.5",
56
- "@ubean/islands": "0.6.5",
57
- "@ubean/markdown": "0.6.5",
58
- "@ubean/pages": "0.6.5",
59
- "@ubean/preset": "0.6.5",
60
- "@ubean/routes": "0.6.5",
61
- "@ubean/scan": "0.6.5",
62
- "@ubean/server": "0.6.5",
63
- "@ubean/shared": "0.6.5",
64
- "@ubean/vue": "0.6.5",
51
+ "@intlify/unplugin-vue-i18n": "11.2.7",
52
+ "@ubean/app": "0.6.7",
53
+ "@ubean/client": "0.6.7",
54
+ "@ubean/config": "0.6.7",
55
+ "@ubean/i18n": "0.6.7",
56
+ "@ubean/islands": "0.6.7",
57
+ "@ubean/markdown": "0.6.7",
58
+ "@ubean/pages": "0.6.7",
59
+ "@ubean/preset": "0.6.7",
60
+ "@ubean/routes": "0.6.7",
61
+ "@ubean/scan": "0.6.7",
62
+ "@ubean/server": "0.6.7",
63
+ "@ubean/shared": "0.6.7",
64
+ "@ubean/vue": "0.6.7",
65
65
  "@vitejs/plugin-vue": "^6.0.10",
66
66
  "openapi-typescript": "^7.13.0",
67
67
  "pathe": "^2.0.3",
@@ -70,7 +70,7 @@
70
70
  "unplugin-auto-import": "21.1.0",
71
71
  "unplugin-vue-components": "^32.1.0",
72
72
  "unplugin-vue-markdown": "^32.1.1",
73
- "vue-i18n": "11.4.15"
73
+ "vue-i18n": "11.4.16"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/node": "^26.6.5",