@hia-doc/renderer-html 0.1.7 → 1.0.0-rc.1

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.
Files changed (45) hide show
  1. package/README.md +243 -0
  2. package/dist/index.d.ts +1623 -126
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +829 -159
  5. package/dist/index.js.map +1 -1
  6. package/dist/information-architecture.d.ts +284 -20
  7. package/dist/information-architecture.d.ts.map +1 -1
  8. package/dist/information-architecture.js +42 -15
  9. package/dist/information-architecture.js.map +1 -1
  10. package/dist/portal-ui-locale.d.ts +108 -20
  11. package/dist/portal-ui-locale.d.ts.map +1 -1
  12. package/dist/portal-ui-locale.js +103 -27
  13. package/dist/portal-ui-locale.js.map +1 -1
  14. package/dist/presentation-profile.d.ts +176 -16
  15. package/dist/presentation-profile.d.ts.map +1 -1
  16. package/dist/presentation-profile.js +40 -14
  17. package/dist/presentation-profile.js.map +1 -1
  18. package/dist/route-history.d.ts +193 -0
  19. package/dist/route-history.d.ts.map +1 -0
  20. package/dist/route-history.js +246 -0
  21. package/dist/route-history.js.map +1 -0
  22. package/dist/site-chrome.d.ts +173 -0
  23. package/dist/site-chrome.d.ts.map +1 -0
  24. package/dist/site-chrome.js +187 -0
  25. package/dist/site-chrome.js.map +1 -0
  26. package/dist/site-navigation-chrome.d.ts +36 -0
  27. package/dist/site-navigation-chrome.d.ts.map +1 -0
  28. package/dist/site-navigation-chrome.js +430 -0
  29. package/dist/site-navigation-chrome.js.map +1 -0
  30. package/dist/site-navigation.d.ts +175 -0
  31. package/dist/site-navigation.d.ts.map +1 -0
  32. package/dist/site-navigation.js +176 -0
  33. package/dist/site-navigation.js.map +1 -0
  34. package/dist/site-reading.d.ts +171 -0
  35. package/dist/site-reading.d.ts.map +1 -0
  36. package/dist/site-reading.js +534 -0
  37. package/dist/site-reading.js.map +1 -0
  38. package/dist/source-lines.d.ts +3 -2
  39. package/dist/source-lines.d.ts.map +1 -1
  40. package/dist/source-lines.js +15 -9
  41. package/dist/source-lines.js.map +1 -1
  42. package/dist/theme-assets.d.ts +12 -3
  43. package/dist/theme-assets.d.ts.map +1 -1
  44. package/dist/theme-assets.js.map +1 -1
  45. package/package.json +10 -5
package/dist/index.js CHANGED
@@ -1,35 +1,57 @@
1
+ import { prepareProjectRouteHistory, PROJECT_ROUTE_HISTORY_SCRIPT } from "./route-history.js";
1
2
  import { renderSourceLines } from "./source-lines.js";
3
+ import { assertDocumentationSiteNavigation } from "./site-navigation.js";
4
+ import { withSiteNavigation } from "./site-navigation-chrome.js";
2
5
  import { canonicalizeDocumentationLocale, getI18nField, resolveI18nFieldText, validateBusinessFlowDocumentationProjection, validateDocumentationSourceCommentProjection } from "@hia-doc/core";
3
6
  import { relocateDefaultThemeAssets } from "./theme-assets.js";
4
7
  import { DEFAULT_THEME_CSS_PATH, DEFAULT_THEME_JS_PATH, PORTAL_THEME_SCHEMES, PORTAL_THEME_SKIN_IDS, getDefaultDocumentationPortalThemeReference, getDefaultThemeAssets, getPortalThemeSchemeLabel, getPortalThemeSkinLabel } from "@hia-doc/theme-default";
5
8
  import { DOCUMENTATION_PORTAL_SEMANTIC_PATH_KINDS, getDocumentationPortalLabels, resolveDocumentationPortalInformationArchitecture, resolveDocumentationPortalUiLocale } from "./information-architecture.js";
6
9
  import { PORTAL_PRESENTATION_PROFILE_PATH, createPortalPresentationBundle } from "./presentation-profile.js";
7
- import { DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID, DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID, DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES, createDocumentationPortalUiLocaleAdoption, resolveDocumentationPortalUiMessage } from "./portal-ui-locale.js";
10
+ import { DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID, DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID, DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES, createDocumentationPortalUiLocaleAdoption, createSiteNavigationUiLocaleAdoption, resolveDocumentationPortalUiMessage } from "./portal-ui-locale.js";
8
11
  export * from "./information-architecture.js";
9
- export * from "./portal-ui-locale.js";
12
+ export { DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID, DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID, DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES, DOCUMENTATION_PORTAL_UI_MESSAGE_IDS, createDocumentationPortalUiLocaleAdoption, resolveDocumentationPortalUiMessage } from "./portal-ui-locale.js";
10
13
  export * from "./presentation-profile.js";
14
+ export * from "./site-navigation.js";
15
+ export { DOCUMENTATION_PROJECT_ROUTE_HISTORY_CONTRACT, DOCUMENTATION_PROJECT_ROUTE_HISTORY_CONTRACT_VERSION, assertDocumentationProjectRouteHistory } from "./route-history.js";
11
16
  export { renderThemeAssets } from "./theme-assets.js";
17
+ /**
18
+ * @lang zh-CN HTML输出文件清单的精确版本0.1.0,独立于包、文档及各引用工件版本。
19
+ * @lang en Exact HTML output-manifest version 0.1.0, independent of package, document and referenced-artifact versions.
20
+ */
12
21
  export const HIA_RENDER_HTML_MANIFEST_SCHEMA_VERSION = "0.1.0";
13
22
  /**
14
- * 项目导航索引的中性 contract 名称;供静态 portal、搜索与宿主导航消费。
15
- * Neutral project-navigation-index contract name consumed by static portals, search, and host navigation.
23
+ * @lang zh-CN 项目导航索引的中性 contract 名称;供静态 portal、搜索与宿主导航消费。
24
+ * @lang en Neutral project-navigation-index contract name consumed by static portals, search, and host navigation.
16
25
  */
17
26
  export const HIA_PROJECT_NAVIGATION_INDEX_CONTRACT = "hia-project-navigation-index";
18
27
  /**
19
- * 项目导航索引的首个草案版本;它独立于 renderer manifest 的文件清单版本。
20
- * First draft version of the project navigation index; independent from the renderer manifest file-list version.
28
+ * @lang zh-CN 项目导航索引的首个草案版本;它独立于 renderer manifest 的文件清单版本。
29
+ * @lang en First draft version of the project navigation index; independent from the renderer manifest file-list version.
21
30
  */
22
31
  export const HIA_PROJECT_NAVIGATION_INDEX_CONTRACT_VERSION = "0.1.0-draft";
23
32
  /**
24
- * 项目级关系图的中性 contract 名称;用于表达文档入口、源码、生成物与宿主能力之间的关系。
25
- * Neutral project-level relation-graph contract for documentation entries, sources, generated artifacts, and host capabilities.
33
+ * @lang zh-CN 携带显式符号作用域的协调索引版本,旧索引writer保留。
34
+ * @lang en Coordinated index version carrying explicit symbol scopes, retaining the legacy index writer.
35
+ */
36
+ export const HIA_PROJECT_SCOPED_NAVIGATION_INDEX_CONTRACT_VERSION = "0.2.0-draft";
37
+ /**
38
+ * @lang zh-CN 项目级关系图的中性 contract 名称;用于表达文档入口、源码、生成物与宿主能力之间的关系。
39
+ * @lang en Neutral project-level relation-graph contract for documentation entries, sources, generated artifacts, and host capabilities.
26
40
  */
27
41
  export const HIA_PROJECT_RELATION_GRAPH_CONTRACT = "hia-project-relation-graph";
28
42
  /**
29
- * 项目级关系图的首个草案版本;后续 IDE/DevTools host 会按此 contract 做能力协商。
30
- * First draft version of the project relation graph; future IDE/DevTools hosts negotiate capabilities against this contract.
43
+ * @lang zh-CN 项目级关系图的首个草案版本;后续 IDE/DevTools host 会按此 contract 做能力协商。
44
+ * @lang en First draft version of the project relation graph; future IDE/DevTools hosts negotiate capabilities against this contract.
31
45
  */
32
46
  export const HIA_PROJECT_RELATION_GRAPH_CONTRACT_VERSION = "0.1.0-draft";
47
+ /**
48
+ * @lang zh-CN 把已结构化文档渲染为单页内存文件与manifest;默认包含主题资源,外部资源模式只返回引用,不写文件。
49
+ * @lang en Renders a structured document into single-page in-memory files and a manifest; theme assets default on, while external-asset mode returns references without file writes.
50
+ * @param document <lang><zh-CN>调用方已校验的HIA文档;此函数不是完整文档验证器。</zh-CN><en>Caller-validated HIA document; this function is not a complete document validator.</en></lang>
51
+ * @param options <lang><zh-CN>标题、初始语言、主题及资产路由;项目策略仅按已声明兼容范围消费。</zh-CN><en>Title, initial locale, theme and asset routing; project policies apply only within their documented compatibility scope.</en></lang>
52
+ * @returns <lang><zh-CN>有序内存文件、诊断和仅本次文件清单。</zh-CN><en>Ordered in-memory files, diagnostics and inventory of files owned by this build.</en></lang>
53
+ * @throws {TypeError} <lang><zh-CN>显式主题颜色或资源路由非法时拒绝,不静默忽略。</zh-CN><en>Invalid explicit theme colors or asset routing are rejected rather than silently ignored.</en></lang>
54
+ */
33
55
  export function renderHtmlDocument(document, options = {}) {
34
56
  const pageTitle = options.title ?? document.title;
35
57
  const includeThemeAssets = options.includeThemeAssets ?? true;
@@ -62,11 +84,9 @@ export function renderHtmlDocument(document, options = {}) {
62
84
  };
63
85
  }
64
86
  /**
65
- * @lang zh-CN
66
- * 把统一项目输入渲染为默认 split-site 或显式 single-page,并生成 exact presentation profile、内容寻址源码资源和 manifest linkage。
87
+ * @lang zh-CN 把统一项目输入渲染为默认 split-site 或显式 single-page,并生成 exact presentation profile、内容寻址源码资源和 manifest linkage。
67
88
  *
68
- * @lang en
69
- * Renders unified project input as the default split site or explicit single page, including an exact presentation profile, content-addressed source assets, and manifest linkage.
89
+ * @lang en Renders unified project input as the default split site or explicit single page, including an exact presentation profile, content-addressed source assets, and manifest linkage.
70
90
  *
71
91
  * @param projectInput - 已结构化的项目、entry 与关系输入;renderer 不自行读取路径。Structured project, entry, and relation input; the renderer performs no path read.
72
92
  * @param options - locale、IA、源码模式和 Portal theme 选择。Locale, IA, source-mode, and Portal-theme selections.
@@ -104,16 +124,53 @@ export async function renderProjectHtmlDocumentToWriter(projectInput, writer, op
104
124
  }
105
125
  return { fileCount: files.length, diagnostics: plan.diagnostics, manifest: plan.manifest(files) };
106
126
  }
107
- /** @lang zh-CN 在任何输出前构造/验证共用事实,保持普通与流式API的契约、顺序和正文一致。 @lang en Builds/validates shared facts before output, preserving contracts, ordering and prose across ordinary and streaming APIs. */
127
+ /**
128
+ * @lang zh-CN 在任何输出前构造/验证共用事实,保持普通与流式API的契约、顺序和正文一致。
129
+ * @lang en Builds/validates shared facts before output, preserving contracts, ordering and prose across ordinary and streaming APIs.
130
+ */
108
131
  function createProjectHtmlRenderPlan(projectInput, options) {
132
+ // <lang><zh-CN>发布身份先于关系、地图呈现和任何输出应用,历史副本隔离writer期间的调用方变更。</zh-CN><en>Apply publication identity before relation/map presentation or output, isolating history from caller mutation during writer waits.</en></lang>
133
+ const historyProjection = options.projectSite?.routeHistory === undefined ? undefined : prepareProjectRouteHistory(projectInput, options.projectSite.routeHistory);
134
+ if (historyProjection && options.projectSite?.layout === "single-page")
135
+ throw new TypeError("HIA_PROJECT_ROUTE_HISTORY_INVALID: History requires split-site output.");
136
+ if (historyProjection)
137
+ projectInput = historyProjection.input;
138
+ // <lang><zh-CN>直接API调用也必须遵守新逻辑作用域的词法边界,在首写前拒绝无效值。</zh-CN><en>Direct API calls also enforce logical-scope syntax before the first output write.</en></lang>
139
+ const scopedSymbols = new Set();
140
+ for (const entry of projectInput.entries) {
141
+ if (entry.identityScope !== undefined && (typeof entry.identityScope !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(entry.identityScope))) {
142
+ throw new TypeError("HIA_RENDER_PROJECT_IDENTITY_SCOPE_INVALID");
143
+ }
144
+ if (entry.identityScope && entry.symbolId) {
145
+ // <lang><zh-CN>显式.NET文档别名参与相同唯一性检查,避免父类型关联覆盖另一声明。</zh-CN><en>Explicit .NET documentation aliases share the uniqueness check so parent joins cannot overwrite another declaration.</en></lang>
146
+ const aliases = new Set([entry.symbolId, ...(entry.hierarchy?.symbolDocumentationId ? [entry.hierarchy.symbolDocumentationId] : [])]);
147
+ for (const alias of aliases) {
148
+ const key = projectSymbolLookupKey(entry, alias);
149
+ if (scopedSymbols.has(key))
150
+ throw new TypeError("HIA_RENDER_PROJECT_SYMBOL_ID_AMBIGUOUS");
151
+ scopedSymbols.add(key);
152
+ }
153
+ }
154
+ }
109
155
  // <lang><zh-CN>资源路由非法时必须在第一次writer调用前拒绝。</zh-CN><en>Reject invalid asset routing before the first writer invocation.</en></lang>
110
156
  relocateDefaultThemeAssets([], options.themeAssets);
157
+ const siteLayout = options.projectSite?.layout ?? "split-site";
158
+ // <lang><zh-CN>仅 split-site 写独立条目及无脚本页;冲突必须在任何文件写入前拒绝。</zh-CN><en>Only split-site writes separate entry and no-script pages; reject their collisions before writing any file.</en></lang>
159
+ if (siteLayout === "split-site")
160
+ assertUniqueProjectEntryArtifactNames(projectInput.entries);
111
161
  // <lang><zh-CN>关系图先规范化,确保 presentation identity 使用最终 relation facts,而不是调用者数组顺序。</zh-CN><en>Normalize the relation graph first so presentation identity uses final relation facts rather than caller array order.</en></lang>
112
- const normalizedProjectInput = normalizeProjectRelationGraphInput(projectInput);
162
+ // <lang><zh-CN>显式父项在本作用域/视图缺失时保留条目并报告未解析,避免向其它来源借用父项。</zh-CN><en>Retain entries and report unresolved explicit parents within their scope/view, without borrowing parents from other origins.</en></lang>
163
+ const parentDiagnostics = projectInput.entries
164
+ .filter(entry => entry.identityScope && entry.hierarchy?.parentSymbolId && !findProjectParentEntry(entry, projectInput.entries))
165
+ .map(() => ({ code: "HIA_RENDER_PROJECT_PARENT_UNRESOLVED", message: "Scoped parent is absent from its view and identity scope.", severity: "warning", targetPath: "project.entries" }));
166
+ const normalizedProjectInput = normalizeProjectRelationGraphInput(parentDiagnostics.length
167
+ ? { ...projectInput, diagnostics: [...(projectInput.diagnostics ?? []), ...parentDiagnostics] }
168
+ : projectInput);
113
169
  const pageTitle = options.title ?? normalizedProjectInput.project.title ?? normalizedProjectInput.project.name;
114
170
  const includeThemeAssets = options.includeThemeAssets ?? true;
115
- const siteLayout = options.projectSite?.layout ?? "split-site";
116
171
  const portalContext = resolveProjectPortalContext(normalizedProjectInput, options, siteLayout);
172
+ if (historyProjection)
173
+ portalContext.routeHistory = historyProjection.history;
117
174
  // <lang><zh-CN>颜色由主题owner单点校验,和普通文档使用同一个品牌资源工厂。</zh-CN><en>The theme owner validates colors centrally through the same branded-asset factory used by documents.</en></lang>
118
175
  const assets = getDefaultThemeAssets(options.theme ?? {});
119
176
  // <lang><zh-CN>bundle 是 profile、source asset 和 owner mapping 的唯一生成点;后续 HTML 只消费 body-free mapping。</zh-CN><en>The bundle is the sole generation point for profiles, source assets, and owner mappings; later HTML consumes only body-free mappings.</en></lang>
@@ -146,18 +203,29 @@ function createProjectHtmlRenderPlan(projectInput, options) {
146
203
  diagnostics: [...(sourcePreparedProjectInput.diagnostics ?? []), ...presentationBundle.diagnostics]
147
204
  };
148
205
  const navigationIndex = createProjectNavigationIndex(renderedProjectInput, pageTitle, options, portalContext, presentationBundle);
149
- /** @lang zh-CN 按既有顺序惰性发出单文件;只在消费者继续迭代时渲染下一页。 @lang en Lazily emits individual files in legacy order, rendering the next page only when the consumer resumes. */
206
+ // <lang><zh-CN>旧文件冲突与真实小节在首写前完整核验,逐项HTML仍按需生成。</zh-CN><en>Preflight legacy-file collisions and actual sections before the first write, while retaining demand-driven HTML generation.</en></lang>
207
+ const routeLocaleModel = resolveProjectLocaleModel(renderedProjectInput, options.locale);
208
+ const legacyGroups = prepareProjectRouteAliases(renderedProjectInput, navigationIndex, portalContext, routeLocaleModel);
209
+ /**
210
+ * @lang zh-CN 按既有顺序惰性发出单文件;只在消费者继续迭代时渲染下一页。
211
+ * @lang en Lazily emits individual files in legacy order, rendering the next page only when the consumer resumes.
212
+ */
150
213
  function* produceFiles() {
151
214
  if (siteLayout === "single-page") {
152
215
  yield { path: "index.html", contents: renderProjectIndexHtml(pageTitle, renderedProjectInput, options, portalContext), contentType: "text/html; charset=utf-8", role: "entry" };
153
216
  }
154
217
  else {
155
218
  yield* createProjectSplitSiteFiles(pageTitle, renderedProjectInput, navigationIndex, options, portalContext);
219
+ yield* createProjectRouteCompatibilityFiles(pageTitle, renderedProjectInput, navigationIndex, portalContext, legacyGroups, routeLocaleModel);
156
220
  }
157
- if (portalContext.uiLocaleAdoption) {
158
- yield { path: DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, contents: `${portalContext.uiLocaleAdoption.reportJson}\n`, contentType: "application/json; charset=utf-8", role: "index" };
221
+ const localeReport = portalContext.uiLocaleAdoption ?? portalContext.siteNavigationUiLocaleAdoption;
222
+ if (localeReport) {
223
+ yield { path: DOCUMENTATION_PORTAL_UI_LOCALE_REPORT_PATH, contents: `${localeReport.reportJson}\n`, contentType: "application/json; charset=utf-8", role: "index" };
159
224
  }
160
- yield { path: "project-index.json", contents: `${JSON.stringify(navigationIndex, null, 2)}\n`, contentType: "application/json; charset=utf-8", role: "index" };
225
+ // <lang><zh-CN>直接序列化既有模型时省略展示缩进,字符串数据保留;输入工件和源码快照走原复制边界。</zh-CN><en>Omit presentation indentation when serializing existing models while preserving string data; input artifacts and source snapshots retain their copy boundaries.</en></lang>
226
+ yield { path: "project-index.json", contents: `${JSON.stringify(navigationIndex)}\n`, contentType: "application/json; charset=utf-8", role: "index" };
227
+ if (portalContext.routeHistory)
228
+ yield { path: "route-history.json", contents: `${JSON.stringify(portalContext.routeHistory)}\n`, contentType: "application/json; charset=utf-8", role: "index" };
161
229
  yield* presentationBundle.artifacts;
162
230
  if (includeThemeAssets) {
163
231
  for (const asset of assets)
@@ -165,7 +233,13 @@ function createProjectHtmlRenderPlan(projectInput, options) {
165
233
  }
166
234
  }
167
235
  return {
168
- files: produceFiles(),
236
+ files: portalContext.siteNavigation ? withSiteNavigation(produceFiles(), portalContext.siteNavigation, portalContext.uiLocale, renderedProjectInput.entries.map(entry => ({
237
+ id: entry.id,
238
+ name: entry.name,
239
+ page: portalContext.uiLocaleAdoption ? createProjectLocalizedNoScriptPagePath(entry.id, portalContext.uiLocale) : createProjectNoScriptPagePath(entry.id),
240
+ ...(portalContext.uiLocaleAdoption ? { localePages: { "zh-CN": createProjectLocalizedNoScriptPagePath(entry.id, "zh-CN"), en: createProjectLocalizedNoScriptPagePath(entry.id, "en") } } : {}),
241
+ ...(entry.source?.publicAsset?.linkUrl ? { sourceUrl: entry.source.publicAsset.linkUrl } : {})
242
+ })), Object.keys(options.theme?.colors ?? {}), Boolean(portalContext.routeHistory)) : produceFiles(),
169
243
  diagnostics: renderedProjectInput.diagnostics ?? [],
170
244
  manifest: (files) => createProjectManifest(renderedProjectInput, files, pageTitle, options, navigationIndex, presentationBundle, portalContext)
171
245
  };
@@ -181,6 +255,15 @@ function createProjectHtmlRenderPlan(projectInput, options) {
181
255
  * @throws 对任何不受支持的显式选择 fail closed。Fails closed for every unsupported explicit selection.
182
256
  */
183
257
  function resolveProjectPortalContext(projectInput, options, layout) {
258
+ // <lang><zh-CN>先核导航契约,再复制供惰性输出使用,writer等待期间的外部修改不能改变后续页面。
259
+ // </zh-CN><en>Validate navigation first, then snapshot it for lazy output so external mutation during writer waits cannot change later pages.</en></lang>
260
+ const requestedNavigation = options.projectSite?.siteNavigation;
261
+ if (requestedNavigation !== undefined) {
262
+ assertDocumentationSiteNavigation(requestedNavigation);
263
+ if (!options.projectSite?.uiLocale)
264
+ throw new TypeError("HIA_SITE_NAVIGATION_UI_LOCALE_REQUIRED: Site navigation requires an explicit UI locale.");
265
+ }
266
+ const siteNavigation = requestedNavigation === undefined ? undefined : structuredClone(requestedNavigation);
184
267
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
185
268
  const explicitInformationArchitecture = options.projectSite?.informationArchitecture;
186
269
  if (explicitInformationArchitecture && !options.projectSite?.uiLocale) {
@@ -238,13 +321,17 @@ function resolveProjectPortalContext(projectInput, options, layout) {
238
321
  contentLocale: localeModel.selectedLocale,
239
322
  contentLocales: localeModel.locales,
240
323
  defaultUiLocale: uiLocale,
324
+ ...(siteNavigation ? { siteNavigation } : {}),
241
325
  profileId: options.projectSite?.uiLocaleCompleteness?.profileId ?? DOCUMENTATION_PORTAL_UI_LOCALE_PROFILE_ID,
242
326
  surfaceId: options.projectSite?.uiLocaleCompleteness?.surfaceId ?? DOCUMENTATION_PORTAL_UI_LOCALE_SURFACE_ID
243
327
  })
244
328
  : undefined;
245
329
  return {
330
+ ...(siteNavigation ? { siteNavigation } : {}),
331
+ ...(siteNavigation && !explicitInformationArchitecture ? { siteNavigationUiLocaleAdoption: createSiteNavigationUiLocaleAdoption({ contentLocale: localeModel.selectedLocale, contentLocales: localeModel.locales, defaultUiLocale: uiLocale, siteNavigation }) } : {}),
246
332
  uiLocale,
247
333
  labels: getDocumentationPortalLabels(uiLocale),
334
+ sourcePresentation: options.projectSite?.source?.presentation ?? "fetch",
248
335
  theme: { skinId: requestedSkin, scheme: requestedScheme },
249
336
  ...(uiLocaleAdoption ? { uiLocaleAdoption } : {}),
250
337
  ...(sourceCommentProjection
@@ -398,9 +485,10 @@ function applyProjectSourcePresentationPolicy(projectInput, options, presentatio
398
485
  * @lang en Removes fetch-runtime metadata for standalone no-script pages and adjusts build-generated links to page-relative paths.
399
486
  *
400
487
  * @param projectInput - 已应用 source policy 的 project input。Project input after source policy application.
488
+ * @param parentPath - 静态页面至输出根的相对前缀,默认一层。Relative prefix from the static page to the output root, defaulting to one level.
401
489
  * @returns 不含不可用 fetch control 的 page input。Page input without unavailable fetch controls.
402
490
  */
403
- function createProjectNoScriptProjectInput(projectInput) {
491
+ function createProjectNoScriptProjectInput(projectInput, parentPath = "../") {
404
492
  return {
405
493
  ...projectInput,
406
494
  entries: projectInput.entries.map((entry) => {
@@ -414,7 +502,7 @@ function createProjectNoScriptProjectInput(projectInput) {
414
502
  ...entry,
415
503
  source: {
416
504
  ...source,
417
- ...(noScriptLinkUrl ? { linkUrl: `../${noScriptLinkUrl}` } : {})
505
+ ...(noScriptLinkUrl ? { linkUrl: `${parentPath}${noScriptLinkUrl}` } : {})
418
506
  }
419
507
  };
420
508
  })
@@ -436,7 +524,10 @@ function createManifest(document, files, options) {
436
524
  }))
437
525
  };
438
526
  }
439
- /** @lang zh-CN 从已验证 bundle 构造 manifest/index 共用的最小 profile 引用。 @lang en Builds the minimal manifest/index profile reference from a validated bundle. */
527
+ /**
528
+ * @lang zh-CN 从已验证 bundle 构造 manifest/index 共用的最小 profile 引用。
529
+ * @lang en Builds the minimal manifest/index profile reference from a validated bundle.
530
+ */
440
531
  function createProjectPresentationProfileRef(presentationBundle) {
441
532
  return {
442
533
  contract: presentationBundle.profile.contract,
@@ -447,11 +538,9 @@ function createProjectPresentationProfileRef(presentationBundle) {
447
538
  };
448
539
  }
449
540
  /**
450
- * @lang zh-CN
451
- * 从已通过 W-P123 gate 的 adoption 构造 manifest/index 共用的 body-free 引用和计数。
541
+ * @lang zh-CN 从已通过 W-P123 gate 的 adoption 构造 manifest/index 共用的 body-free 引用和计数。
452
542
  *
453
- * @lang en
454
- * Builds the body-free manifest/index reference and counts from a W-P123 gate-complete adoption.
543
+ * @lang en Builds the body-free manifest/index reference and counts from a W-P123 gate-complete adoption.
455
544
  *
456
545
  * @param adoption <lang><zh-CN>当前 Portal surface 的完整性结果。</lang><en>Completeness result for the current Portal surface.</en></lang>
457
546
  * @returns <lang><zh-CN>不含 message text 或内容正文的引用。</lang><en>Reference containing no message text or content body.</en></lang>
@@ -499,7 +588,10 @@ function collectProjectPresentationRelationIds(entry, relationGraph) {
499
588
  .map(({ id }) => id)
500
589
  .sort(compareStableText);
501
590
  }
502
- /** @lang zh-CN 构造含 profile linkage 的 body-free renderer manifest。 @lang en Builds a body-free renderer manifest with presentation-profile linkage. */
591
+ /**
592
+ * @lang zh-CN 构造含 profile linkage 的 body-free renderer manifest。
593
+ * @lang en Builds a body-free renderer manifest with presentation-profile linkage.
594
+ */
503
595
  function createProjectManifest(projectInput, files, pageTitle, options, navigationIndex, presentationBundle, portalContext) {
504
596
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
505
597
  const views = collectProjectViews(projectInput.entries);
@@ -570,13 +662,17 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
570
662
  }
571
663
  };
572
664
  }
573
- /** @lang zh-CN 构造 owner route index,并附加 neutral topic/page/fragment identity 和 profile 引用。 @lang en Builds the owner route index with neutral topic/page/fragment identities and a profile reference. */
665
+ /**
666
+ * @lang zh-CN 构造 owner route index,并附加 neutral topic/page/fragment identity 和 profile 引用。
667
+ * @lang en Builds the owner route index with neutral topic/page/fragment identities and a profile reference.
668
+ */
574
669
  function createProjectNavigationIndex(projectInput, pageTitle, options, portalContext, presentationBundle) {
575
670
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
576
671
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
577
672
  return {
578
673
  contract: HIA_PROJECT_NAVIGATION_INDEX_CONTRACT,
579
- contractVersion: HIA_PROJECT_NAVIGATION_INDEX_CONTRACT_VERSION,
674
+ contractVersion: projectInput.entries.some((entry) => entry.identityScope !== undefined)
675
+ ? HIA_PROJECT_SCOPED_NAVIGATION_INDEX_CONTRACT_VERSION : HIA_PROJECT_NAVIGATION_INDEX_CONTRACT_VERSION,
580
676
  project: {
581
677
  defaultLocale: localeModel.selectedLocale,
582
678
  entryCounts: countEntriesByView(projectInput.entries),
@@ -604,6 +700,7 @@ function createProjectNavigationIndex(projectInput, pageTitle, options, portalCo
604
700
  ? { sourceCommentProjection: selectProjectSourceCommentProjection(entry.sourceCommentProjection) }
605
701
  : {}),
606
702
  ...(entry.symbolId ? { symbolId: entry.symbolId } : {}),
703
+ ...(entry.identityScope ? { identityScope: entry.identityScope } : {}),
607
704
  ...(entry.hierarchy ? { hierarchy: entry.hierarchy } : {}),
608
705
  contentPath: createProjectEntryContentPath(entry.id),
609
706
  ...(options.projectSite?.layout === "single-page" ? {} : { noScriptPagePath: createProjectNoScriptPagePath(entry.id) }),
@@ -676,7 +773,7 @@ function* createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex,
676
773
  const files = [
677
774
  {
678
775
  path: "index.html",
679
- contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext),
776
+ contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext, navigationIndex.navigationTree),
680
777
  contentType: "text/html; charset=utf-8",
681
778
  role: "entry"
682
779
  },
@@ -701,31 +798,41 @@ function* createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex,
701
798
  : {}),
702
799
  searchText: createProjectEntrySearchText(entry)
703
800
  }))
704
- }, null, 2)}\n`,
801
+ })}\n`,
705
802
  contentType: "application/json; charset=utf-8",
706
803
  role: "index"
707
804
  },
708
805
  {
709
806
  path: "relations/project.json",
710
- contents: `${JSON.stringify(projectInput.relationGraph ?? createProjectRelationGraph(projectInput.entries), null, 2)}\n`,
807
+ contents: `${JSON.stringify(projectInput.relationGraph ?? createProjectRelationGraph(projectInput.entries))}\n`,
711
808
  contentType: "application/json; charset=utf-8",
712
809
  role: "index"
713
810
  }
714
811
  ];
715
812
  // <lang><zh-CN>no-script 入口与逐 topic 页面保持独立,不把数千节点重新塞回应用壳。</zh-CN><en>The no-script index and per-topic pages stay separate so thousands of nodes are not embedded back into the application shell.</en></lang>
716
813
  const noScriptProjectInput = createProjectNoScriptProjectInput(projectInput);
814
+ // <lang><zh-CN>静态导航仍使用完整语言目录及可见译文,交互入口和可加载片段继续携带动态绑定。</zh-CN><en>Static navigation retains its full locale catalog and visible translations. Interactive entries and loadable fragments retain dynamic bindings.</en></lang>
815
+ const noScriptContext = portalContext.siteNavigation
816
+ ? { ...portalContext, runtimeUiMessages: false }
817
+ : portalContext;
717
818
  // <lang><zh-CN>按稳定 entry id 建立单次索引,避免大型项目为每页线性扫描全部节点。</zh-CN><en>Build a one-time stable-entry index so large projects do not scan every node for every page.</en></lang>
718
819
  const noScriptEntryById = new Map(noScriptProjectInput.entries.map((entry) => [entry.id, entry]));
820
+ // <lang><zh-CN>本地化页面多一层目录,单次重定位全部条目也覆盖随父项呈现的成员来源。</zh-CN><en>Localized pages add one directory level; rebasing all entries once also covers sources of members rendered with their parent.</en></lang>
821
+ const localizedNoScriptProjectInput = portalContext.uiLocaleAdoption
822
+ ? createProjectNoScriptProjectInput(projectInput, "../../")
823
+ : noScriptProjectInput;
824
+ // <lang><zh-CN>复用同一身份集合的索引,逐页读取不再扫描全部声明。</zh-CN><en>Index the same identity set so per-page lookups do not rescan all declarations.</en></lang>
825
+ const localizedNoScriptEntryById = new Map(localizedNoScriptProjectInput.entries.map((entry) => [entry.id, entry]));
719
826
  files.push({
720
827
  path: "pages/index.html",
721
- contents: renderProjectNoScriptIndexHtml(pageTitle, noScriptProjectInput, localeModel.selectedLocale, portalContext),
828
+ contents: renderProjectNoScriptIndexHtml(pageTitle, noScriptProjectInput, localeModel.selectedLocale, noScriptContext),
722
829
  contentType: "text/html; charset=utf-8",
723
830
  role: "entry"
724
831
  });
725
832
  // <lang><zh-CN>采用 W-P123 的 surface 为每个 UI locale 生成真实静态入口;legacy 默认路径仍保留。</zh-CN><en>A W-P123-adopted surface emits a real static entry for every UI locale while retaining the legacy default path.</en></lang>
726
833
  if (portalContext.uiLocaleAdoption) {
727
834
  for (const uiLocale of DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES) {
728
- const localizedContext = withProjectUiLocale(portalContext, uiLocale);
835
+ const localizedContext = withProjectUiLocale(noScriptContext, uiLocale);
729
836
  files.push({
730
837
  path: `pages/${uiLocale}/index.html`,
731
838
  contents: renderProjectNoScriptIndexHtml(pageTitle, noScriptProjectInput, localeModel.selectedLocale, localizedContext, true),
@@ -759,16 +866,16 @@ function* createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex,
759
866
  });
760
867
  files.push({
761
868
  path: createProjectNoScriptPagePath(entry.id),
762
- contents: renderProjectNoScriptEntryHtml(pageTitle, noScriptEntry, noScriptProjectInput, localeModel, portalContext),
869
+ contents: renderProjectNoScriptEntryHtml(pageTitle, noScriptEntry, noScriptProjectInput, localeModel, noScriptContext),
763
870
  contentType: "text/html; charset=utf-8",
764
871
  role: "entry"
765
872
  });
766
873
  if (portalContext.uiLocaleAdoption) {
767
874
  for (const uiLocale of DOCUMENTATION_PORTAL_UI_CATALOG_LOCALES) {
768
- const localizedContext = withProjectUiLocale(portalContext, uiLocale);
875
+ const localizedContext = withProjectUiLocale(noScriptContext, uiLocale);
769
876
  files.push({
770
877
  path: createProjectLocalizedNoScriptPagePath(entry.id, uiLocale),
771
- contents: renderProjectNoScriptEntryHtml(pageTitle, noScriptEntry, noScriptProjectInput, localeModel, localizedContext, true),
878
+ contents: renderProjectNoScriptEntryHtml(pageTitle, localizedNoScriptEntryById.get(entry.id), localizedNoScriptProjectInput, localeModel, localizedContext, true),
772
879
  contentType: "text/html; charset=utf-8",
773
880
  role: "entry"
774
881
  });
@@ -801,13 +908,120 @@ function* createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex,
801
908
  contract: "documentation-portal-eager-fragment-index",
802
909
  contractVersion: "0.1.0-draft",
803
910
  fragments
804
- }, null, 2)}\n`,
911
+ })}\n`,
805
912
  contentType: "application/json; charset=utf-8",
806
913
  role: "index"
807
914
  });
808
915
  }
809
916
  yield* files;
810
917
  }
918
+ /**
919
+ * @lang zh-CN 历史核验与规范地址复用同一个正文渲染器。
920
+ * @lang en History validation and canonical addresses reuse the same prose renderer.
921
+ */
922
+ function renderProjectRouteTarget(entry, project, context, locale) {
923
+ return context.informationArchitecture
924
+ ? renderProjectSemanticTopic(entry, project, locale.locales, locale.selectedLocale, context, context.informationArchitecture.memberPlacement === "with-parent")
925
+ : renderProjectEntry(entry, locale.locales, locale.selectedLocale);
926
+ }
927
+ /**
928
+ * @lang zh-CN 在首写前核全部历史路径和锚点,只保存条目级元数据。
929
+ * @lang en Preflight all historical paths and anchors before the first write, retaining entry-level metadata only.
930
+ */
931
+ function prepareProjectRouteAliases(project, index, context, locale) {
932
+ const groups = new Map();
933
+ if (!context.routeHistory?.pathAliases.length)
934
+ return groups;
935
+ // <lang><zh-CN>历史不能覆盖当前正文或实际静态入口。</zh-CN><en>History cannot replace current prose or actual static entries.</en></lang>
936
+ const currentPaths = new Set(index.entries.flatMap(entry => [entry.contentPath, entry.noScriptPagePath, ...(entry.noScriptLocalePages ?? []).map(page => page.path)]).filter((file) => Boolean(file)).map(file => file.toLowerCase()));
937
+ const indexed = new Map(index.entries.map(entry => [entry.id, entry]));
938
+ for (const route of context.routeHistory.pathAliases) {
939
+ if (currentPaths.has(route.path.toLowerCase()))
940
+ throw new TypeError("HIA_PROJECT_ROUTE_HISTORY_INVALID: Legacy path shadows a current file.");
941
+ if (route.uiLocale && !indexed.get(route.entryId)?.noScriptLocalePages?.some(page => page.uiLocale === route.uiLocale))
942
+ throw new TypeError("HIA_PROJECT_ROUTE_HISTORY_INVALID: Missing localized target.");
943
+ const routes = groups.get(route.entryId) ?? [];
944
+ routes.push(route);
945
+ groups.set(route.entryId, routes);
946
+ }
947
+ const entries = new Map(project.entries.map(entry => [entry.id, entry]));
948
+ for (const [entryId, routes] of groups) {
949
+ const contents = renderProjectRouteTarget(entries.get(entryId), project, context, locale);
950
+ const anchors = new Set([...contents.matchAll(/\sid="([^"]*)"/gu)].map(match => match[1]));
951
+ for (const route of routes)
952
+ for (const anchor of route.anchors) {
953
+ if (!anchors.has(escapeHtml(anchor.targetId)))
954
+ throw new TypeError("HIA_PROJECT_ROUTE_HISTORY_INVALID: Historical anchor has no current counterpart.");
955
+ }
956
+ }
957
+ return groups;
958
+ }
959
+ /**
960
+ * @lang zh-CN 精确改写生成片段的已核id及页内链接,原生符号/地图与源码元数据保持。
961
+ * @lang en Remap verified IDs and local links in generated fragments while retaining native symbols/maps and source metadata.
962
+ */
963
+ function renderProjectLegacyFragment(contents, route) {
964
+ const anchors = new Map(route.anchors.map(anchor => [escapeHtml(anchor.targetId), escapeHtml(anchor.id)]));
965
+ const links = new Map(route.anchors.flatMap(anchor => [
966
+ [escapeHtml(anchor.targetId), escapeHtml(anchor.id)],
967
+ [escapeHtml(encodeURIComponent(anchor.targetId)), escapeHtml(encodeURIComponent(anchor.id))]
968
+ ]));
969
+ return contents.replace(/(\s)(id|href)="([^"]*)"/gu, (original, spacing, attribute, value) => {
970
+ if (attribute === "id" && anchors.has(value))
971
+ return `${spacing}id="${anchors.get(value)}"`;
972
+ if (attribute === "href" && value.startsWith("#") && links.has(value.slice(1)))
973
+ return `${spacing}href="#${links.get(value.slice(1))}"`;
974
+ return original;
975
+ });
976
+ }
977
+ /**
978
+ * @lang zh-CN 发出实际旧片段和已确认的无脚本恢复页,共用一份增强脚本。
979
+ * @lang en Emit actual historical fragments and confirmed script-free recovery pages, sharing one enhancement script.
980
+ */
981
+ function* createProjectRouteCompatibilityFiles(pageTitle, project, index, context, groups, locale) {
982
+ if (!groups.size)
983
+ return;
984
+ const entries = new Map(project.entries.map(entry => [entry.id, entry]));
985
+ const indexed = new Map(index.entries.map(entry => [entry.id, entry]));
986
+ let needsScript = false;
987
+ for (const [entryId, routes] of groups) {
988
+ const entry = entries.get(entryId);
989
+ const canonical = indexed.get(entryId);
990
+ // <lang><zh-CN>仅在当前条目迭代期间保留一个正文片段。</zh-CN><en>Retain one prose fragment only for the current entry iteration.</en></lang>
991
+ const fragment = renderProjectRouteTarget(entry, project, context, locale);
992
+ for (const route of routes) {
993
+ if (route.kind === "fragment") {
994
+ yield { path: route.path, contents: renderProjectLegacyFragment(fragment, route), contentType: "text/html; charset=utf-8", role: "asset" };
995
+ continue;
996
+ }
997
+ needsScript = true;
998
+ const uiLocale = route.uiLocale ?? context.uiLocale;
999
+ const pageContext = { ...withProjectUiLocale(context, uiLocale), runtimeUiMessages: false };
1000
+ const targetPage = route.uiLocale ? canonical.noScriptLocalePages.find(page => page.uiLocale === route.uiLocale).path : canonical.noScriptPagePath;
1001
+ const prefix = "../".repeat(route.path.split("/").length - 1);
1002
+ const target = prefix + targetPage;
1003
+ const messages = uiLocale === "zh-CN"
1004
+ ? { title: "旧链接已迁移", notice: "此条目的当前文档已就绪。无脚本模式可通过下列普通链接继续阅读原小节。", open: "打开当前条目", section: "阅读当前小节", missing: "旧链接中的小节暂无对应位置,请使用下方链接继续阅读。" }
1005
+ : { title: "This link has moved", notice: "The current documentation is available. Use the ordinary links below to continue to the same section without scripts.", open: "Open the current entry", section: "Read the current section", missing: "This section has no current counterpart. Use a link below to continue reading." };
1006
+ // <lang><zh-CN>小节顺序来自实际正文,输入记录顺序不改变阅读层级。</zh-CN><en>Section order comes from actual prose, preventing input record order from changing reading hierarchy.</en></lang>
1007
+ const sections = route.anchors.filter(anchor => anchor.targetId !== entry.id).sort((left, right) => fragment.indexOf(` id="${escapeHtml(left.targetId)}"`) - fragment.indexOf(` id="${escapeHtml(right.targetId)}"`)).map(anchor => {
1008
+ const position = fragment.indexOf(` id="${escapeHtml(anchor.targetId)}"`);
1009
+ const heading = fragment.slice(position, position + 2048).match(/<(h[1-6]|summary)\b[^>]*>([\s\S]*?)<\/\1>/u)?.[2] ?? escapeHtml(entry.name);
1010
+ const messageId = heading.match(/data-hia-ui-message="([^"]+)"/u)?.[1];
1011
+ const label = messageId ? escapeHtml(resolveProjectUiPlainText(pageContext, messageId, {}, entry.name)) : heading;
1012
+ return `<section class="hia-project-topic-section" id="${escapeHtml(anchor.id)}"><h2>${label}</h2><a href="${escapeHtml(target + "#" + encodeURIComponent(anchor.targetId))}">${escapeHtml(messages.section)}</a></section>`;
1013
+ }).join("");
1014
+ const article = `<article class="hia-project-entry" id="${escapeHtml(entry.id)}"><h1>${escapeHtml(messages.title)}</h1><p data-hia-route-status role="status">${escapeHtml(messages.notice)}</p><p><a href="${escapeHtml(target)}">${escapeHtml(messages.open)}</a></p>${sections}</article>`;
1015
+ const configuration = JSON.stringify({ target, anchors: route.anchors.map(anchor => [anchor.id, anchor.targetId]), missing: messages.missing }).replaceAll("<", "\\u003c");
1016
+ const enhancement = `<script type="application/json" data-hia-route-history-page>${configuration}</script><script defer src="${prefix}assets/hia-route-history.js"></script>`;
1017
+ const template = renderProjectNoScriptEntryHtml(pageTitle, entry, project, locale, pageContext, route.path.split("/").length > 2);
1018
+ const contents = template.replace(/<title>[\s\S]*?<\/title>/u, `<title>${escapeHtml(messages.title)} - ${escapeHtml(pageTitle)}</title>`).replace(/(<main\b[^>]*>)[\s\S]*?<\/main>/u, (_, opening) => `${opening}${article}</main>`).replace("</body>", `${enhancement}</body>`);
1019
+ yield { path: route.path, contents, contentType: "text/html; charset=utf-8", role: "entry" };
1020
+ }
1021
+ }
1022
+ if (needsScript)
1023
+ yield { path: "assets/hia-route-history.js", contents: PROJECT_ROUTE_HISTORY_SCRIPT, contentType: "text/javascript; charset=utf-8", role: "asset" };
1024
+ }
811
1025
  function createProjectNavigationShardFiles(nodes, loadingStrategy) {
812
1026
  const files = [];
813
1027
  const emittedPaths = new Set();
@@ -819,7 +1033,7 @@ function createProjectNavigationShardFiles(nodes, loadingStrategy) {
819
1033
  contractVersion: "0.1.0-draft",
820
1034
  nodeId: "root",
821
1035
  children: nodes
822
- }, null, 2)}\n`,
1036
+ })}\n`,
823
1037
  contentType: "application/json; charset=utf-8",
824
1038
  role: "index"
825
1039
  }];
@@ -837,7 +1051,7 @@ function createProjectNavigationShardFiles(nodes, loadingStrategy) {
837
1051
  contractVersion: "0.1.0-draft",
838
1052
  nodeId,
839
1053
  children: children.map(toLazyProjectNavigationNode)
840
- }, null, 2)}\n`,
1054
+ })}\n`,
841
1055
  contentType: "application/json; charset=utf-8",
842
1056
  role: "index"
843
1057
  });
@@ -863,7 +1077,27 @@ function toLazyProjectNavigationNode(node) {
863
1077
  function createProjectEntryContentPath(entryId) {
864
1078
  return `entries/${stableProjectArtifactName(entryId)}.html`;
865
1079
  }
866
- /** @lang zh-CN 为每个 neutral topic 生成稳定的 no-script owner page route。 @lang en Generates a stable no-script owner page route for every neutral topic. */
1080
+ /**
1081
+ * @lang zh-CN 在生成文件前拒绝不同条目投影到相同静态文件名,防止 FNV 文件名摘要碰撞时覆盖正文。
1082
+ * @lang en Refuses distinct entries projected to the same static filename before output, preventing body overwrite on an FNV filename digest collision.
1083
+ * @param entries - 已聚合的项目条目。Aggregated project entries.
1084
+ * @throws 当条目 ID 或其文件名投影重复时抛出固定错误,不回显可能敏感的 ID。Throws a fixed error for duplicate entry IDs or filename projections without exposing potentially sensitive IDs.
1085
+ */
1086
+ function assertUniqueProjectEntryArtifactNames(entries) {
1087
+ // <lang><zh-CN>同一文件名用于 entries/pages/本地化无脚本页;一次检查覆盖三类路由。</zh-CN><en>One filename is used by entries, pages and localized no-script pages, so one check covers all three routes.</en></lang>
1088
+ const names = new Set();
1089
+ for (const entry of entries) {
1090
+ const artifactName = stableProjectArtifactName(entry.id);
1091
+ if (names.has(artifactName)) {
1092
+ throw new TypeError("HIA_PORTAL_ENTRY_ARTIFACT_PATH_COLLISION: Distinct entries would share a static page path.");
1093
+ }
1094
+ names.add(artifactName);
1095
+ }
1096
+ }
1097
+ /**
1098
+ * @lang zh-CN 为每个 neutral topic 生成稳定的 no-script owner page route。
1099
+ * @lang en Generates a stable no-script owner page route for every neutral topic.
1100
+ */
867
1101
  function createProjectNoScriptPagePath(entryId) {
868
1102
  return `pages/${stableProjectArtifactName(entryId)}.html`;
869
1103
  }
@@ -897,7 +1131,17 @@ function createProjectSemanticContainerPath(entry) {
897
1131
  /** 仅按显式 parentSymbolId/symbolId 解析父入口,不执行名称或路径猜测。Resolves a parent only by explicit parentSymbolId/symbolId, with no name or path inference. */
898
1132
  function findProjectParentEntry(entry, entries) {
899
1133
  const parentSymbolId = entry.hierarchy?.parentSymbolId;
900
- return parentSymbolId ? entries.find((candidate) => candidate.symbolId === parentSymbolId) : undefined;
1134
+ return parentSymbolId ? entries.find((candidate) => (candidate.symbolId === parentSymbolId
1135
+ || Boolean(entry.identityScope && candidate.hierarchy?.symbolDocumentationId === parentSymbolId))
1136
+ && candidate.identityScope === entry.identityScope
1137
+ && (!entry.identityScope || candidate.view === entry.view)) : undefined;
1138
+ }
1139
+ /**
1140
+ * @lang zh-CN 为新作用域构造层级关联键,旧未限定符号保留原键及跨视图行为。
1141
+ * @lang en Build hierarchy join keys for new scopes, retaining original keys and cross-view behavior for legacy symbols.
1142
+ */
1143
+ function projectSymbolLookupKey(entry, symbolId) {
1144
+ return entry.identityScope ? JSON.stringify([entry.identityScope, entry.view, symbolId]) : symbolId;
901
1145
  }
902
1146
  /** 把 canonical 与 presentation location 投影到 leaf node,保持 tree node identity 不变。Projects canonical and presentation locations onto leaf nodes without changing tree-node identity. */
903
1147
  function applyProjectNavigationPresentationPaths(nodes, entries, informationArchitecture) {
@@ -1007,7 +1251,10 @@ function renderDefaultThemeRootAttributes(themeSelection) {
1007
1251
  : [])
1008
1252
  ].join(" ");
1009
1253
  }
1010
- /** @lang zh-CN 优先共用theme,逐项回退旧项目theme与默认值;未知选择在产生HTML前拒绝。 @lang en Prefers shared theme, falls back per field to legacy project theme and defaults, and rejects unknown selections before HTML generation. */
1254
+ /**
1255
+ * @lang zh-CN 优先共用theme,逐项回退旧项目theme与默认值;未知选择在产生HTML前拒绝。
1256
+ * @lang en Prefers shared theme, falls back per field to legacy project theme and defaults, and rejects unknown selections before HTML generation.
1257
+ */
1011
1258
  function resolveThemeSelection(options) {
1012
1259
  // <lang><zh-CN>皮肤与配色独立解析,不从品牌颜色推断另一种主题。</zh-CN><en>Resolve skin and scheme independently without inferring another theme from brand colors.</en></lang>
1013
1260
  const skinId = options.theme?.skinId ?? options.projectSite?.theme?.skinId ?? "portal.classic";
@@ -1050,50 +1297,53 @@ function renderIndexHtml(pageTitle, document, options) {
1050
1297
  ].join("");
1051
1298
  }
1052
1299
  /**
1053
- * @lang zh-CN
1054
- * 渲染一个带稳定 identity 的 UI 文本节点;译文先按纯文本解析,再进行 HTML 转义。
1300
+ * @lang zh-CN 渲染一个带稳定 identity 的 UI 文本节点;译文先按纯文本解析,再进行 HTML 转义。
1055
1301
  *
1056
- * @lang en
1057
- * Renders a UI text node with a stable identity; translation is resolved as plain text before HTML escaping.
1302
+ * @lang en Renders a UI text node with a stable identity; translation is resolved as plain text before HTML escaping.
1058
1303
  */
1059
1304
  function renderProjectUiMessage(portalContext, messageId, values = {}, fallback = "") {
1060
1305
  if (!portalContext.uiLocaleAdoption) {
1061
1306
  return escapeHtml(fallback);
1062
1307
  }
1063
- const valueAttribute = Object.keys(values).length > 0
1064
- ? ` data-hia-ui-values="${escapeHtml(JSON.stringify(values))}"`
1065
- : "";
1066
- const text = resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values);
1067
- return `<span data-hia-ui-message="${escapeHtml(messageId)}"${valueAttribute}>${escapeHtml(text)}</span>`;
1308
+ const { attributes, text } = renderProjectUiMarkedText(portalContext, messageId, values);
1309
+ // <lang><zh-CN>持久历史站的固定语言页直接输出已转义消息,省去无属性且无运行时用途的包装。</zh-CN><en>Fixed-language history pages emit escaped messages directly, omitting attribute-free wrappers with no runtime role.</en></lang>
1310
+ if (portalContext.routeHistory && !attributes)
1311
+ return text;
1312
+ return `<span${attributes}>${text}</span>`;
1068
1313
  }
1069
- /** @lang zh-CN 解析 attribute/dynamic state 使用的 UI 纯文本,并为 legacy surface 保留既有 fallback。 @lang en Resolves UI plain text for attributes/dynamic state while retaining the existing fallback for legacy surfaces. */
1314
+ /**
1315
+ * @lang zh-CN 解析 attribute/dynamic state 使用的 UI 纯文本,并为 legacy surface 保留既有 fallback。
1316
+ * @lang en Resolves UI plain text for attributes/dynamic state while retaining the existing fallback for legacy surfaces.
1317
+ */
1070
1318
  function resolveProjectUiPlainText(portalContext, messageId, values = {}, fallback = "") {
1071
1319
  return portalContext.uiLocaleAdoption
1072
1320
  ? resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values)
1073
1321
  : fallback;
1074
1322
  }
1075
- /** @lang zh-CN 为共享 legacy/adopted renderer helper 选择带 marker 的消息或原有文本。 @lang en Selects a marked message or original text for renderer helpers shared by legacy and adopted surfaces. */
1323
+ /**
1324
+ * @lang zh-CN 为共享 legacy/adopted renderer helper 选择带 marker 的消息或原有文本。
1325
+ * @lang en Selects a marked message or original text for renderer helpers shared by legacy and adopted surfaces.
1326
+ */
1076
1327
  function renderOptionalProjectUiMessage(portalContext, messageId, fallback, values = {}) {
1077
1328
  return portalContext
1078
1329
  ? renderProjectUiMessage(portalContext, messageId, values, fallback)
1079
1330
  : escapeHtml(fallback);
1080
1331
  }
1081
1332
  /**
1082
- * @lang zh-CN
1083
- * 为不能包裹 span 的元素生成稳定 message marker,并返回已转义文本。
1333
+ * @lang zh-CN 为不能包裹 span 的元素生成稳定 message marker,并返回已转义文本。
1084
1334
  *
1085
- * @lang en
1086
- * Creates a stable message marker for elements that cannot wrap a span and returns escaped text.
1335
+ * @lang en Creates a stable message marker for elements that cannot wrap a span and returns escaped text.
1087
1336
  */
1088
1337
  function renderProjectUiMarkedText(portalContext, messageId, values = {}) {
1089
1338
  if (!portalContext.uiLocaleAdoption) {
1090
1339
  return { attributes: "", text: "" };
1091
1340
  }
1092
- const valueAttribute = Object.keys(values).length > 0
1341
+ // <lang><zh-CN>无脚本页面保留标签结构和转义后的译文,省掉仅运行时消费的消息身份与参数。</zh-CN><en>Script-free pages keep their element structure and escaped translations while omitting runtime-only message identities and values.</en></lang>
1342
+ const valueAttribute = portalContext.runtimeUiMessages !== false && Object.keys(values).length > 0
1093
1343
  ? ` data-hia-ui-values="${escapeHtml(JSON.stringify(values))}"`
1094
1344
  : "";
1095
1345
  return {
1096
- attributes: ` data-hia-ui-message="${escapeHtml(messageId)}"${valueAttribute}`,
1346
+ attributes: portalContext.runtimeUiMessages === false ? "" : ` data-hia-ui-message="${escapeHtml(messageId)}"${valueAttribute}`,
1097
1347
  text: escapeHtml(resolveDocumentationPortalUiMessage(portalContext.uiLocaleAdoption, portalContext.uiLocale, messageId, values))
1098
1348
  };
1099
1349
  }
@@ -1108,7 +1358,10 @@ function withProjectUiLocale(portalContext, uiLocale) {
1108
1358
  labels: getDocumentationPortalLabels(uiLocale)
1109
1359
  };
1110
1360
  }
1111
- /** @lang zh-CN 渲染彼此独立的 UI/content locale 原生控件。 @lang en Renders independent native UI/content-locale controls. */
1361
+ /**
1362
+ * @lang zh-CN 渲染彼此独立的 UI/content locale 原生控件。
1363
+ * @lang en Renders independent native UI/content-locale controls.
1364
+ */
1112
1365
  function renderProjectLocaleControls(contentLocales, selectedContentLocale, portalContext) {
1113
1366
  if (!portalContext.uiLocaleAdoption) {
1114
1367
  return renderLocaleControl(contentLocales, selectedContentLocale);
@@ -1124,8 +1377,11 @@ function renderProjectLocaleControls(contentLocales, selectedContentLocale, port
1124
1377
  "</div>"
1125
1378
  ].join("");
1126
1379
  }
1127
- /** @lang zh-CN 渲染带 no-script theme 默认和可见选择器的 split-site 应用壳。 @lang en Renders the split-site shell with a no-script theme default and visible selectors. */
1128
- function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext) {
1380
+ /**
1381
+ * @lang zh-CN 渲染带 no-script theme 默认和可见选择器的 split-site 应用壳。
1382
+ * @lang en Renders the split-site shell with a no-script theme default and visible selectors.
1383
+ */
1384
+ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext, navigationTree) {
1129
1385
  const projectName = projectInput.project.title ?? projectInput.project.name;
1130
1386
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
1131
1387
  const views = collectProjectViews(projectInput.entries);
@@ -1161,7 +1417,7 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalCont
1161
1417
  `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${renderProjectUiMessage(portalContext, "portal.navigation.select", {}, labels.select)}</p><noscript><p class="hia-noscript-notice"><a href="pages/index.html">${renderProjectUiMessage(portalContext, "portal.navigation.noscriptlink", {}, "No-script page index / 无脚本页面索引")}</a></p></noscript></main>`,
1162
1418
  "</div>",
1163
1419
  `<script src="${escapeHtml(DEFAULT_THEME_JS_PATH)}"></script>`,
1164
- renderProjectSplitSiteScript(portalContext, portalContext.informationArchitecture?.loadingStrategy ?? "lazy"),
1420
+ renderProjectSplitSiteScript(portalContext, portalContext.informationArchitecture?.loadingStrategy ?? "lazy", portalContext.siteNavigation ? navigationTree : []),
1165
1421
  "</body>",
1166
1422
  "</html>"
1167
1423
  ].join("");
@@ -1203,7 +1459,7 @@ function renderProjectNoScriptIndexHtml(pageTitle, projectInput, selectedContent
1203
1459
  alternateLinks ? `<p>${alternateLinks}</p>` : "",
1204
1460
  `<p>${renderProjectUiMessage(portalContext, "portal.theme.skinlabel", {}, "Skin")}:${renderProjectUiMessage(portalContext, skinMessageId, {}, getPortalThemeSkinLabel(portalContext.theme.skinId))} · ${renderProjectUiMessage(portalContext, "portal.theme.schemelabel", {}, "Scheme")}:${renderProjectUiMessage(portalContext, schemeMessageId, {}, getPortalThemeSchemeLabel(portalContext.theme.scheme))}</p>`,
1205
1461
  `</aside><main class="hia-main hia-project-main"><h2>${renderProjectUiMessage(portalContext, "portal.noscript.pagesheading", {}, "Documentation pages / 文档页面")}</h2>`,
1206
- `<nav aria-label="${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.noscript.pagesaccessible", {}, "Documentation pages"))}"${portalContext.uiLocaleAdoption ? " data-hia-ui-aria=\"portal.noscript.pagesaccessible\"" : ""}><ul>${links}</ul></nav>`,
1462
+ `<nav aria-label="${escapeHtml(resolveProjectUiPlainText(portalContext, "portal.noscript.pagesaccessible", {}, "Documentation pages"))}"${portalContext.uiLocaleAdoption && portalContext.runtimeUiMessages !== false ? " data-hia-ui-aria=\"portal.noscript.pagesaccessible\"" : ""}><ul>${links}</ul></nav>`,
1207
1463
  "</main></div></body></html>"
1208
1464
  ].join("");
1209
1465
  }
@@ -1268,6 +1524,8 @@ function renderProjectSourceFetchClientLines(rootExpression) {
1268
1524
  " const loadButton = details.querySelector('[data-hia-source-fetch-button]');",
1269
1525
  " const resetButton = details.querySelector('[data-hia-source-reset]');",
1270
1526
  " const status = details.querySelector('[data-hia-source-fetch-status]');",
1527
+ " /* <lang><zh-CN>在隐藏控件前记录其焦点归属,后续只交接本次确实被隐藏的发起控件。</zh-CN><en>Remember focus ownership before hiding controls, transferring only from the initiating control hidden by this update.</en></lang> */",
1528
+ " const focusedControl = document.activeElement;",
1271
1529
  " details.dataset.hiaSourceState = state;",
1272
1530
  " details.toggleAttribute('aria-busy', state === 'loading');",
1273
1531
  " if (status) {",
@@ -1283,6 +1541,9 @@ function renderProjectSourceFetchClientLines(rootExpression) {
1283
1541
  " resetButton.dataset.hiaUiMessage = resetMessageId;",
1284
1542
  " resetButton.textContent = sourceUiMessage(resetMessageId, state === 'loading' ? 'Cancel' : 'Reset');",
1285
1543
  " }",
1544
+ " /* <lang><zh-CN>加载交给现有取消控件;重置交回手动加载或原生summary,默认聚焦滚动揭示目标,并尊重用户已移走的焦点。</zh-CN><en>Loading hands off to the existing cancel control; reset restores manual load or the native summary, using default focus scrolling to reveal it and respecting user-moved focus.</en></lang> */",
1545
+ " if (focusedControl === loadButton && loadButton?.hidden) resetButton?.focus();",
1546
+ " if (focusedControl === resetButton && resetButton?.hidden) (loadButton || details.querySelector(':scope > summary'))?.focus();",
1286
1547
  " }",
1287
1548
  " function sourceFailureState(response) {",
1288
1549
  " if (response.status === 401 || response.status === 403) return 'denied';",
@@ -1311,8 +1572,9 @@ function renderProjectSourceFetchClientLines(rootExpression) {
1311
1572
  " const response = await fetch(target, { cache: 'default', credentials: 'omit', mode: 'same-origin', redirect: 'error', signal: controller.signal });",
1312
1573
  " if (!response.ok) {",
1313
1574
  " const state = sourceFailureState(response);",
1314
- " const detail = `${response.status} ${response.statusText}`;",
1315
- " setSourceState(details, state, 'portal.source.status.failed', `Source load failed: ${detail}`, { detail });",
1575
+ " /* <lang><zh-CN>按已知HTTP结果给固定公开反馈,禁止回显服务端statusText或响应正文。</zh-CN><en>Use fixed public feedback for known HTTP outcomes without reflecting server statusText or response bodies.</en></lang> */",
1576
+ " const message = state === 'denied' ? ['portal.source.status.denied', 'Source request denied.'] : state === 'not-found' ? ['portal.source.status.notfound', 'Source asset was not found.'] : ['portal.source.status.network', 'Source is temporarily unavailable.'];",
1577
+ " setSourceState(details, state, message[0], message[1]);",
1316
1578
  " return;",
1317
1579
  " }",
1318
1580
  " /* <lang><zh-CN>先验证字节数与 SHA-384,再把公开 asset 解码为不可执行纯文本。</zh-CN><en>Verify byte length and SHA-384 before decoding the public asset as non-executable plain text.</en></lang> */",
@@ -1367,8 +1629,8 @@ function renderProjectSourceFetchClientLines(rootExpression) {
1367
1629
  " setSourceState(details, 'ready', 'portal.source.status.ready', 'Source ready.');",
1368
1630
  " } catch (error) {",
1369
1631
  " const aborted = error?.name === 'AbortError';",
1370
- " const detail = String(error?.message || error);",
1371
- " setSourceState(details, aborted ? 'aborted' : 'network-error', aborted ? 'portal.source.status.aborted' : 'portal.source.status.failed', aborted ? 'Source load aborted.' : `Source load failed: ${detail}`, aborted ? {} : { detail });",
1632
+ " /* <lang><zh-CN>网络异常仅映射为固定状态,原异常可能携带主机路径或端点细节。</zh-CN><en>Map network exceptions to fixed states only; original exceptions may carry host paths or endpoint details.</en></lang> */",
1633
+ " setSourceState(details, aborted ? 'aborted' : 'network-error', aborted ? 'portal.source.status.aborted' : 'portal.source.status.network', aborted ? 'Source load aborted.' : 'Source is temporarily unavailable.');",
1372
1634
  " } finally {",
1373
1635
  " clearTimeout(timeout);",
1374
1636
  " sourceControllers.delete(details);",
@@ -1400,7 +1662,38 @@ function renderProjectSourceFetchClientLines(rootExpression) {
1400
1662
  " }"
1401
1663
  ];
1402
1664
  }
1403
- function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1665
+ function renderProjectSplitSiteScript(portalContext, loadingStrategy, readingTree = []) {
1666
+ // <lang><zh-CN>共享祖先只存一次,条目持有父索引和已验证的真实呈现路径。数据仅随同次HTML运行时消费。</zh-CN><en>Store shared ancestors once, retaining parent indexes and validated presentation paths per entry for this HTML runtime only.</en></lang>
1667
+ const readingParents = [];
1668
+ const readingEntries = [];
1669
+ /**
1670
+ * @lang zh-CN 遍历已验证的中性树,记录单一祖先和条目路由,复用原规范/呈现位置及成员锚点。
1671
+ * @lang en Walks the validated neutral tree to record unique ancestors and routes, reusing canonical/presentation locations and member anchors.
1672
+ * @param nodes <lang><zh-CN>当前层的已验证导航节点。</zh-CN><en>Validated navigation nodes at this level.</en></lang>
1673
+ * @param parent <lang><zh-CN>共享祖先表中的父索引,根使用-1。</zh-CN><en>Parent index in the shared ancestor table, with -1 for the root.</en></lang>
1674
+ */
1675
+ function collectReadingRoutes(nodes, parent) {
1676
+ for (const node of nodes) {
1677
+ if (node.entryId && node.contentPath)
1678
+ readingEntries.push([node.entryId, {
1679
+ parent,
1680
+ contentPath: node.contentPath,
1681
+ // <lang><zh-CN>只记录不同于规范路径/条目ID的覆写,运行时复用原有回退,避免重复传输相同字符串。</zh-CN><en>Record only overrides differing from the canonical path/entry ID, reusing runtime fallbacks instead of transmitting identical strings twice.</en></lang>
1682
+ ...(node.presentationPath && node.presentationPath !== node.contentPath ? { presentationPath: node.presentationPath } : {}),
1683
+ ...(node.memberAnchor && node.memberAnchor !== node.entryId ? { memberAnchor: node.memberAnchor } : {}),
1684
+ ...(node.views[0] ? { view: node.views[0] } : {})
1685
+ }]);
1686
+ if (node.children?.length) {
1687
+ // <lang><zh-CN>当前分支登记后才递归子层,每个条目的父链按索引可逆恢复。</zh-CN><en>Register this branch before descending so every entry's parent chain remains reversibly indexed.</en></lang>
1688
+ const childParent = readingParents.length;
1689
+ readingParents.push({ id: node.id, path: createProjectNavigationChildrenPath(node.id), parent });
1690
+ collectReadingRoutes(node.children, childParent);
1691
+ }
1692
+ }
1693
+ }
1694
+ const directReading = Boolean(portalContext.siteNavigation || portalContext.routeHistory);
1695
+ if (directReading)
1696
+ collectReadingRoutes(readingTree, -1);
1404
1697
  // <lang><zh-CN>只有 adopted surface 嵌入 public plain-text bundle;metadata-only report 仍不含译文。</zh-CN><en>Only adopted surfaces embed the public plain-text bundle; the metadata-only report still contains no translations.</en></lang>
1405
1698
  const uiConfig = portalContext.uiLocaleAdoption
1406
1699
  ? {
@@ -1414,6 +1707,37 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1414
1707
  "<script>",
1415
1708
  "(() => {",
1416
1709
  ` const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json', loadingStrategy: ${JSON.stringify(loadingStrategy)}, eagerContent: 'content/eager.json', ui: ${JSON.stringify(uiConfig)} };`,
1710
+ ...(directReading ? [
1711
+ ` const readingParents = ${JSON.stringify(readingParents).replaceAll("<", "\\u003c")};`,
1712
+ ` const readingEntries = new Map(${JSON.stringify(readingEntries).replaceAll("<", "\\u003c")});`,
1713
+ ...(portalContext.routeHistory ? [` const readingAliases = new Map(${JSON.stringify(portalContext.routeHistory.entryAliases.map(alias => [alias.entryId, alias.canonicalEntryId])).replaceAll("<", "\\u003c")});`] : []),
1714
+ ...(portalContext.siteNavigation ? [" const readingBranches = new WeakMap();"] : []),
1715
+ " let readingEntrySequence = 0;",
1716
+ " let readingNavigation = Promise.resolve();"
1717
+ ] : []),
1718
+ ...(portalContext.siteNavigation ? [
1719
+ " /* <lang><zh-CN>同一分片的展开和深链恢复共享在途请求,失败允许下一次显式重试。</zh-CN><en>Disclosure and deep-link restoration share in-flight shard requests, allowing explicit retries after failure.</en></lang> */",
1720
+ " function loadReadingBranch(details, path) {",
1721
+ " if (details.dataset.loaded === 'true') return Promise.resolve();",
1722
+ " if (readingBranches.has(details)) return readingBranches.get(details);",
1723
+ " const loading = document.createElement('p'); loading.className = 'hia-project-loading'; loading.setAttribute('role', 'status'); loading.dataset.hiaUiMessage = 'portal.navigation.loading'; loading.textContent = uiMessage('portal.navigation.loading', {}, 'Loading…');",
1724
+ " details.querySelector(':scope > .hia-project-loading')?.remove(); details.append(loading);",
1725
+ " const request = readJson(path).then(shard => { loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : [])); details.dataset.loaded = 'true'; }).catch(error => { loading.textContent = uiMessage('portal.navigation.loaderror', { detail: String(error?.message || error) }, 'Navigation unavailable.'); throw error; }).finally(() => readingBranches.delete(details));",
1726
+ " readingBranches.set(details, request); return request;",
1727
+ " }",
1728
+ " /* <lang><zh-CN>仅打开选中项实际祖先,正文加载失败或目录故障不获取无关源码。</zh-CN><en>Open only actual selected-item ancestors without fetching unrelated sources when content or directory loading fails.</en></lang> */",
1729
+ " async function revealReadingEntry(entryId, requestSequence) {",
1730
+ " /* <lang><zh-CN>从本次HTML的父索引恢复根到叶路径,无需获取全量检索索引。</zh-CN><en>Restore root-to-leaf paths from this HTML's parent indexes without fetching the full search index.</en></lang> */",
1731
+ " const ancestors = [];",
1732
+ " for (let parent = readingEntries.get(entryId)?.parent ?? -1; parent >= 0; parent = readingParents[parent].parent) ancestors.unshift(readingParents[parent]);",
1733
+ " for (const ancestor of ancestors) {",
1734
+ " if (requestSequence !== readingEntrySequence) return;",
1735
+ " const item = Array.from(treeHost?.querySelectorAll('[data-hia-project-node-id]') || []).find(item => item.dataset.hiaProjectNodeId === ancestor.id);",
1736
+ " const details = item?.querySelector(':scope > details'); if (!details) continue;",
1737
+ " details.open = true; try { await loadReadingBranch(details, ancestor.path); } catch { break; }",
1738
+ " }",
1739
+ " }"
1740
+ ] : []),
1417
1741
  " const treeHost = document.querySelector('[data-hia-project-tree]');",
1418
1742
  " const contentHost = document.querySelector('[data-hia-project-content]');",
1419
1743
  " const search = document.querySelector('[data-hia-project-search]');",
@@ -1422,6 +1746,9 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1422
1746
  " const viewButtons = Array.from(document.querySelectorAll('[data-hia-project-view]'));",
1423
1747
  " let rootNodes = [];",
1424
1748
  " let searchEntries = null;",
1749
+ // <lang><zh-CN>索引在途请求共享;查询序号让清空/过滤变化后的旧响应失效。</zh-CN><en>Share the in-flight index read; query generations invalidate responses after clearing or filter changes.</en></lang>
1750
+ " let searchIndexPromise = null;",
1751
+ " let searchSequence = 0;",
1425
1752
  " let eagerFragments = null;",
1426
1753
  " let activeView = 'all';",
1427
1754
  " function uiMessage(messageId, values = {}, fallback = messageId) {",
@@ -1440,6 +1767,11 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1440
1767
  " for (const node of root.querySelectorAll('[data-hia-ui-message]')) node.textContent = uiMessage(node.getAttribute('data-hia-ui-message'), readUiValues(node));",
1441
1768
  " for (const node of root.querySelectorAll('[data-hia-ui-placeholder]')) node.setAttribute('placeholder', uiMessage(node.getAttribute('data-hia-ui-placeholder')));",
1442
1769
  " for (const node of root.querySelectorAll('[data-hia-ui-aria]')) node.setAttribute('aria-label', uiMessage(node.getAttribute('data-hia-ui-aria')));",
1770
+ // <lang><zh-CN>导航href只能来自首写前验证的两语言数据;UI切换不猜测URL或变更正文语言。</zh-CN><en>Navigation hrefs come only from bilingual data validated before output; UI switching guesses no URLs and does not change content locale.</en></lang>
1771
+ ...(portalContext.siteNavigation ? [
1772
+ " for (const node of root.querySelectorAll('[data-hia-site-hrefs]')) { const targets = JSON.parse(node.getAttribute('data-hia-site-hrefs')); node.setAttribute('href', targets[selected]); }",
1773
+ " for (const node of root.querySelectorAll('[data-hia-site-language]')) { const other = selected === 'en' ? 'zh-CN' : 'en'; node.lang = other; node.hreflang = other; }"
1774
+ ] : []),
1443
1775
  " try { localStorage.setItem('hia-doc-portal-ui-locale', selected); } catch {}",
1444
1776
  " document.dispatchEvent(new CustomEvent('hia:ui-locale-change', { detail: { uiLocale: selected } }));",
1445
1777
  " }",
@@ -1448,12 +1780,17 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1448
1780
  " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
1449
1781
  " return response.json();",
1450
1782
  " }",
1451
- " function showLoadError(error) {",
1783
+ " function showLoadError(error, searchFailure = false) {",
1452
1784
  ` const detail = location.protocol === 'file:' ? ${JSON.stringify(fileProtocolMessage)} : String(error?.message || error);`,
1453
1785
  " const hint = location.protocol === 'file:' ? detail : uiMessage('portal.navigation.loaderror', { detail }, detail);",
1454
- " if (contentHost) contentHost.innerHTML = '';",
1786
+ ...(portalContext.siteNavigation ? [
1787
+ // <lang><zh-CN>目录或索引故障保留已读正文,只替换本次状态提示。</zh-CN><en>Keep the current prose on directory/index failure, replacing only the current status.</en></lang>
1788
+ " contentHost?.querySelector(':scope > .hia-project-load-error')?.remove();"
1789
+ ] : [" if (contentHost) contentHost.innerHTML = '';"]),
1455
1790
  " const message = document.createElement('p');",
1456
1791
  " message.className = 'hia-project-load-error';",
1792
+ // <lang><zh-CN>检索专属失败可在成功重试或清空查询后移除,独立目录/条目故障继续保留。</zh-CN><en>Search-specific failures can clear after successful retry or query reset while independent navigation/entry failures remain.</en></lang>
1793
+ " if (searchFailure) message.dataset.hiaSearchError = '';",
1457
1794
  " message.setAttribute('role', 'status');",
1458
1795
  " message.dataset.hiaUiMessage = location.protocol === 'file:' ? 'portal.navigation.requiresserver' : 'portal.navigation.loaderror';",
1459
1796
  " if (location.protocol !== 'file:') message.dataset.hiaUiValues = JSON.stringify({ detail });",
@@ -1500,22 +1837,26 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1500
1837
  " details.dataset.loaded = 'true';",
1501
1838
  " details.append(createTreeList(inlineChildren));",
1502
1839
  " } else {",
1503
- " details.addEventListener('toggle', async () => {",
1504
- " if (!details.open || details.dataset.loaded === 'true') return;",
1505
- " details.dataset.loaded = 'true';",
1506
- " const loading = document.createElement('p');",
1507
- " loading.className = 'hia-project-loading';",
1508
- " loading.setAttribute('role', 'status');",
1509
- " loading.dataset.hiaUiMessage = 'portal.navigation.loading';",
1510
- ` loading.textContent = uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)});`,
1511
- " details.append(loading);",
1512
- " try {",
1513
- " const shard = await readJson(node.childrenPath);",
1514
- " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
1515
- " } catch (error) {",
1516
- " loading.textContent = String(error?.message || error);",
1517
- " }",
1518
- " });",
1840
+ ...(portalContext.siteNavigation ? [
1841
+ " details.addEventListener('toggle', () => { if (details.open) loadReadingBranch(details, node.childrenPath).catch(() => {}); });"
1842
+ ] : [
1843
+ " details.addEventListener('toggle', async () => {",
1844
+ " if (!details.open || details.dataset.loaded === 'true') return;",
1845
+ " details.dataset.loaded = 'true';",
1846
+ " const loading = document.createElement('p');",
1847
+ " loading.className = 'hia-project-loading';",
1848
+ " loading.setAttribute('role', 'status');",
1849
+ " loading.dataset.hiaUiMessage = 'portal.navigation.loading';",
1850
+ ` loading.textContent = uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)});`,
1851
+ " details.append(loading);",
1852
+ " try {",
1853
+ " const shard = await readJson(node.childrenPath);",
1854
+ " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
1855
+ " } catch (error) {",
1856
+ " loading.textContent = String(error?.message || error);",
1857
+ " }",
1858
+ " });"
1859
+ ]),
1519
1860
  " }",
1520
1861
  " item.append(details);",
1521
1862
  " } else if (node.entryId && node.contentPath) {",
@@ -1572,40 +1913,102 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1572
1913
  " const leaf = Array.from(document.querySelectorAll('[data-hia-project-entry-id]')).find((item) => item.dataset.hiaProjectEntryId === entryId);",
1573
1914
  " if (!leaf) return;",
1574
1915
  " leaf.dataset.hiaActiveEntry = 'true';",
1916
+ ...(portalContext.siteNavigation ? [
1917
+ " for (const control of treeHost.querySelectorAll('[aria-current]')) control.removeAttribute('aria-current');",
1918
+ " const currentControl = leaf.querySelector(':scope > .hia-project-entry-link, :scope > details > summary > .hia-project-entry-link'); currentControl?.setAttribute('aria-current', 'page');"
1919
+ ] : []),
1575
1920
  " for (const details of leaf.parentElement?.closest('details') ? [leaf.parentElement.closest('details')] : []) {",
1576
1921
  " let current = details;",
1577
- " while (current) { current.open = true; current.dataset.hiaActiveAncestor = 'true'; current = current.parentElement?.closest('details'); }",
1922
+ ...(portalContext.siteNavigation ? [
1923
+ // <lang><zh-CN>只展开树内祖先,不强行打开外层手机目录或改变其阅读位置。</zh-CN><en>Expand only in-tree ancestors without forcing the outer mobile directory open or moving its reading position.</en></lang>
1924
+ " while (current && treeHost.contains(current)) { current.open = true; current.dataset.hiaActiveAncestor = 'true'; current = current.parentElement?.closest('details'); }"
1925
+ ] : [" while (current) { current.open = true; current.dataset.hiaActiveAncestor = 'true'; current = current.parentElement?.closest('details'); }"]),
1578
1926
  " }",
1579
1927
  " }",
1580
1928
  " async function loadEntry(entry, updateHash) {",
1581
1929
  " if (!contentHost) return;",
1582
- ` contentHost.innerHTML = \`<p class="hia-project-loading" role="status" data-hia-ui-message="portal.navigation.loading">\${uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)})}</p>\`;`,
1930
+ ...(!portalContext.siteNavigation && portalContext.routeHistory ? [" const requestSequence = ++readingEntrySequence;"] : []),
1931
+ ...(portalContext.siteNavigation ? [
1932
+ // <lang><zh-CN>记录发起树控件;迟到响应只能转移仍由它持有的手机焦点。</zh-CN><en>Remember the initiating tree control so a late response only transfers mobile focus it still owns.</en></lang>
1933
+ " const readingTrigger = treeHost.contains(document.activeElement) ? document.activeElement : null;",
1934
+ " const requestSequence = ++readingEntrySequence;",
1935
+ " contentHost.querySelector(':scope > .hia-project-loading')?.remove();",
1936
+ " const readingLoading = document.createElement('p'); readingLoading.className = 'hia-project-loading'; readingLoading.setAttribute('role', 'status'); readingLoading.dataset.hiaUiMessage = 'portal.navigation.loading'; readingLoading.textContent = uiMessage('portal.navigation.loading', {}, 'Loading…'); contentHost.prepend(readingLoading);"
1937
+ ] : [` contentHost.innerHTML = \`<p class="hia-project-loading" role="status" data-hia-ui-message="portal.navigation.loading">\${uiMessage('portal.navigation.loading', {}, ${JSON.stringify(portalContext.labels.loading)})}</p>\`;`]),
1583
1938
  " try {",
1584
1939
  " const contentPath = entry.presentationPath || entry.contentPath;",
1585
- " contentHost.innerHTML = await readFragment(contentPath);",
1940
+ ...(directReading ? [
1941
+ " const readingContents = await readFragment(contentPath); if (requestSequence !== readingEntrySequence) return; contentHost.innerHTML = readingContents;"
1942
+ ] : [" contentHost.innerHTML = await readFragment(contentPath);"]),
1586
1943
  " applyContentLocale();",
1587
1944
  " applyUiLocale(contentHost);",
1588
1945
  " bindSourceFetch();",
1946
+ ...(portalContext.siteNavigation ? [
1947
+ " contentHost.dataset.hiaReadingEntry = entry.entryId || entry.id;",
1948
+ " document.dispatchEvent(new Event('hia:site-content'));"
1949
+ ] : []),
1589
1950
  " const anchor = entry.memberAnchor || entry.entryId || entry.id;",
1590
1951
  " const target = Array.from(contentHost.querySelectorAll('[id]')).find((item) => item.id === anchor);",
1952
+ ...(portalContext.siteNavigation ? [
1953
+ " /* <lang><zh-CN>同页成员可在关闭的小节内,先展开真实正文祖先再定位,无需目录响应。</zh-CN><en>A same-page member can be inside a closed section. Open actual prose ancestors before positioning without waiting for directory data.</en></lang> */",
1954
+ " for (let section = target?.parentElement?.closest('details'); section && contentHost.contains(section); section = section.parentElement?.closest('details')) section.open = true;"
1955
+ ] : []),
1591
1956
  " target?.scrollIntoView({ block: 'start' });",
1957
+ ...(portalContext.siteNavigation ? [
1958
+ // <lang><zh-CN>在清空检索前记录目录重建条件,避免删除当前控件后才尝试转移焦点。</zh-CN><en>Record the directory-reset condition before clearing search, avoiding focus transfer after its control is removed.</en></lang>
1959
+ " const readingResetsTree = Boolean(search?.value || (activeView !== 'all' && entry.view && entry.view !== activeView));",
1960
+ // <lang><zh-CN>手机或即将重建的目录先将仍属发起控件的焦点移到已装入的正文。</zh-CN><en>On mobile or before rebuilding the directory, transfer focus still owned by its trigger to the loaded prose.</en></lang>
1961
+ " if ((matchMedia('(max-width:800px)').matches || readingResetsTree) && readingTrigger && document.activeElement === readingTrigger) contentHost.closest('main')?.focus({preventScroll:true});",
1962
+ " if (readingResetsTree) { searchSequence++; activeView = 'all'; if (search) search.value = ''; for (const button of viewButtons) button.setAttribute('aria-pressed', String(button.dataset.hiaProjectView === 'all')); renderRoot(); }",
1963
+ " /* <lang><zh-CN>正文已呈现后再等根目录,较新的选择可取消旧祖先恢复。</zh-CN><en>Await the root only after presenting prose, allowing newer selections to invalidate older ancestor restoration.</en></lang> */",
1964
+ " await readingNavigation; if (requestSequence !== readingEntrySequence) return;",
1965
+ " await revealReadingEntry(entry.entryId || entry.id, requestSequence); if (requestSequence !== readingEntrySequence) return;"
1966
+ ] : []),
1592
1967
  " markActiveEntry(entry.entryId || entry.id);",
1968
+ ...(portalContext.siteNavigation ? [
1969
+ " if (!matchMedia('(max-width:800px)').matches) treeHost.querySelector('[aria-current=\"page\"]')?.scrollIntoView({block:'nearest', inline:'nearest'});"
1970
+ ] : []),
1593
1971
  " if (updateHash) history.replaceState(null, '', `#entry=${encodeURIComponent(entry.entryId || entry.id)}`);",
1594
1972
  " } catch (error) {",
1595
- " showLoadError(error);",
1973
+ ...(portalContext.siteNavigation ? [
1974
+ " if (requestSequence !== readingEntrySequence) return; const loading = contentHost.querySelector(':scope > .hia-project-loading'); if (loading) { loading.setAttribute('role', 'alert'); loading.textContent = uiMessage('portal.navigation.loaderror', { detail: String(error?.message || error) }, 'Entry unavailable.'); }"
1975
+ ] : [portalContext.routeHistory ? " if (requestSequence === readingEntrySequence) showLoadError(error);" : " showLoadError(error);"]),
1596
1976
  " }",
1597
1977
  " }",
1598
1978
  " async function ensureSearchIndex() {",
1599
1979
  " if (searchEntries) return searchEntries;",
1600
- " const index = await readJson(config.search);",
1601
- " searchEntries = Array.isArray(index.entries) ? index.entries : [];",
1602
- " return searchEntries;",
1980
+ // <lang><zh-CN>坏JSON/缺集合属于索引失败,固定错误避免回显响应正文;失败释放共享请求以供显式重试。</zh-CN><en>Invalid JSON or a missing collection is an index failure. A fixed error excludes response bodies, and failed shared reads are released for explicit retry.</en></lang>
1981
+ " if (!searchIndexPromise) searchIndexPromise = readJson(config.search).then(index => {",
1982
+ " if (!index || !Array.isArray(index.entries)) throw new Error('Search index unavailable.');",
1983
+ " searchEntries = index.entries; return searchEntries;",
1984
+ " }).catch(() => { throw new Error('Search index unavailable.'); }).finally(() => { searchIndexPromise = null; });",
1985
+ " return searchIndexPromise;",
1603
1986
  " }",
1987
+ ...(directReading ? [
1988
+ " /* <lang><zh-CN>已知路由直接加载,未知身份沿既有索引回退。查询期间即取得选择序号,旧成功/失败均不得覆盖新选择。</zh-CN><en>Load known routes directly and retain index fallback for unknown identities. Claim the selection sequence before lookup so stale successes and failures cannot replace newer selections.</en></lang> */",
1989
+ " async function openReadingEntry(entryId, updateHash) {",
1990
+ " const requestSequence = ++readingEntrySequence;",
1991
+ " try {",
1992
+ ...(portalContext.routeHistory ? [
1993
+ " const canonicalEntryId = readingAliases.get(entryId) || entryId;",
1994
+ " const entry = readingEntries.get(canonicalEntryId) || (await ensureSearchIndex()).find(candidate => candidate.id === canonicalEntryId);"
1995
+ ] : [" const entry = readingEntries.get(entryId) || (await ensureSearchIndex()).find(candidate => candidate.id === entryId);"]),
1996
+ " if (requestSequence !== readingEntrySequence) return;",
1997
+ portalContext.routeHistory
1998
+ ? " if (entry) await loadEntry({ ...entry, id: canonicalEntryId, entryId: canonicalEntryId }, updateHash || canonicalEntryId !== entryId);"
1999
+ : " if (entry) await loadEntry({ ...entry, id: entryId, entryId }, updateHash);",
2000
+ " } catch (error) { if (requestSequence === readingEntrySequence) showLoadError(error); }",
2001
+ " }"
2002
+ ] : []),
1604
2003
  " async function runSearch() {",
2004
+ // <lang><zh-CN>清空同样推进序号,迟到的成功/失败均不能覆盖当前目录。</zh-CN><en>Clearing also advances the sequence so late successes and failures cannot overwrite the current directory.</en></lang>
2005
+ " const current = ++searchSequence;",
1605
2006
  " const query = String(search?.value || '').trim().toLowerCase();",
1606
- " if (!query) { renderRoot(); return; }",
2007
+ " if (!query) { contentHost?.querySelector(':scope > [data-hia-search-error]')?.remove(); renderRoot(); return; }",
1607
2008
  " try {",
1608
2009
  " const entries = await ensureSearchIndex();",
2010
+ " if (current !== searchSequence) return;",
2011
+ " contentHost?.querySelector(':scope > [data-hia-search-error]')?.remove();",
1609
2012
  " const matches = entries.filter((entry) => (activeView === 'all' || entry.view === activeView) && String(entry.searchText || '').includes(query)).slice(0, 200);",
1610
2013
  " if (!treeHost) return;",
1611
2014
  " treeHost.innerHTML = '';",
@@ -1619,7 +2022,7 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1619
2022
  " empty.dataset.hiaUiMessage = 'portal.common.nomatches';",
1620
2023
  " empty.textContent = uiMessage('portal.common.nomatches', {}, 'No entries match the current filters.');",
1621
2024
  " treeHost.append(empty);",
1622
- " } catch (error) { showLoadError(error); }",
2025
+ " } catch (error) { if (current === searchSequence) showLoadError(error, true); }",
1623
2026
  " }",
1624
2027
  " for (const button of viewButtons) {",
1625
2028
  " button.addEventListener('click', () => {",
@@ -1629,8 +2032,13 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1629
2032
  " });",
1630
2033
  " }",
1631
2034
  " search?.addEventListener('input', runSearch);",
2035
+ ...(portalContext.siteNavigation ? [
2036
+ " document.addEventListener('hia:site-entry', event => { void openReadingEntry(event.detail, true); });"
2037
+ ] : []),
1632
2038
  " contentLocale?.addEventListener('change', applyContentLocale);",
1633
2039
  " uiLocale?.addEventListener('change', () => applyUiLocale());",
2040
+ // <lang><zh-CN>原生菜单保留无脚本阅读,交互页Escape收起并将焦点返回原summary。</zh-CN><en>Native menus retain script-free reading; Escape on interactive pages closes the menu and returns focus to its own summary.</en></lang>
2041
+ ...(portalContext.siteNavigation ? [" document.querySelector('.hia-site-header')?.addEventListener('keydown', (event) => { if (event.key !== 'Escape') return; const menu = event.target.closest('details[open]'); if (menu) { menu.open = false; menu.querySelector('summary')?.focus(); event.preventDefault(); } });"] : []),
1634
2042
  " document.querySelector('[data-hia-project-relations]')?.addEventListener('click', async () => {",
1635
2043
  " try {",
1636
2044
  " const graph = await readJson(config.relations);",
@@ -1649,15 +2057,35 @@ function renderProjectSplitSiteScript(portalContext, loadingStrategy) {
1649
2057
  " contentHost.append(article);",
1650
2058
  " } catch (error) { showLoadError(error); }",
1651
2059
  " });",
1652
- " readJson(config.navigation).then((shard) => {",
1653
- " rootNodes = Array.isArray(shard.children) ? shard.children : [];",
1654
- " renderRoot();",
1655
- " const hash = location.hash.startsWith('#entry=') ? decodeURIComponent(location.hash.slice(7)) : '';",
1656
- " if (hash) ensureSearchIndex().then((entries) => {",
1657
- " const entry = entries.find((candidate) => candidate.id === hash);",
1658
- " if (entry) loadEntry({ ...entry, entryId: entry.id }, false);",
1659
- " });",
1660
- " }).catch(showLoadError);",
2060
+ // <lang><zh-CN>根目录响应可以晚于用户输入和检索结果,装配后按当前查询重算,保留已选过滤而不覆盖为原目录。</zh-CN><en>The root response may arrive after user input and search results. Reapply the current query after assembly, preserving selected filters instead of overwriting results with the root.</en></lang>
2061
+ ...(directReading ? [
2062
+ " readingNavigation = readJson(config.navigation).then(async shard => {",
2063
+ " rootNodes = Array.isArray(shard.children) ? shard.children : [];",
2064
+ " await runSearch();",
2065
+ " }).catch(showLoadError);",
2066
+ " /* <lang><zh-CN>初始正文独立于目录和检索启动,坏片段仍报告原有错误。</zh-CN><en>Start initial prose independently of directory and search, retaining existing malformed-fragment errors.</en></lang> */",
2067
+ " try { if (location.hash.startsWith('#entry=')) void openReadingEntry(decodeURIComponent(location.hash.slice(7)), false); } catch (error) { showLoadError(error); }"
2068
+ ] : [
2069
+ " readJson(config.navigation).then(async (shard) => {",
2070
+ " rootNodes = Array.isArray(shard.children) ? shard.children : [];",
2071
+ " await runSearch();",
2072
+ " const hash = location.hash.startsWith('#entry=') ? decodeURIComponent(location.hash.slice(7)) : '';",
2073
+ " if (hash) ensureSearchIndex().then((entries) => {",
2074
+ " const entry = entries.find((candidate) => candidate.id === hash);",
2075
+ " if (entry) loadEntry({ ...entry, entryId: entry.id }, false);",
2076
+ " });",
2077
+ " }).catch(showLoadError);",
2078
+ ]),
2079
+ ...(directReading ? [
2080
+ // <lang><zh-CN>同文档深链和历史复用直接路由/兼容回退,并保留请求顺序与原生replaceState行为。</zh-CN><en>Same-document deep links and history reuse direct routes and compatibility fallback, preserving request ordering and native replaceState behavior.</en></lang>
2081
+ " window.addEventListener('hashchange', async () => {",
2082
+ " try {",
2083
+ " if (!location.hash.startsWith('#entry=')) return;",
2084
+ " const hash = decodeURIComponent(location.hash.slice(7));",
2085
+ " await openReadingEntry(hash, false);",
2086
+ " } catch (error) { showLoadError(error); }",
2087
+ " });"
2088
+ ] : []),
1661
2089
  " if (config.ui && uiLocale) {",
1662
2090
  " try {",
1663
2091
  " const saved = localStorage.getItem('hia-doc-portal-ui-locale');",
@@ -1830,7 +2258,10 @@ function renderProjectNavItem(entry) {
1830
2258
  "</li>"
1831
2259
  ].join("");
1832
2260
  }
1833
- /** @lang zh-CN 将项目条目作为完整API参考渲染;本地化正文与单文档复用同一formatter,不将导航摘要当完整正文。 @lang en Renders a project entry as a complete API reference, sharing the document field formatter rather than treating a navigation summary as full prose. */
2261
+ /**
2262
+ * @lang zh-CN 将项目条目作为完整API参考渲染;本地化正文与单文档复用同一formatter,不将导航摘要当完整正文。
2263
+ * @lang en Renders a project entry as a complete API reference, sharing the document field formatter rather than treating a navigation summary as full prose.
2264
+ */
1834
2265
  function renderProjectEntry(entry, locales, selectedLocale) {
1835
2266
  const signature = entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : "";
1836
2267
  const summary = renderProjectEntrySummary(entry, locales, selectedLocale);
@@ -1875,24 +2306,46 @@ function renderProjectSemanticTopicInternal(entry, projectInput, locales, select
1875
2306
  const nextAncestors = new Set(ancestors);
1876
2307
  nextAncestors.add(entry.id);
1877
2308
  const members = collectProjectEntryMembers(entry, projectInput.entries);
2309
+ // <lang><zh-CN>站点采用保留原kind/view数据,用已登记标题呈现徽标,并按确认稿将说明置于徽标之前。</zh-CN><en>Site adoption retains kind/view facts, presenting registered badge labels after the description as confirmed in the design.</en></lang>
2310
+ const kindMessageId = `site.kind.${entry.kind.replaceAll("-", ".")}`;
2311
+ const kindLabel = portalContext.siteNavigation && portalContext.uiLocaleAdoption?.bundles[portalContext.uiLocale][kindMessageId]
2312
+ ? renderProjectUiMessage(portalContext, kindMessageId)
2313
+ : escapeHtml(entry.kind);
2314
+ // <lang><zh-CN>JS领域中的显式TypeScript原源使用真实语言徽标,缺语言时保留既有JavaScript回退。</zh-CN><en>Explicit TypeScript sources in the JS domain use their actual language badge, retaining the existing JavaScript fallback when unspecified.</en></lang>
2315
+ const scriptLanguage = entry.source?.language === "typescript" ? "TypeScript" : "JavaScript";
2316
+ const viewLabel = portalContext.siteNavigation && entry.view === "js" ? scriptLanguage : formatProjectViewLabel(entry.view);
2317
+ const badges = `<span class="hia-kind">${kindLabel}</span><span class="hia-kind">${escapeHtml(viewLabel)}</span>`;
2318
+ const primarySummary = renderProjectEntrySummary(entry, locales, selectedLocale);
2319
+ const additionalFields = renderAdditionalI18nFields(entry, locales, selectedLocale, getPrimaryI18nFieldPath(entry), portalContext, entry.id);
2320
+ const summaryBadges = portalContext.siteNavigation && primarySummary ? `<div class="hia-site-api-meta">${badges}</div>` : "";
2321
+ const headingTag = portalContext.siteNavigation && ancestors.size === 0 ? "h1" : "h2";
2322
+ // <lang><zh-CN>同一来源事实在来源区显示一次,原公开代码保留在提示元数据中,其它诊断继续独立呈现。</zh-CN><en>Show each source fact once in its source section, retain public codes in notice metadata, and present other diagnostics independently.</en></lang>
2323
+ const sourceFeedback = renderProjectSourceAvailabilityFeedback(entry, portalContext);
2324
+ const topicDiagnostics = sourceFeedback ? (entry.diagnostics ?? []).filter(item => !["HIA_CLI_SOURCE_NOT_AUTHORIZED", "HIA_CLI_SOURCE_NOT_FOUND", "HIA_CLI_SOURCE_READ_FAILED", "HIA_CLI_SOURCE_NOT_PROVIDED"].includes(item.code)) : entry.diagnostics ?? [];
1878
2325
  const sections = [
1879
2326
  // <lang><zh-CN>显式IA保留既有section顺序,在正文分区内加入完整字段,避免建立第二条内容降级路径。</zh-CN><en>Explicit IA retains section order while including full fields inside the prose section, avoiding a second content-loss route.</en></lang>
1880
- renderProjectTopicSection("summary", "portal.section.summary", labels.summary, renderProjectEntrySummary(entry, locales, selectedLocale) + renderAdditionalI18nFields(entry, locales, selectedLocale, getPrimaryI18nFieldPath(entry)), portalContext),
2327
+ renderProjectTopicSection("summary", "portal.section.summary", labels.summary, primarySummary + summaryBadges + (portalContext.siteNavigation ? "" : additionalFields), portalContext),
1881
2328
  renderProjectTopicSection("declaration", "portal.section.declaration", labels.declaration, entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : "", portalContext),
2329
+ portalContext.siteNavigation ? additionalFields : "",
1882
2330
  renderProjectTopicSection("metadata", "portal.section.metadata", labels.metadata, renderProjectTopicMetadata(entry, projectInput.project.productVersion, portalContext), portalContext),
1883
2331
  renderProjectTopicSection("contract", "portal.section.contract", labels.contract, renderProjectTopicContract(entry, portalContext), portalContext),
1884
2332
  renderProjectTopicSection("coverage", "portal.section.coverage", labels.coverage, renderProjectTopicCoverage(projectInput.documentationContinuity, projectInput.ownerAdoption, portalContext), portalContext),
1885
2333
  renderProjectTopicSection("provenance", "portal.section.provenance", labels.provenance, renderProjectTopicProvenance(projectInput.documentationContinuity, projectInput.ownerAdoption, portalContext), portalContext),
1886
2334
  renderProjectTopicSection("members", "portal.section.members", labels.members, renderProjectTopicMembers(members, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, nextAncestors), portalContext),
1887
2335
  renderProjectTopicSection("relations", "portal.section.relations", labels.relations, renderProjectTopicRelations(entry, projectInput.relationGraph, portalContext), portalContext),
1888
- renderProjectTopicSection("source", "portal.section.source", labels.source, renderProjectTopicSource(entry, portalContext), portalContext),
1889
- renderProjectTopicSection("diagnostics", "portal.section.diagnostics", labels.diagnostics, renderProjectTopicDiagnostics(entry.diagnostics ?? []), portalContext)
2336
+ renderProjectTopicSection("source", "portal.section.source", labels.source, renderProjectTopicSource(entry, portalContext, sourceFeedback), portalContext),
2337
+ renderProjectTopicSection("diagnostics", "portal.section.diagnostics", labels.diagnostics, renderProjectTopicDiagnostics(topicDiagnostics), portalContext)
1890
2338
  ].join("");
1891
2339
  const searchText = createProjectEntrySearchText(entry);
1892
2340
  return [
1893
2341
  `<article class="hia-symbol hia-project-entry hia-project-topic" id="${escapeHtml(entry.id)}" data-hia-project-entry="${escapeHtml(entry.view)}" data-hia-project-search-text="${escapeHtml(searchText)}">`,
1894
- `<header class="hia-project-topic-header"><h2>${escapeHtml(entry.name)}</h2><span class="hia-kind">${escapeHtml(entry.kind)}</span><span class="hia-kind">${escapeHtml(formatProjectViewLabel(entry.view))}</span></header>`,
1895
- sections,
2342
+ ...(portalContext.siteNavigation ? [
2343
+ `<p class="hia-site-breadcrumbs">${renderProjectUiMessage(portalContext, "site.reading.directory")} / ${escapeHtml(entry.hierarchy?.namespace ?? projectInput.project.title ?? projectInput.project.name)}</p>`,
2344
+ `<p class="hia-site-eyebrow">${renderProjectUiMessage(portalContext, "site.reading.api")} · ${escapeHtml(formatProjectViewLabel(entry.view))}</p>`
2345
+ ] : []),
2346
+ `<header class="hia-project-topic-header"><${headingTag}>${escapeHtml(entry.name)}</${headingTag}>${portalContext.siteNavigation && primarySummary ? "" : badges}</header>`,
2347
+ // <lang><zh-CN>采用站点阅读布局时为实际小节建立逐条目稳定锚点,旧输出精确保留。</zh-CN><en>Create entry-specific stable section anchors for adopted reading layouts, preserving legacy output exactly.</en></lang>
2348
+ portalContext.siteNavigation ? sections.replace(/data-hia-topic-section="([^"]+)"/gu, (_, section) => `id="${escapeHtml(entry.id)}--${section}" tabindex="-1" data-hia-topic-section="${section}"`) : sections,
1896
2349
  "</article>"
1897
2350
  ].join("");
1898
2351
  }
@@ -1901,8 +2354,11 @@ function renderProjectTopicSection(section, messageId, label, body, portalContex
1901
2354
  if (!body) {
1902
2355
  return "";
1903
2356
  }
2357
+ if (portalContext.siteNavigation && ["summary", "declaration", "source"].includes(section)) {
2358
+ return `<section class="hia-project-topic-section" data-hia-topic-section="${section}"><h3>${renderProjectUiMessage(portalContext, messageId, {}, label)}</h3>${body}</section>`;
2359
+ }
1904
2360
  // <lang><zh-CN>首要阅读区默认展开;其余区保持原生 disclosure,可同时打开且不依赖脚本。</zh-CN><en>Primary reading sections start open; remaining sections use native disclosure, allow concurrent expansion, and require no script.</en></lang>
1905
- const open = section === "summary" || section === "declaration" || section === "metadata" ? " open" : "";
2361
+ const open = section === "summary" || section === "declaration" || (section === "metadata" && !portalContext.siteNavigation) ? " open" : "";
1906
2362
  return `<details class="hia-project-topic-section" data-hia-topic-section="${section}"${open}><summary>${renderProjectUiMessage(portalContext, messageId, {}, label)}</summary><div class="hia-project-topic-section-body">${body}</div></details>`;
1907
2363
  }
1908
2364
  /** metadata 只含公开 entry/project facts;关系由 relations section 独立承载。Metadata contains public entry/project facts only; relations stay in their own section. */
@@ -1985,7 +2441,11 @@ function collectProjectEntryMembers(entry, entries) {
1985
2441
  return [];
1986
2442
  }
1987
2443
  return entries
1988
- .filter((candidate) => candidate.hierarchy?.parentSymbolId === entry.symbolId)
2444
+ .filter((candidate) => (candidate.hierarchy?.parentSymbolId === entry.symbolId
2445
+ || Boolean(entry.identityScope && entry.hierarchy?.symbolDocumentationId
2446
+ && candidate.hierarchy?.parentSymbolId === entry.hierarchy.symbolDocumentationId))
2447
+ && candidate.identityScope === entry.identityScope
2448
+ && (!entry.identityScope || candidate.view === entry.view))
1989
2449
  .sort(compareProjectNavigationEntries);
1990
2450
  }
1991
2451
  /** separate 输出 canonical links;with-parent 输出嵌套完整 topic,并对 cycle 回退 link。Separate mode emits canonical links; with-parent emits nested topics with cycle-safe link fallback. */
@@ -2021,9 +2481,17 @@ function renderProjectTopicRelations(entry, relationGraph, portalContext) {
2021
2481
  const items = [...semanticItems, ...graphItems].join("");
2022
2482
  return items ? `<ul class="hia-project-relation-list">${items}</ul>` : "";
2023
2483
  }
2024
- /** source 与 doc-source-map 保持既有 privacy policy;本函数不新增 source body。Source and doc-source-map retain the existing privacy policy; this function adds no source body. */
2025
- function renderProjectTopicSource(entry, portalContext) {
2484
+ /**
2485
+ * @lang zh-CN 来源区组合一次性状态反馈及既有白名单元数据,保持文档正文独立可读。
2486
+ * @lang en The source section combines one availability notice with existing allowlisted metadata while keeping documentation prose independently readable.
2487
+ * @param entry <lang><zh-CN>当前语义条目。</zh-CN><en>Current semantic entry.</en></lang>
2488
+ * @param portalContext <lang><zh-CN>已确认的阅读及双语呈现选择。</zh-CN><en>Confirmed reading and bilingual presentation choices.</en></lang>
2489
+ * @param sourceFeedback <lang><zh-CN>同次渲染已生成的安全反馈HTML。</zh-CN><en>Safe feedback HTML prepared in the same render.</en></lang>
2490
+ * @returns <lang><zh-CN>来源区正文,不进行文件或网络读取。</zh-CN><en>Source-section body without file or network reading.</en></lang>
2491
+ */
2492
+ function renderProjectTopicSource(entry, portalContext, sourceFeedback) {
2026
2493
  return [
2494
+ sourceFeedback,
2027
2495
  entry.source ? renderProjectEntrySource(entry.source, false, portalContext) : "",
2028
2496
  entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability, false, portalContext) : "",
2029
2497
  entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap, false, portalContext) : "",
@@ -2033,11 +2501,33 @@ function renderProjectTopicSource(entry, portalContext) {
2033
2501
  ].join("");
2034
2502
  }
2035
2503
  /**
2036
- * @lang zh-CN
2037
- * 将 source-comment projection 缩减为 navigation allowlist;正文与 producer 的正文授权事实都不进入 index。
2504
+ * @lang zh-CN 将既有CLI公开诊断投影为已确认来源状态,元数据或诊断均不授予读取权限。
2505
+ * @lang en Projects existing CLI public diagnostics onto confirmed source states; metadata and diagnostics grant no read authority.
2506
+ * @param entry <lang><zh-CN>保留文档正文及可选授权资产的条目。</zh-CN><en>Entry retaining prose and optional authorized assets.</en></lang>
2507
+ * @param context <lang><zh-CN>已解析模式和双语界面上下文。</zh-CN><en>Resolved mode and bilingual UI context.</en></lang>
2508
+ * @returns <lang><zh-CN>可读状态提示,存在资产或显式none时为空;未知原因只说明未提供。</zh-CN><en>Readable status notice, empty for existing assets or explicit none; unknown causes report only an absent excerpt.</en></lang>
2509
+ */
2510
+ function renderProjectSourceAvailabilityFeedback(entry, context) {
2511
+ if (context.sourcePresentation === "none" || entry.source?.preview || entry.source?.fetchUrl || entry.source?.linkUrl)
2512
+ return "";
2513
+ // <lang><zh-CN>仅消费固定公开代码,既有诊断正文与附加字段不会进入反馈文案。</zh-CN><en>Consume fixed public codes only; existing diagnostic text and extra fields never enter feedback copy.</en></lang>
2514
+ const known = {
2515
+ HIA_CLI_SOURCE_NOT_AUTHORIZED: ["denied", "portal.source.status.denied", "Source request denied."],
2516
+ HIA_CLI_SOURCE_NOT_FOUND: ["not-found", "portal.source.status.notfound", "Source asset was not found."],
2517
+ HIA_CLI_SOURCE_READ_FAILED: ["network-error", "portal.source.status.network", "Source is temporarily unavailable."],
2518
+ HIA_CLI_SOURCE_NOT_PROVIDED: ["unavailable", "portal.source.status.notprovided", "This entry has no public source excerpt."]
2519
+ };
2520
+ // <lang><zh-CN>有公开原因才区分失败,缺少证据保持未提供;正文入口与普通阅读不受影响。</zh-CN><en>Distinguish failures only with a public reason; missing evidence remains an absent excerpt and ordinary prose stays readable.</en></lang>
2521
+ const diagnostic = entry.diagnostics?.find(item => Object.hasOwn(known, item.code));
2522
+ const [state, messageId, fallback] = diagnostic ? known[diagnostic.code] : ["unavailable", "portal.source.status.notprovided", "This entry has no public source excerpt."];
2523
+ // <lang><zh-CN>公开代码只作为已转义的状态元数据,原诊断消息不重复进入视觉正文。</zh-CN><en>The public code remains escaped status metadata; original diagnostic messages are not repeated in visual prose.</en></lang>
2524
+ const code = diagnostic ? ` data-hia-source-diagnostic="${escapeHtml(diagnostic.code)}"` : "";
2525
+ return `<div data-hia-source-state="${state}"${code}><p class="hia-project-loading" data-hia-source-fetch-status role="status">${renderOptionalProjectUiMessage(context, messageId, fallback)}</p></div>`;
2526
+ }
2527
+ /**
2528
+ * @lang zh-CN 将 source-comment projection 缩减为 navigation allowlist;正文与 producer 的正文授权事实都不进入 index。
2038
2529
  *
2039
- * @lang en
2040
- * Reduces a source-comment projection to a navigation allowlist; neither bodies nor the producer body-authorization fact enters the index.
2530
+ * @lang en Reduces a source-comment projection to a navigation allowlist; neither bodies nor the producer body-authorization fact enters the index.
2041
2531
  */
2042
2532
  function selectProjectSourceCommentProjection(projection) {
2043
2533
  return {
@@ -2058,11 +2548,9 @@ function selectProjectSourceCommentProjection(projection) {
2058
2548
  };
2059
2549
  }
2060
2550
  /**
2061
- * @lang zh-CN
2062
- * 渲染 metadata 与可选纯文本正文。正文必须同时得到 producer projection 与 renderer config 授权。
2551
+ * @lang zh-CN 渲染 metadata 与可选纯文本正文。正文必须同时得到 producer projection 与 renderer config 授权。
2063
2552
  *
2064
- * @lang en
2065
- * Renders metadata and optional plain-text bodies. Bodies require authorization from both the producer projection and renderer config.
2553
+ * @lang en Renders metadata and optional plain-text bodies. Bodies require authorization from both the producer projection and renderer config.
2066
2554
  */
2067
2555
  function renderProjectSourceCommentProjection(projection, options, portalContext) {
2068
2556
  const bodyAuthorized = options.contentPolicy === "explicit-projected-text"
@@ -2117,7 +2605,10 @@ function renderProjectEntryHierarchy(hierarchy) {
2117
2605
  ].join("");
2118
2606
  return details ? `<dl class="hia-project-meta hia-project-hierarchy-meta">${details}</dl>` : "";
2119
2607
  }
2120
- /** @lang zh-CN 仅选择主描述字段,使用原字段身份及共用的locale/fallback规则;不改写i18n模型。 @lang en Selects only the primary prose field with its original identity and shared locale/fallback rules, without rewriting the i18n model. */
2608
+ /**
2609
+ * @lang zh-CN 仅选择主描述字段,使用原字段身份及共用的locale/fallback规则;不改写i18n模型。
2610
+ * @lang en Selects only the primary prose field with its original identity and shared locale/fallback rules, without rewriting the i18n model.
2611
+ */
2121
2612
  function renderProjectEntrySummary(entry, locales, selectedLocale) {
2122
2613
  return renderI18nField(entry, getPrimaryI18nFieldPath(entry), locales, selectedLocale, entry.summary ?? "");
2123
2614
  }
@@ -2545,7 +3036,7 @@ function addProjectSourceRelation(nodes, relations, entry, sourcePath, confidenc
2545
3036
  return;
2546
3037
  }
2547
3038
  const entryNodeId = createProjectEntryRelationNodeId(entry.id);
2548
- const sourceNodeId = createProjectPathRelationNodeId("source", sourcePath);
3039
+ const sourceNodeId = createProjectPathRelationNodeId("source", sourcePath, entry.identityScope);
2549
3040
  addProjectRelationNode(nodes, {
2550
3041
  id: sourceNodeId,
2551
3042
  kind: "source",
@@ -2569,7 +3060,7 @@ function addProjectArtifactRelation(nodes, relations, entry) {
2569
3060
  return;
2570
3061
  }
2571
3062
  const entryNodeId = createProjectEntryRelationNodeId(entry.id);
2572
- const artifactNodeId = createProjectPathRelationNodeId("artifact", entry.docSourceMap.artifactPath);
3063
+ const artifactNodeId = createProjectPathRelationNodeId("artifact", entry.docSourceMap.artifactPath, entry.identityScope);
2573
3064
  addProjectRelationNode(nodes, {
2574
3065
  id: artifactNodeId,
2575
3066
  kind: "artifact",
@@ -2640,8 +3131,10 @@ function inferProjectSourceRelationKind(entry) {
2640
3131
  function createProjectEntryRelationNodeId(entryId) {
2641
3132
  return `entry:${entryId}`;
2642
3133
  }
2643
- function createProjectPathRelationNodeId(kind, path) {
2644
- return `${kind}:${path.replaceAll("\\", "/")}`;
3134
+ function createProjectPathRelationNodeId(kind, path, identityScope) {
3135
+ // <lang><zh-CN>相同相对路径在不同源归属中保持独立关系节点,旧路径身份保留。</zh-CN><en>Equal relative paths retain distinct relation nodes across source scopes while legacy path identities remain unchanged.</en></lang>
3136
+ const normalized = path.replaceAll("\\", "/");
3137
+ return identityScope ? `scoped-${kind}:${JSON.stringify([identityScope, normalized])}` : `${kind}:${normalized}`;
2645
3138
  }
2646
3139
  function createProjectRelationId(kind, from, to) {
2647
3140
  return `${kind}:${from}->${to}`;
@@ -2688,11 +3181,20 @@ function collectProjectNavigationTree(entries, informationArchitecture) {
2688
3181
  }];
2689
3182
  });
2690
3183
  }
3184
+ /**
3185
+ * @lang zh-CN 按程序集、命名空间和文档身份构建.NET树,声明入口的显示名称优先于成员提供的标签。
3186
+ * @lang en Builds a .NET tree by assembly, namespace and documentation identity, preferring declaration labels over member labels.
3187
+ * @param entries <lang><zh-CN>已过滤到.NET视图的条目,不修改其内容。</zh-CN><en>Entries filtered to the .NET view, whose content is not mutated.</en></lang>
3188
+ * @param includeTypeRelations <lang><zh-CN>是否加入既有继承节点,默认true。</zh-CN><en>Whether to include existing inheritance nodes, defaulting to true.</en></lang>
3189
+ * @returns <lang><zh-CN>排序后的新导航树。</zh-CN><en>A new sorted navigation tree.</en></lang>
3190
+ */
2691
3191
  function collectDotNetNavigationTree(entries, includeTypeRelations = true) {
2692
3192
  const roots = new Map();
2693
3193
  for (const entry of entries) {
2694
3194
  const parts = getDotNetNavigationParts(entry);
2695
- const assemblyNode = getOrCreateProjectTreeChild(roots, `dotnet:${parts.rootKind}:${slugProjectGroupLabel(parts.assemblyLabel)}`, parts.rootKind, parts.assemblyLabel);
3195
+ const assemblyNode = getOrCreateProjectTreeChild(roots, entry.identityScope
3196
+ ? `scoped-dotnet:${JSON.stringify([entry.identityScope, parts.rootKind, parts.assemblyLabel])}`
3197
+ : `dotnet:${parts.rootKind}:${slugProjectGroupLabel(parts.assemblyLabel)}`, parts.rootKind, parts.assemblyLabel);
2696
3198
  addProjectTreeEntry(assemblyNode, entry);
2697
3199
  let namespaceParent = assemblyNode;
2698
3200
  const namespaceSegments = parts.namespaceLabel === "(global namespace)"
@@ -2712,6 +3214,8 @@ function collectDotNetNavigationTree(entries, includeTypeRelations = true) {
2712
3214
  namespaceParent.children = [...namespaceParent.childrenById.values()];
2713
3215
  addProjectTreeEntry(typeNode, entry);
2714
3216
  if (isDotNetTypeNavigationEntry(entry)) {
3217
+ // <lang><zh-CN>成员可能先到;声明到达时同步标签与声明入口,消除输入顺序带来的显示差异。</zh-CN><en>A member may arrive first; synchronize the label with the declaration entry when it arrives.</en></lang>
3218
+ typeNode.label = parts.typeLabel;
2715
3219
  typeNode.entryId = entry.id;
2716
3220
  assignProjectTreeEntryRefs(typeNode, entry);
2717
3221
  if (includeTypeRelations && entry.kind === "dotnet-type") {
@@ -2780,7 +3284,11 @@ function collectSymbolContainmentNavigationTree(entries) {
2780
3284
  const entriesBySymbolId = new Map();
2781
3285
  for (const entry of entries) {
2782
3286
  if (entry.symbolId) {
2783
- entriesBySymbolId.set(entry.symbolId, entry);
3287
+ entriesBySymbolId.set(projectSymbolLookupKey(entry, entry.symbolId), entry);
3288
+ // <lang><zh-CN>新作用域同时登记.NET显式文档身份,成员的原始父ID保持不改写。</zh-CN><en>Also index explicit .NET documentation identities in new scopes without rewriting native parent IDs.</en></lang>
3289
+ if (entry.identityScope && entry.hierarchy?.symbolDocumentationId) {
3290
+ entriesBySymbolId.set(projectSymbolLookupKey(entry, entry.hierarchy.symbolDocumentationId), entry);
3291
+ }
2784
3292
  }
2785
3293
  const entryNode = getOrCreateProjectTreeChild(nodesByEntryId, `entry:${entry.id}`, isProjectTypeLikeKind(entry.kind) ? "type" : "entry", entry.name);
2786
3294
  addProjectTreeEntry(entryNode, entry);
@@ -2790,7 +3298,7 @@ function collectSymbolContainmentNavigationTree(entries) {
2790
3298
  for (const entry of entries) {
2791
3299
  const entryNode = nodesByEntryId.get(`entry:${entry.id}`);
2792
3300
  const parentEntry = entry.hierarchy?.parentSymbolId
2793
- ? entriesBySymbolId.get(entry.hierarchy.parentSymbolId)
3301
+ ? entriesBySymbolId.get(projectSymbolLookupKey(entry, entry.hierarchy.parentSymbolId))
2794
3302
  : undefined;
2795
3303
  const parentNode = parentEntry ? nodesByEntryId.get(`entry:${parentEntry.id}`) : undefined;
2796
3304
  if (entryNode && parentEntry && parentNode && parentNode !== entryNode) {
@@ -2868,7 +3376,11 @@ function collectSemanticSourceNavigationTree(entries) {
2868
3376
  const fileNodesByEntryId = new Map();
2869
3377
  for (const entry of entries) {
2870
3378
  if (entry.symbolId) {
2871
- entriesBySymbolId.set(entry.symbolId, entry);
3379
+ entriesBySymbolId.set(projectSymbolLookupKey(entry, entry.symbolId), entry);
3380
+ // <lang><zh-CN>新作用域同时登记.NET显式文档身份,成员的原始父ID保持不改写。</zh-CN><en>Also index explicit .NET documentation identities in new scopes without rewriting native parent IDs.</en></lang>
3381
+ if (entry.identityScope && entry.hierarchy?.symbolDocumentationId) {
3382
+ entriesBySymbolId.set(projectSymbolLookupKey(entry, entry.hierarchy.symbolDocumentationId), entry);
3383
+ }
2872
3384
  }
2873
3385
  const entryNode = getOrCreateProjectTreeChild(nodesByEntryId, `entry:${entry.id}`, isProjectTypeLikeKind(entry.kind) ? "type" : "entry", entry.name);
2874
3386
  addProjectTreeEntry(entryNode, entry);
@@ -2876,7 +3388,9 @@ function collectSemanticSourceNavigationTree(entries) {
2876
3388
  assignProjectTreeEntryRefs(entryNode, entry);
2877
3389
  const sourceRootLabel = getProjectSourceRoot(entry.source?.path);
2878
3390
  const sourcePathLabel = entry.source?.path?.replaceAll("\\", "/") || "unknown-source";
2879
- const rootNode = getOrCreateProjectTreeChild(roots, `source-root:${slugProjectGroupLabel(sourceRootLabel)}`, "source-root", sourceRootLabel);
3391
+ const rootNode = getOrCreateProjectTreeChild(roots, entry.identityScope
3392
+ ? `scoped-source-root:${JSON.stringify([entry.identityScope, sourceRootLabel])}`
3393
+ : `source-root:${slugProjectGroupLabel(sourceRootLabel)}`, "source-root", sourceRootLabel);
2880
3394
  addProjectTreeEntry(rootNode, entry);
2881
3395
  const fileNode = getOrCreateProjectTreeChild(rootNode.childrenById, `${rootNode.id}:source-file:${slugProjectGroupLabel(sourcePathLabel)}`, "source-file", sourcePathLabel);
2882
3396
  rootNode.children = [...rootNode.childrenById.values()];
@@ -2887,7 +3401,7 @@ function collectSemanticSourceNavigationTree(entries) {
2887
3401
  for (const entry of entries) {
2888
3402
  const entryNode = nodesByEntryId.get(`entry:${entry.id}`);
2889
3403
  const parentEntry = entry.hierarchy?.parentSymbolId
2890
- ? entriesBySymbolId.get(entry.hierarchy.parentSymbolId)
3404
+ ? entriesBySymbolId.get(projectSymbolLookupKey(entry, entry.hierarchy.parentSymbolId))
2891
3405
  : undefined;
2892
3406
  const parentNode = parentEntry
2893
3407
  ? nodesByEntryId.get(`entry:${parentEntry.id}`)
@@ -2915,7 +3429,7 @@ function incrementProjectNavigationAncestorCounts(parentEntry, entriesBySymbolId
2915
3429
  node.entryCount += 1;
2916
3430
  }
2917
3431
  current = current.hierarchy?.parentSymbolId
2918
- ? entriesBySymbolId.get(current.hierarchy.parentSymbolId)
3432
+ ? entriesBySymbolId.get(projectSymbolLookupKey(current, current.hierarchy.parentSymbolId))
2919
3433
  : undefined;
2920
3434
  }
2921
3435
  }
@@ -3021,14 +3535,31 @@ function projectTreeKindOrder(kind) {
3021
3535
  }
3022
3536
  return 12;
3023
3537
  }
3538
+ /**
3539
+ * @lang zh-CN 复用文档ID和父类型ID分组,仅将语义显示文本用于标签;旧输入保留既有回退。
3540
+ * @lang en Groups by documentation and parent-type IDs, using semantic display text only for labels while retaining legacy fallbacks.
3541
+ * @param entry <lang><zh-CN>包含可选语义字段的.NET条目。</zh-CN><en>A .NET entry with optional semantic fields.</en></lang>
3542
+ * @returns <lang><zh-CN>分组身份与独立显示标签,不修改条目。</zh-CN><en>Grouping identities and separate display labels without entry mutation.</en></lang>
3543
+ */
3024
3544
  function getDotNetNavigationParts(entry) {
3545
+ // <lang><zh-CN>领域根分类和程序集沿用旧输入规则,缺语义数据时继续可读。</zh-CN><en>Retain domain-root and assembly classification so inputs without semantic metadata remain readable.</en></lang>
3025
3546
  const fallback = getDotNetNonAssemblyNavigationParts(entry);
3026
3547
  const assemblyLabel = entry.hierarchy?.assembly || fallback.assemblyLabel;
3027
3548
  const semanticNamespace = entry.hierarchy?.namespace;
3028
3549
  const semanticContainingType = entry.hierarchy?.containingType;
3550
+ // <lang><zh-CN>文档ID包含泛型参数数量,不能与C#显示名称互换。</zh-CN><en>Documentation IDs encode generic arity and cannot be replaced with C# display names.</en></lang>
3029
3551
  const symbolId = entry.hierarchy?.symbolDocumentationId
3030
3552
  || (entry.symbolId?.match(/^[A-Z]:/) ? entry.symbolId : "")
3031
3553
  || (entry.id.match(/^[A-Z]:/) ? entry.id : "");
3554
+ const typeDocumentationId = entry.kind === "dotnet-type" ? symbolId : entry.hierarchy?.parentSymbolId;
3555
+ const canonicalTypeId = typeDocumentationId?.startsWith("T:") ? typeDocumentationId : undefined;
3556
+ // <lang><zh-CN>只移除已明确提供的命名空间前缀,保留泛型实参中的点和嵌套类型显示文本。</zh-CN><en>Remove only the supplied namespace prefix, retaining dots in generic arguments and nested type display text.</en></lang>
3557
+ const semanticTypeName = entry.kind === "dotnet-type" ? entry.hierarchy?.displayName : semanticContainingType;
3558
+ const namespacePrefix = semanticNamespace ? `${semanticNamespace}.` : "";
3559
+ const semanticTypeLabel = namespacePrefix && semanticTypeName?.startsWith(namespacePrefix)
3560
+ ? semanticTypeName.slice(namespacePrefix.length)
3561
+ : semanticTypeName;
3562
+ // <lang><zh-CN>既有文档ID拆分只作无父ID时的类型身份和旧标签回退,不解析显示文本中的C#语法。</zh-CN><en>Use existing documentation-ID splitting for owner identity and legacy labels when parent IDs are absent, without parsing display syntax.</en></lang>
3032
3563
  const symbolBody = symbolId.match(/^[A-Z]:/) ? symbolId.slice(2) : "";
3033
3564
  const normalizedSymbol = symbolBody.replace(/\(.+$/, "");
3034
3565
  const segments = normalizedSymbol.split(".").filter((segment) => segment.length > 0);
@@ -3042,8 +3573,8 @@ function getDotNetNavigationParts(entry) {
3042
3573
  memberLabel,
3043
3574
  namespaceLabel: semanticNamespace || namespaceLabel,
3044
3575
  rootKind: entry.hierarchy?.assembly ? "assembly" : fallback.rootKind,
3045
- typeId: semanticContainingType ? `T:${semanticContainingType}` : `T:${segments.slice(0, typeIndex + 1).join(".")}`,
3046
- typeLabel: semanticContainingType?.split(".").pop() || typeLabel
3576
+ typeId: canonicalTypeId || `T:${segments.slice(0, typeIndex + 1).join(".")}`,
3577
+ typeLabel: semanticTypeLabel || typeLabel
3047
3578
  };
3048
3579
  }
3049
3580
  const sourceStem = entry.source?.path
@@ -3054,8 +3585,8 @@ function getDotNetNavigationParts(entry) {
3054
3585
  memberLabel: entry.name,
3055
3586
  namespaceLabel: semanticNamespace || fallback.namespaceLabel,
3056
3587
  rootKind: entry.hierarchy?.assembly ? "assembly" : fallback.rootKind,
3057
- typeId: semanticContainingType ? `T:${semanticContainingType}` : symbolId || entry.id,
3058
- typeLabel: semanticContainingType?.split(".").pop() || sourceStem || entry.name
3588
+ typeId: canonicalTypeId || (semanticContainingType ? `T:${semanticContainingType}` : symbolId || entry.id),
3589
+ typeLabel: semanticTypeLabel || sourceStem || entry.name
3059
3590
  };
3060
3591
  }
3061
3592
  function getDotNetNonAssemblyNavigationParts(entry) {
@@ -3200,6 +3731,8 @@ function createProjectEntrySearchText(entry) {
3200
3731
  entry.docSourceMap?.sourcePath,
3201
3732
  entry.docSourceMap?.artifactPath,
3202
3733
  entry.docSourceMap?.artifactSelector,
3734
+ // <lang><zh-CN>已审语义标签参与同一检索,包名与默认导出别名可找到原规范页面。</zh-CN><en>Reviewed semantic labels participate in the same search so package names and default-export aliases locate the original canonical page.</en></lang>
3735
+ ...(entry.semanticPath?.map(segment => segment.label) ?? []),
3203
3736
  ...collectProjectEntryLocalizedText(entry)
3204
3737
  ].filter((item) => typeof item === "string" && item.length > 0).join(" ").toLowerCase();
3205
3738
  }
@@ -3249,7 +3782,7 @@ function renderSymbol(symbol, document, locales, selectedLocale) {
3249
3782
  const signature = symbol.signature ? `<pre class="hia-signature"><code>${escapeHtml(symbol.signature)}</code></pre>` : "";
3250
3783
  // <lang><zh-CN>纯.NET summary与description共用主字段选择,主字段只呈现一次,附加字段全部保留。</zh-CN><en>.NET summary and description share primary-field selection, showing the primary once and retaining every additional field.</en></lang>
3251
3784
  const primaryPath = getPrimaryI18nFieldPath(symbol);
3252
- const description = renderI18nField(symbol, primaryPath, locales, selectedLocale, symbol.summary);
3785
+ const description = renderI18nField(symbol, primaryPath, locales, selectedLocale, symbol.summary, document.defaultLocale);
3253
3786
  const otherFields = renderAdditionalI18nFields(symbol, locales, selectedLocale, primaryPath);
3254
3787
  const source = renderSource(symbol);
3255
3788
  return [
@@ -3263,47 +3796,177 @@ function renderSymbol(symbol, document, locales, selectedLocale) {
3263
3796
  "</article>"
3264
3797
  ].join("");
3265
3798
  }
3266
- /** @lang zh-CN description优先,其次summary,无模型时仍用description承载普通摘要回退。 @lang en Prefers description, then summary, retaining description for plain-summary fallback without a model. */
3799
+ /**
3800
+ * @lang zh-CN description优先,其次summary,无模型时仍用description承载普通摘要回退。
3801
+ * @lang en Prefers description, then summary, retaining description for plain-summary fallback without a model.
3802
+ */
3267
3803
  function getPrimaryI18nFieldPath(owner) {
3268
3804
  return owner.i18n?.fields.description ? "description" : owner.i18n?.fields.summary ? "summary" : "description";
3269
3805
  }
3270
- /** @lang zh-CN 按原顺序遍历所有附加字段;不按.NET字段清单过滤,不修改输入或把字段文本当HTML。 @lang en Iterates all additional fields in input order without a .NET whitelist, input mutation, or interpreting field text as HTML. */
3271
- function renderAdditionalI18nFields(symbol, locales, selectedLocale, primaryPath = "description") {
3806
+ /**
3807
+ * @lang zh-CN 完整呈现主字段之外的本地化正文;已采用Portal使用其独立UI语言,旧调用保留原标题。
3808
+ * @lang en Renders all localized prose beyond the primary field, using the adopted Portal's independent UI language while retaining the legacy heading for other callers.
3809
+ * @lang zh-CN 附加字段完整保留,具名字段按首次出现位置归组;不修改输入或把字段文本当HTML。
3810
+ * @lang en Retains every additional field, grouping named fields at their first position without input mutation or interpreting field text as HTML.
3811
+ * @param symbol <lang><zh-CN>字段所有者,仅读取不修改。</zh-CN><en>Read-only field owner.</en></lang>
3812
+ * @param locales <lang><zh-CN>实际正文语言集合。</zh-CN><en>Actual content locales.</en></lang>
3813
+ * @param selectedLocale <lang><zh-CN>当前可见正文语言。</zh-CN><en>Currently visible content locale.</en></lang>
3814
+ * @param primaryPath <lang><zh-CN>已显示的主字段,默认description。</zh-CN><en>Already displayed primary field, defaulting to description.</en></lang>
3815
+ * @param portalContext <lang><zh-CN>可选已采用Portal上下文,用于标题及切换标记。</zh-CN><en>Optional adopted Portal context for the heading and switching marker.</en></lang>
3816
+ * @param ownerId <lang><zh-CN>原条目身份,用于稳定字段锚点,默认entry。</zh-CN><en>Original entry identity for stable field anchors, defaulting to entry.</en></lang>
3817
+ * @returns <lang><zh-CN>完整附加字段HTML,没有可见字段则为空。</zh-CN><en>Complete additional-field HTML, or an empty string without renderable fields.</en></lang>
3818
+ */
3819
+ function renderAdditionalI18nFields(symbol, locales, selectedLocale, primaryPath = "description", portalContext, ownerId = "entry") {
3272
3820
  const fields = symbol.i18n?.fields || {};
3273
3821
  // <lang><zh-CN>只移除已显示的主字段,允许summary与description同时完整显示。</zh-CN><en>Remove only the already-rendered primary field, allowing summary and description to coexist completely.</en></lang>
3274
3822
  const fieldEntries = Object.entries(fields).filter(([fieldPath]) => fieldPath !== primaryPath);
3275
3823
  if (fieldEntries.length === 0) {
3276
3824
  return "";
3277
3825
  }
3826
+ // <lang><zh-CN>具名参数按首次出现位置归组为确认稿的名称/说明表;原字段锚点与双语容器仍逐项保留。</zh-CN><en>Group named parameters at their first occurrence into the confirmed name/description tables, retaining each original field anchor and bilingual container.</en></lang>
3827
+ const namedGroups = new Map();
3828
+ /**
3829
+ * @lang zh-CN 识别已有生产器的具名说明字段,保留名称,不推断参数类型或值。
3830
+ * @lang en Recognizes existing producer named-description fields, preserving names without inferring parameter types or values.
3831
+ */
3832
+ const namedCategory = (fieldPath) => {
3833
+ const match = /^(params|parameters|typeParams|typeParameters|exceptions)\.(.+)\.(?:summary|description)$/u.exec(fieldPath);
3834
+ return match ? { category: match[1] === "params" ? "parameters" : match[1].toLowerCase().replace("typeparams", "typeparameters"), name: match[2] } : undefined;
3835
+ };
3836
+ if (portalContext?.siteNavigation) {
3837
+ for (const [fieldPath] of fieldEntries) {
3838
+ const named = namedCategory(fieldPath);
3839
+ if (named) {
3840
+ let group = namedGroups.get(named.category);
3841
+ if (!group) {
3842
+ group = [];
3843
+ namedGroups.set(named.category, group);
3844
+ }
3845
+ group.push({ fieldPath, name: named.name });
3846
+ }
3847
+ }
3848
+ }
3849
+ const emittedGroups = new Set();
3278
3850
  const items = fieldEntries
3279
3851
  .map(([fieldPath]) => {
3280
3852
  const renderedField = renderI18nField(symbol, fieldPath, locales, selectedLocale);
3853
+ if (renderedField && portalContext?.siteNavigation) {
3854
+ const group = namedCategory(fieldPath);
3855
+ if (group) {
3856
+ if (emittedGroups.has(group.category))
3857
+ return "";
3858
+ emittedGroups.add(group.category);
3859
+ const rows = namedGroups.get(group.category).map(field => {
3860
+ const body = renderI18nField(symbol, field.fieldPath, locales, selectedLocale);
3861
+ const anchor = `${ownerId}--field-${stableProjectArtifactName(field.fieldPath)}`;
3862
+ return body ? `<tr id="${escapeHtml(anchor)}" tabindex="-1"><td><code>${escapeHtml(field.name)}</code></td><td>${body}</td></tr>` : "";
3863
+ }).join("");
3864
+ const title = renderProjectUiMessage(portalContext, `site.field.${group.category}`);
3865
+ return `<section class="hia-site-field" id="${escapeHtml(ownerId)}--fields-${group.category}" tabindex="-1" data-hia-reading-section="${group.category}"><h3>${title}</h3><table class="hia-site-field-table"><thead><tr><th scope="col">${renderProjectUiMessage(portalContext, "site.field.name")}</th><th scope="col">${renderProjectUiMessage(portalContext, "site.field.description")}</th></tr></thead><tbody>${rows}</tbody></table></section>`;
3866
+ }
3867
+ // <lang><zh-CN>标准API字段用已登记的双语标题;名称和原字段身份仍保留,扩展字段继续完整可读。</zh-CN><en>Use registered bilingual headings for standard API fields, retaining names and original field identities while preserving extension fields.</en></lang>
3868
+ // <lang><zh-CN>复用各生产器已存在的字段别名,只改变阅读标题,不迁移原工件身份。</zh-CN><en>Reuse existing producer field aliases for headings without migrating artifact identities.</en></lang>
3869
+ const category = /^returns(?:\.(?:summary|description)|\.\d+\.(?:summary|description))?$/u.test(fieldPath) ? "returns" : /^throws\.\d+$/u.test(fieldPath) ? "exceptions" : fieldPath.toLowerCase();
3870
+ const known = ["remarks", "parameters", "typeparameters", "returns", "exceptions"].includes(category);
3871
+ // <lang><zh-CN>命令契约字段保留原身份和锚点,只把已知标题映射为正式双语消息;扩展字段继续显示原名。</zh-CN><en>Keep command field identities and anchors while mapping known headings to formal bilingual messages, retaining original names for extensions.</en></lang>
3872
+ const commandMessage = ["command", "command-group", "command-option", "command-argument"].includes(symbol.kind ?? "") ? commandFieldMessage(fieldPath) : undefined;
3873
+ const title = commandMessage ? renderProjectUiMessage(portalContext, commandMessage) : known ? renderProjectUiMessage(portalContext, `site.field.${category}`) : `<code>${escapeHtml(fieldPath)}</code>`;
3874
+ const anchor = `${ownerId}--field-${stableProjectArtifactName(fieldPath)}`;
3875
+ return `<section class="hia-site-field" id="${escapeHtml(anchor)}" tabindex="-1" data-hia-reading-section="${escapeHtml(fieldPath)}"><h3>${title}</h3>${renderedField}</section>`;
3876
+ }
3281
3877
  return renderedField
3282
3878
  ? `<div class="hia-i18n-field"><dt>${escapeHtml(fieldPath)}</dt><dd>${renderedField}</dd></div>`
3283
3879
  : "";
3284
3880
  })
3285
3881
  .join("");
3286
- return items ? `<section class="hia-i18n-fields"><h3>Localized Fields</h3><dl>${items}</dl></section>` : "";
3882
+ return items ? portalContext?.siteNavigation ? items : `<section class="hia-i18n-fields"><h3>${renderOptionalProjectUiMessage(portalContext, "portal.section.localizedfields", "Localized Fields")}</h3><dl>${items}</dl></section>` : "";
3883
+ }
3884
+ /**
3885
+ * @lang zh-CN 命令字段的固定标题别名表,只初始化一次,消息身份由同包双语目录类型约束。
3886
+ * @lang en Fixed heading aliases for command fields, initialized once and constrained by the same package's bilingual catalog type.
3887
+ */
3888
+ const COMMAND_FIELD_MESSAGE_IDS = Object.freeze({
3889
+ summary: "site.field.command.summary",
3890
+ indexlabel: "site.field.command.purpose",
3891
+ paths: "site.field.command.paths",
3892
+ effects: "site.field.command.effects",
3893
+ writes: "site.field.command.effects",
3894
+ offline: "site.field.command.offline",
3895
+ parsing: "site.field.command.parsing",
3896
+ parsingrules: "site.field.command.parsing",
3897
+ configusage: "site.field.command.configusage",
3898
+ configoverrides: "site.field.command.configoverrides",
3899
+ directonly: "site.field.command.directonly",
3900
+ versionidentity: "site.field.command.versionidentity",
3901
+ defaults: "site.field.command.defaults",
3902
+ metavar: "site.field.command.metavar",
3903
+ aliases: "site.field.command.aliases",
3904
+ prerequisites: "site.field.command.prerequisites",
3905
+ section: "site.field.command.section",
3906
+ "command.owner.packagename": "site.field.command.package",
3907
+ "command.owner.packageversion": "site.field.command.packageversion",
3908
+ "command.displayversion.kind": "site.field.command.versionidentity",
3909
+ "command.displayversion.value": "site.field.command.displayversion",
3910
+ "command.aliasof": "site.field.command.aliases",
3911
+ "command.parsing.helporder": "site.field.command.helporder",
3912
+ "command.parsing.unknownoptions": "site.field.command.unknownoptions",
3913
+ "command.effects.filesystem": "site.field.command.filesystem",
3914
+ "command.effects.network": "site.field.command.network",
3915
+ "command.examples.*": "site.field.command.examples",
3916
+ "command.exitcodes.*.code": "site.field.command.exitcode",
3917
+ "command.exitcodes.*.summary": "site.field.command.exitsummary",
3918
+ "command.exitcodes.*.description": "site.field.command.exitdescription",
3919
+ "parameter.choices.*": "site.field.command.choices",
3920
+ "parameter.defaultrule.conditions.*": "site.field.command.defaultconditions",
3921
+ "parameter.defaultrule.kind": "site.field.command.defaultkind",
3922
+ "parameter.defaultrule.value": "site.field.command.defaultvalue",
3923
+ "parameter.multiple": "site.field.command.multiple",
3924
+ "parameter.name": "site.field.command.parametername",
3925
+ "parameter.required": "site.field.command.required",
3926
+ "parameter.short": "site.field.command.short",
3927
+ "parameter.valuetype": "site.field.command.valuetype"
3928
+ });
3929
+ /**
3930
+ * @lang zh-CN 对已知命令字段选择完整阅读标题,编号槽位只影响身份,未知字段不猜语义。
3931
+ * @lang en Select complete reading headings for known command fields, retaining numbered identities and avoiding inferred meanings for unknown fields.
3932
+ * @param fieldPath - 原生或网页投影的精确字段路径。Exact native or web-projection field path.
3933
+ * @returns 正式消息身份,未知字段为undefined。Formal message identity, or undefined for unknown fields.
3934
+ */
3935
+ function commandFieldMessage(fieldPath) {
3936
+ // <lang><zh-CN>只归一化数值数组下标用于固定表查找,原路径继续用于字段内容和链接。</zh-CN><en>Normalize numeric array indices only for fixed-table lookup, retaining original paths for field content and links.</en></lang>
3937
+ const key = fieldPath.toLowerCase().replace(/\.\d+(?=\.|$)/gu, ".*");
3938
+ return Object.hasOwn(COMMAND_FIELD_MESSAGE_IDS, key) ? COMMAND_FIELD_MESSAGE_IDS[key] : undefined;
3287
3939
  }
3288
- /** @lang zh-CN 渲染每个locale的纯文本与明确fallback;所有locale均无正文时省略空字段。 @lang en Renders plain text and explicit fallback per locale, omitting fields with no prose in any locale. */
3289
- function renderI18nField(symbol, fieldPath, locales, selectedLocale, fallbackText = "") {
3940
+ /**
3941
+ * @lang zh-CN 渲染各请求语言的纯文本和回退,lang取实际来源;裸摘要只采用模型或原文档明确声明,未知时不猜测。
3942
+ * @lang en Renders prose and fallback for requested locales with lang from the actual source; bare summaries use only model or document declarations, never guesses for unknown provenance.
3943
+ */
3944
+ function renderI18nField(symbol, fieldPath, locales, selectedLocale, fallbackText = "", fallbackLocale) {
3290
3945
  const field = getI18nField(symbol.i18n, fieldPath);
3291
3946
  if (!field && !fallbackText) {
3292
3947
  return "";
3293
3948
  }
3294
3949
  // <lang><zh-CN>缺译不等于空字段:先用现有解析规则核全部locale,保留任何可解析正文。</zh-CN><en>A missing translation is not an empty field: use existing resolution rules across all locales and retain any resolvable prose.</en></lang>
3295
3950
  const resolveOptions = createI18nResolveOptions(symbol);
3951
+ // <lang><zh-CN>仅单文档调用可补其声明;混合项目不能用整站选择语言替代各来源。</zh-CN><en>Only document calls supply their declaration; mixed projects cannot substitute site selection for individual sources.</en></lang>
3952
+ const sourceLocale = symbol.i18n?.defaultLocale || fallbackLocale;
3296
3953
  if (field && !fallbackText && !locales.some((locale) => resolveI18nFieldText(field, locale, resolveOptions).text.length > 0))
3297
3954
  return "";
3298
3955
  const blocks = locales
3299
- .map((locale) => renderLocalizedBlock(field, locale, selectedLocale, resolveOptions, fallbackText))
3956
+ .map((locale) => renderLocalizedBlock(field, locale, selectedLocale, resolveOptions, fallbackText, sourceLocale))
3300
3957
  .join("");
3301
3958
  return `<div class="hia-localized-set" data-hia-i18n-field="${escapeHtml(fieldPath)}">${blocks}</div>`;
3302
3959
  }
3303
- function renderLocalizedBlock(field, locale, selectedLocale, options, fallbackText) {
3960
+ /**
3961
+ * @lang zh-CN 保留请求语言容器的选择行为,按实际解析语言标正文,未知语言显式阻断祖先继承。
3962
+ * @lang en Preserves requested-locale selection while marking actual prose language, explicitly preventing ancestor-language inheritance when unknown.
3963
+ */
3964
+ function renderLocalizedBlock(field, locale, selectedLocale, options, fallbackText, sourceLocale) {
3965
+ // <lang><zh-CN>字段用既有回退链,裸摘要只用已声明来源,二者均不依赖初始选择推断原文。</zh-CN><en>Fields use existing fallback chains and bare summaries use declared provenance; neither infers source language from initial selection.</en></lang>
3304
3966
  const resolved = field
3305
3967
  ? resolveI18nFieldText(field, locale, options)
3306
- : createFallbackResolvedText(locale, selectedLocale, fallbackText);
3968
+ : createFallbackResolvedText(locale, sourceLocale, fallbackText);
3969
+ // <lang><zh-CN>显隐仍由请求语言控制;语义lang单独取实际解析结果,避免切换后误标。</zh-CN><en>Requested locale still controls visibility; semantic lang independently follows resolution to avoid mislabeling after switching.</en></lang>
3307
3970
  const hidden = locale === selectedLocale ? "" : " hidden";
3308
3971
  const fallbackAttrs = resolved.usedFallback
3309
3972
  ? ` data-hia-used-fallback="true" data-hia-fallback-from="${escapeHtml(resolved.resolvedLocale)}"`
@@ -3312,18 +3975,22 @@ function renderLocalizedBlock(field, locale, selectedLocale, options, fallbackTe
3312
3975
  ? `<span class="hia-fallback-badge">fallback: ${escapeHtml(resolved.resolvedLocale)}</span>`
3313
3976
  : "";
3314
3977
  return [
3315
- `<p class="hia-localized-text" data-hia-locale="${escapeHtml(locale)}" lang="${escapeHtml(locale)}"${fallbackAttrs}${hidden}>`,
3978
+ `<p class="hia-localized-text" data-hia-locale="${escapeHtml(locale)}" lang="${escapeHtml(resolved.resolvedLocale)}"${fallbackAttrs}${hidden}>`,
3316
3979
  escapeHtml(resolved.text),
3317
3980
  fallbackBadge,
3318
3981
  "</p>"
3319
3982
  ].join("");
3320
3983
  }
3321
- function createFallbackResolvedText(locale, selectedLocale, text) {
3984
+ /**
3985
+ * @lang zh-CN 裸摘要只保留已声明原文语言;未知来源不制造回退身份,正文仍逐请求语言可读。
3986
+ * @lang en Bare summaries retain only declared source language; unknown provenance creates no fallback identity while prose stays readable for every request.
3987
+ */
3988
+ function createFallbackResolvedText(locale, sourceLocale, text) {
3322
3989
  return {
3323
3990
  requestedLocale: locale,
3324
- resolvedLocale: selectedLocale,
3325
- fallbackChain: [locale, selectedLocale],
3326
- usedFallback: locale !== selectedLocale,
3991
+ resolvedLocale: sourceLocale ?? "",
3992
+ fallbackChain: [...new Set([locale, ...(sourceLocale ? [sourceLocale] : [])])],
3993
+ usedFallback: Boolean(text && sourceLocale && locale !== sourceLocale),
3327
3994
  missing: !text,
3328
3995
  text
3329
3996
  };
@@ -3448,7 +4115,10 @@ function resolveProjectLocaleModel(projectInput, requestedLocale) {
3448
4115
  }
3449
4116
  return { selectedLocale, locales };
3450
4117
  }
3451
- /** @lang zh-CN 从不修改的i18n owner读取默认/fallback语言,保持各渲染路径一致。 @lang en Reads default/fallback locales from an unmodified i18n owner consistently across rendering routes. */
4118
+ /**
4119
+ * @lang zh-CN 从不修改的i18n owner读取默认/fallback语言,保持各渲染路径一致。
4120
+ * @lang en Reads default/fallback locales from an unmodified i18n owner consistently across rendering routes.
4121
+ */
3452
4122
  function createI18nResolveOptions(symbol) {
3453
4123
  return createI18nResolveOptionsFromModel(symbol.i18n);
3454
4124
  }