@hia-doc/renderer-html 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { getI18nField, resolveI18nFieldText } from "@hia-doc/core";
1
+ import { canonicalizeDocumentationLocale, getI18nField, resolveI18nFieldText, validateDocumentationSourceCommentProjection } from "@hia-doc/core";
2
2
  import { DEFAULT_THEME_CSS_PATH, DEFAULT_THEME_JS_PATH, getDefaultThemeAssets } from "@hia-doc/theme-default";
3
+ import { DOCUMENTATION_PORTAL_SEMANTIC_PATH_KINDS, getDocumentationPortalLabels, resolveDocumentationPortalInformationArchitecture, resolveDocumentationPortalUiLocale } from "./information-architecture.js";
4
+ export * from "./information-architecture.js";
3
5
  export const HIA_RENDER_HTML_MANIFEST_SCHEMA_VERSION = "0.1.0";
4
6
  /**
5
7
  * 项目导航索引的中性 contract 名称;供静态 portal、搜索与宿主导航消费。
@@ -54,7 +56,8 @@ export function renderProjectHtmlDocument(projectInput, options = {}) {
54
56
  const pageTitle = options.title ?? normalizedProjectInput.project.title ?? normalizedProjectInput.project.name;
55
57
  const includeThemeAssets = options.includeThemeAssets ?? true;
56
58
  const siteLayout = options.projectSite?.layout ?? "split-site";
57
- const navigationIndex = createProjectNavigationIndex(normalizedProjectInput, pageTitle, options);
59
+ const portalContext = resolveProjectPortalContext(normalizedProjectInput, options, siteLayout);
60
+ const navigationIndex = createProjectNavigationIndex(normalizedProjectInput, pageTitle, options, portalContext);
58
61
  const files = siteLayout === "single-page"
59
62
  ? [
60
63
  {
@@ -64,7 +67,7 @@ export function renderProjectHtmlDocument(projectInput, options = {}) {
64
67
  role: "entry"
65
68
  }
66
69
  ]
67
- : createProjectSplitSiteFiles(pageTitle, normalizedProjectInput, navigationIndex, options);
70
+ : createProjectSplitSiteFiles(pageTitle, normalizedProjectInput, navigationIndex, options, portalContext);
68
71
  files.push({
69
72
  path: "project-index.json",
70
73
  contents: `${JSON.stringify(navigationIndex, null, 2)}\n`,
@@ -87,6 +90,149 @@ export function renderProjectHtmlDocument(projectInput, options = {}) {
87
90
  manifest: createProjectManifest(normalizedProjectInput, files, pageTitle, options, navigationIndex)
88
91
  };
89
92
  }
93
+ /**
94
+ * 在任何文件生成前完成 exact draft 与 single-page gate,避免 partial output。
95
+ * Resolves the exact draft and single-page gate before any files are generated, preventing partial output.
96
+ */
97
+ function resolveProjectPortalContext(projectInput, options, layout) {
98
+ const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
99
+ const uiLocale = resolveDocumentationPortalUiLocale(options.projectSite?.uiLocale, localeModel.selectedLocale);
100
+ const explicitInformationArchitecture = options.projectSite?.informationArchitecture;
101
+ const sourceCommentProjection = options.projectSite?.sourceCommentProjection;
102
+ if (projectInput.documentationContinuity) {
103
+ assertProjectDocumentationContinuitySummary(projectInput.documentationContinuity);
104
+ }
105
+ if (projectInput.ownerAdoption) {
106
+ assertProjectOwnerAdoptionSummary(projectInput.ownerAdoption);
107
+ if (!explicitInformationArchitecture) {
108
+ throw new TypeError("HIA_PORTAL_IA_OWNER_ADOPTION_REQUIRES_IA: owner-adoption linkage requires explicit Portal information architecture.");
109
+ }
110
+ }
111
+ if (sourceCommentProjection && !explicitInformationArchitecture) {
112
+ throw new TypeError("HIA_PORTAL_SOURCE_COMMENT_REQUIRES_IA: source-comment projection requires explicit Portal information architecture.");
113
+ }
114
+ if (sourceCommentProjection) {
115
+ const canonical = canonicalizeDocumentationLocale(sourceCommentProjection.locale);
116
+ if (!canonical || canonical.usedLegacyUnderscore || canonical.canonical !== sourceCommentProjection.locale) {
117
+ throw new TypeError("HIA_PORTAL_SOURCE_COMMENT_LOCALE_INVALID: source-comment locale must be a canonical BCP 47 tag.");
118
+ }
119
+ for (const entry of projectInput.entries) {
120
+ if (!entry.sourceCommentProjection)
121
+ continue;
122
+ const validationDiagnostics = validateDocumentationSourceCommentProjection(entry.sourceCommentProjection);
123
+ if (validationDiagnostics.length > 0 || entry.sourceCommentProjection.requestedLocale !== canonical.canonical) {
124
+ throw new TypeError("HIA_PORTAL_SOURCE_COMMENT_PROJECTION_INVALID: source-comment projection must be valid and match the explicit locale.");
125
+ }
126
+ }
127
+ }
128
+ if (explicitInformationArchitecture && layout === "single-page") {
129
+ throw new TypeError("HIA_CONFIG_IA_SINGLE_PAGE_UNSUPPORTED: Explicit Portal IA is supported only with split-site in this draft.");
130
+ }
131
+ return {
132
+ uiLocale,
133
+ labels: getDocumentationPortalLabels(uiLocale),
134
+ ...(sourceCommentProjection
135
+ ? {
136
+ sourceCommentProjection: {
137
+ contentPolicy: sourceCommentProjection.contentPolicy ?? "none",
138
+ locale: sourceCommentProjection.locale
139
+ }
140
+ }
141
+ : {}),
142
+ ...(explicitInformationArchitecture
143
+ ? {
144
+ informationArchitecture: resolveDocumentationPortalInformationArchitecture(explicitInformationArchitecture, uiLocale, localeModel.selectedLocale)
145
+ }
146
+ : {})
147
+ };
148
+ }
149
+ /** optional continuity linkage 只接受 exact、non-negative、body-free summary。Optional continuity linkage accepts only an exact, non-negative, body-free summary. */
150
+ function assertProjectDocumentationContinuitySummary(summary) {
151
+ const validShape = isExactObject(summary, [
152
+ "contract",
153
+ "contractVersion",
154
+ "status",
155
+ "entries",
156
+ "requiredOutputsPreserved",
157
+ "semantics"
158
+ ])
159
+ && isExactObject(summary.entries, ["addedCount", "baselineCount", "currentCount", "removedCount", "unchangedCount"])
160
+ && isExactObject(summary.semantics, ["resolution", "confidence", "provenance"]);
161
+ const counts = validShape ? Object.values(summary.entries) : [];
162
+ const countsConsistent = validShape
163
+ && summary.entries.baselineCount === summary.entries.unchangedCount + summary.entries.removedCount
164
+ && summary.entries.currentCount === summary.entries.unchangedCount + summary.entries.addedCount;
165
+ if (!validShape
166
+ || summary.contract !== "target-documentation-continuity"
167
+ || summary.contractVersion !== "0.1.0-draft"
168
+ || !["accepted", "refused"].includes(summary.status)
169
+ || typeof summary.requiredOutputsPreserved !== "boolean"
170
+ || !["evidence-summary-pair-validated", "unresolved"].includes(summary.semantics.resolution)
171
+ || summary.semantics.confidence !== "caller-provided-unverified"
172
+ || summary.semantics.provenance !== "metadata-only-comparison"
173
+ || counts.some((value) => !Number.isSafeInteger(value) || value < 0)
174
+ || !countsConsistent) {
175
+ throw new TypeError("HIA_PORTAL_IA_CONTINUITY_INVALID: continuity linkage must be an exact metadata-only count summary.");
176
+ }
177
+ }
178
+ /**
179
+ * @lang zh-CN owner-adoption linkage 只接受 exact、count-consistent、identity/body-free 的 metadata 投影。
180
+ * @lang en Owner-adoption linkage accepts only an exact, count-consistent, identity- and body-free metadata projection.
181
+ */
182
+ function assertProjectOwnerAdoptionSummary(summary) {
183
+ const rootFields = ["contract", "contractVersion", "projection", "status", "targetFamily", "ownerInput", "contracts", "semantics"];
184
+ const workspaceExpected = summary.targetFamily === "workspace-container";
185
+ const hasWorkspace = summary.workspaceHandoff !== undefined;
186
+ const validShape = isExactObject(summary, hasWorkspace ? [...rootFields, "workspaceHandoff"] : rootFields)
187
+ && isExactObject(summary.ownerInput, ["submitted", "consent"])
188
+ && isExactObject(summary.contracts, ["requiredCount", "providedCount", "missingCount"])
189
+ && isExactObject(summary.semantics, ["resolution", "confidence", "provenance"])
190
+ && (!hasWorkspace || (summary.workspaceHandoff !== undefined
191
+ && isExactObject(summary.workspaceHandoff, ["repositoryOwnerCount", "handoffEdgeCount", "state"])));
192
+ const counts = validShape
193
+ ? [summary.contracts.requiredCount, summary.contracts.providedCount, summary.contracts.missingCount]
194
+ : [];
195
+ const statusResolutionValid = (summary.status === "ready-for-owner-review"
196
+ && summary.ownerInput.submitted
197
+ && summary.contracts.missingCount === 0
198
+ && summary.semantics.resolution === "owner-input-validated")
199
+ || (summary.status === "deferred-owner-input-missing"
200
+ && !summary.ownerInput.submitted
201
+ && summary.semantics.resolution === "owner-input-not-received")
202
+ || (summary.status === "refused" && summary.semantics.resolution === "unresolved");
203
+ const workspaceValid = workspaceExpected
204
+ ? (summary.status !== "ready-for-owner-review" && !hasWorkspace) || (summary.workspaceHandoff !== undefined
205
+ && Number.isSafeInteger(summary.workspaceHandoff.repositoryOwnerCount)
206
+ && summary.workspaceHandoff.repositoryOwnerCount >= 2
207
+ && Number.isSafeInteger(summary.workspaceHandoff.handoffEdgeCount)
208
+ && summary.workspaceHandoff.handoffEdgeCount >= 1
209
+ && summary.workspaceHandoff.state === "owner-review-required")
210
+ : !hasWorkspace;
211
+ if (!validShape
212
+ || summary.contract !== "target-owner-adoption-kit"
213
+ || summary.contractVersion !== "0.1.0-draft"
214
+ || summary.projection !== "portal-metadata-only"
215
+ || !["ready-for-owner-review", "deferred-owner-input-missing", "refused"].includes(summary.status)
216
+ || !["enterprise-business", "workspace-container"].includes(summary.targetFamily)
217
+ || typeof summary.ownerInput.submitted !== "boolean"
218
+ || !["not-recorded", "recorded-for-review"].includes(summary.ownerInput.consent)
219
+ || counts.some((value) => !Number.isSafeInteger(value) || value < 0)
220
+ || summary.contracts.providedCount + summary.contracts.missingCount !== summary.contracts.requiredCount
221
+ || summary.semantics.confidence !== "caller-provided-unverified"
222
+ || summary.semantics.provenance !== "metadata-only-owner-kit"
223
+ || !statusResolutionValid
224
+ || !workspaceValid) {
225
+ throw new TypeError("HIA_PORTAL_IA_OWNER_ADOPTION_INVALID: owner-adoption linkage must be an exact metadata-only summary.");
226
+ }
227
+ }
228
+ /** closed-world runtime object shape 检查,防止 TypeScript 之外的 caller 注入 path/body/identity。Checks closed-world runtime object shapes so non-TypeScript callers cannot inject paths, bodies, or identities. */
229
+ function isExactObject(value, allowedFields) {
230
+ return value !== null
231
+ && typeof value === "object"
232
+ && !Array.isArray(value)
233
+ && Object.keys(value).every((field) => allowedFields.includes(field))
234
+ && allowedFields.every((field) => Object.hasOwn(value, field));
235
+ }
90
236
  /**
91
237
  * 在 renderer 公共入口执行源码呈现边界,保证直接库调用与 CLI 调用具有同一隐私语义。
92
238
  * Enforces source-presentation boundaries at the renderer API so direct library and CLI calls share the same privacy semantics.
@@ -161,6 +307,7 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
161
307
  name: projectInput.project.name,
162
308
  views,
163
309
  entryCounts: countEntriesByView(projectInput.entries),
310
+ ...(projectInput.project.productVersion ? { productVersion: projectInput.project.productVersion } : {}),
164
311
  navigationIndex: {
165
312
  contract: navigationIndex.contract,
166
313
  contractVersion: navigationIndex.contractVersion,
@@ -169,6 +316,18 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
169
316
  },
170
317
  ...(projectInput.profiles && projectInput.profiles.length > 0 ? { profiles: projectInput.profiles } : {}),
171
318
  ...(projectInput.docSourceMaps && projectInput.docSourceMaps.length > 0 ? { docSourceMaps: projectInput.docSourceMaps } : {}),
319
+ ...(projectInput.generatedDocumentationBindingProjection
320
+ ? {
321
+ generatedDocumentationBindingProjection: {
322
+ bindingCount: projectInput.generatedDocumentationBindingProjection.summary.bindingCount,
323
+ contract: projectInput.generatedDocumentationBindingProjection.contract,
324
+ contractVersion: projectInput.generatedDocumentationBindingProjection.contractVersion,
325
+ path: "project-index.json",
326
+ status: projectInput.generatedDocumentationBindingProjection.status,
327
+ targetCount: projectInput.generatedDocumentationBindingProjection.summary.targetCount
328
+ }
329
+ }
330
+ : {}),
172
331
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
173
332
  ? {
174
333
  relationGraph: {
@@ -179,11 +338,14 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
179
338
  path: "project-index.json"
180
339
  }
181
340
  }
341
+ : {}),
342
+ ...(navigationIndex.site?.informationArchitecture
343
+ ? { informationArchitecture: navigationIndex.site.informationArchitecture }
182
344
  : {})
183
345
  }
184
346
  };
185
347
  }
186
- function createProjectNavigationIndex(projectInput, pageTitle, options) {
348
+ function createProjectNavigationIndex(projectInput, pageTitle, options, portalContext) {
187
349
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
188
350
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
189
351
  return {
@@ -196,7 +358,8 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
196
358
  locales: localeModel.locales,
197
359
  name: projectInput.project.name,
198
360
  title: pageTitle,
199
- views: collectProjectViews(projectInput.entries)
361
+ views: collectProjectViews(projectInput.entries),
362
+ ...(projectInput.project.productVersion ? { productVersion: projectInput.project.productVersion } : {})
200
363
  },
201
364
  entries: projectInput.entries
202
365
  .map((entry) => ({
@@ -210,16 +373,32 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
210
373
  ...(entry.profile ? { profile: entry.profile } : {}),
211
374
  ...(entry.input ? { input: entry.input } : {}),
212
375
  ...(entry.source ? { source: omitProjectSourcePreview(entry.source) } : {}),
376
+ ...(entry.sourceUsability ? { sourceUsability: selectProjectSourceUsability(entry.sourceUsability) } : {}),
377
+ ...(entry.sourceCommentProjection && portalContext.sourceCommentProjection
378
+ ? { sourceCommentProjection: selectProjectSourceCommentProjection(entry.sourceCommentProjection) }
379
+ : {}),
213
380
  ...(entry.symbolId ? { symbolId: entry.symbolId } : {}),
214
381
  ...(entry.hierarchy ? { hierarchy: entry.hierarchy } : {}),
215
382
  contentPath: createProjectEntryContentPath(entry.id),
383
+ ...(portalContext.informationArchitecture
384
+ ? {
385
+ presentationPath: createProjectEntryPresentationPath(entry, projectInput.entries, portalContext.informationArchitecture),
386
+ memberAnchor: entry.id,
387
+ ...(entry.semanticPath ? { semanticPath: entry.semanticPath } : {})
388
+ }
389
+ : {}),
216
390
  ...(entry.docSourceMap ? { docSourceMap: entry.docSourceMap } : {})
217
391
  }))
218
392
  .sort(compareProjectNavigationEntries),
219
393
  groups: collectProjectNavigationGroups(projectInput.entries),
220
- navigationTree: collectProjectNavigationTree(projectInput.entries),
394
+ navigationTree: applyProjectNavigationPresentationPaths(collectProjectNavigationTree(projectInput.entries, portalContext.informationArchitecture), projectInput.entries, portalContext.informationArchitecture),
221
395
  profiles: [...(projectInput.profiles ?? [])].sort(compareProjectProfiles),
222
396
  docSourceMaps: [...(projectInput.docSourceMaps ?? [])].sort(compareProjectDocSourceMaps),
397
+ ...(projectInput.generatedDocumentationBindingProjection
398
+ ? { generatedDocumentationBindingProjection: projectInput.generatedDocumentationBindingProjection }
399
+ : {}),
400
+ ...(projectInput.documentationContinuity ? { documentationContinuity: projectInput.documentationContinuity } : {}),
401
+ ...(projectInput.ownerAdoption ? { ownerAdoption: projectInput.ownerAdoption } : {}),
223
402
  site: {
224
403
  layout: options.projectSite?.layout ?? "split-site",
225
404
  ...(options.projectSite?.layout === "single-page" ? {} : {
@@ -227,7 +406,10 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
227
406
  searchIndexPath: "search/index.json",
228
407
  relationIndexPath: "relations/project.json"
229
408
  }),
230
- sourcePresentation: options.projectSite?.source?.presentation ?? "link"
409
+ sourcePresentation: options.projectSite?.source?.presentation ?? "link",
410
+ ...(portalContext.informationArchitecture
411
+ ? { informationArchitecture: portalContext.informationArchitecture }
412
+ : {})
231
413
  },
232
414
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
233
415
  ? { relationGraph: projectInput.relationGraph }
@@ -238,16 +420,17 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
238
420
  * 生成大型项目默认使用的 split-site 文件集合;入口页只保留应用壳。
239
421
  * Generates the split-site file set used by large projects by default; the entry page only keeps the application shell.
240
422
  */
241
- function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options) {
423
+ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options, portalContext) {
242
424
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
425
+ const informationArchitecture = portalContext.informationArchitecture;
243
426
  const files = [
244
427
  {
245
428
  path: "index.html",
246
- contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options),
429
+ contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext),
247
430
  contentType: "text/html; charset=utf-8",
248
431
  role: "entry"
249
432
  },
250
- ...createProjectNavigationShardFiles(navigationIndex.navigationTree),
433
+ ...createProjectNavigationShardFiles(navigationIndex.navigationTree, informationArchitecture?.loadingStrategy ?? "lazy"),
251
434
  {
252
435
  path: "search/index.json",
253
436
  contents: `${JSON.stringify({
@@ -259,6 +442,12 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
259
442
  kind: entry.kind,
260
443
  view: entry.view,
261
444
  contentPath: createProjectEntryContentPath(entry.id),
445
+ ...(informationArchitecture
446
+ ? {
447
+ presentationPath: createProjectEntryPresentationPath(entry, projectInput.entries, informationArchitecture),
448
+ memberAnchor: entry.id
449
+ }
450
+ : {}),
262
451
  searchText: createProjectEntrySearchText(entry)
263
452
  }))
264
453
  }, null, 2)}\n`,
@@ -272,19 +461,60 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
272
461
  role: "index"
273
462
  }
274
463
  ];
464
+ // <lang zh-CN>canonical entry fragment 始终生成,保证旧 deep link 与不识别 IA 的 consumer 可回退。</lang>
465
+ // <lang en>Canonical entry fragments are always emitted so old deep links and IA-unaware consumers retain a fallback.</lang>
275
466
  for (const entry of projectInput.entries) {
276
467
  files.push({
277
468
  path: createProjectEntryContentPath(entry.id),
278
- contents: renderProjectEntry(entry, localeModel.locales, localeModel.selectedLocale),
469
+ contents: informationArchitecture
470
+ ? renderProjectSemanticTopic(entry, projectInput, localeModel.locales, localeModel.selectedLocale, portalContext, informationArchitecture.memberPlacement === "with-parent")
471
+ : renderProjectEntry(entry, localeModel.locales, localeModel.selectedLocale),
279
472
  contentType: "text/html; charset=utf-8",
280
473
  role: "asset"
281
474
  });
282
475
  }
476
+ // <lang zh-CN>semantic-container 只增加 presentation fragment,不替换 canonical fragment。</lang>
477
+ // <lang en>Semantic containers add presentation fragments without replacing canonical fragments.</lang>
478
+ if (informationArchitecture?.contentGrouping === "semantic-container") {
479
+ files.push(...createProjectSemanticContainerFiles(projectInput, localeModel, portalContext));
480
+ }
481
+ // <lang zh-CN>eager 以单一 index 预载 presentation fragment;canonical files 仍保持独立可寻址。</lang>
482
+ // <lang en>Eager delivery preloads presentation fragments through one index while canonical files remain independently addressable.</lang>
483
+ if (informationArchitecture?.loadingStrategy === "eager") {
484
+ const presentationPaths = new Set(navigationIndex.entries.map((entry) => entry.presentationPath ?? entry.contentPath).filter((path) => Boolean(path)));
485
+ const fragments = files
486
+ .filter((file) => presentationPaths.has(file.path))
487
+ .map((file) => ({ path: file.path, contents: file.contents }))
488
+ .sort((left, right) => compareStableText(left.path, right.path));
489
+ files.push({
490
+ path: "content/eager.json",
491
+ contents: `${JSON.stringify({
492
+ contract: "documentation-portal-eager-fragment-index",
493
+ contractVersion: "0.1.0-draft",
494
+ fragments
495
+ }, null, 2)}\n`,
496
+ contentType: "application/json; charset=utf-8",
497
+ role: "index"
498
+ });
499
+ }
283
500
  return files;
284
501
  }
285
- function createProjectNavigationShardFiles(nodes) {
502
+ function createProjectNavigationShardFiles(nodes, loadingStrategy) {
286
503
  const files = [];
287
504
  const emittedPaths = new Set();
505
+ if (loadingStrategy === "eager") {
506
+ return [{
507
+ path: "navigation/root.json",
508
+ contents: `${JSON.stringify({
509
+ contract: "hia-project-navigation-shard",
510
+ contractVersion: "0.1.0-draft",
511
+ nodeId: "root",
512
+ children: nodes
513
+ }, null, 2)}\n`,
514
+ contentType: "application/json; charset=utf-8",
515
+ role: "index"
516
+ }];
517
+ }
288
518
  const emitChildren = (nodeId, children, root = false) => {
289
519
  const shardPath = root ? "navigation/root.json" : createProjectNavigationChildrenPath(nodeId);
290
520
  if (emittedPaths.has(shardPath)) {
@@ -318,12 +548,93 @@ function toLazyProjectNavigationNode(node) {
318
548
  ...(node.children && node.children.length > 0
319
549
  ? { childrenPath: createProjectNavigationChildrenPath(node.id) }
320
550
  : {}),
321
- ...(node.entryId ? { contentPath: createProjectEntryContentPath(node.entryId) } : {})
551
+ ...(node.entryId && !node.contentPath ? { contentPath: createProjectEntryContentPath(node.entryId) } : {})
322
552
  };
323
553
  }
324
554
  function createProjectEntryContentPath(entryId) {
325
555
  return `entries/${stableProjectArtifactName(entryId)}.html`;
326
556
  }
557
+ /**
558
+ * 计算 additive presentation location;canonical contentPath 永远由 entry id 单独计算。
559
+ * Computes the additive presentation location; canonical contentPath is always computed independently from the entry id.
560
+ */
561
+ function createProjectEntryPresentationPath(entry, entries, informationArchitecture) {
562
+ const presentationOwner = informationArchitecture.memberPlacement === "with-parent"
563
+ ? findProjectParentEntry(entry, entries) ?? entry
564
+ : entry;
565
+ if (informationArchitecture.contentGrouping === "semantic-container") {
566
+ return createProjectSemanticContainerPath(presentationOwner);
567
+ }
568
+ return createProjectEntryContentPath(presentationOwner.id);
569
+ }
570
+ /** semantic container id 只消费 manifest segment 或稳定 unscoped view,不读取 source path。Semantic container ids use manifest segments or a stable unscoped view, never source paths. */
571
+ function createProjectSemanticContainerPath(entry) {
572
+ const identity = entry.semanticPath && entry.semanticPath.length > 0
573
+ ? entry.semanticPath.map((segment) => `${segment.kind}:${segment.id}`).join("|")
574
+ : `unscoped:${entry.view}`;
575
+ return `semantic-containers/${stableProjectArtifactName(identity)}.html`;
576
+ }
577
+ /** 仅按显式 parentSymbolId/symbolId 解析父入口,不执行名称或路径猜测。Resolves a parent only by explicit parentSymbolId/symbolId, with no name or path inference. */
578
+ function findProjectParentEntry(entry, entries) {
579
+ const parentSymbolId = entry.hierarchy?.parentSymbolId;
580
+ return parentSymbolId ? entries.find((candidate) => candidate.symbolId === parentSymbolId) : undefined;
581
+ }
582
+ /** 把 canonical 与 presentation location 投影到 leaf node,保持 tree node identity 不变。Projects canonical and presentation locations onto leaf nodes without changing tree-node identity. */
583
+ function applyProjectNavigationPresentationPaths(nodes, entries, informationArchitecture) {
584
+ const entriesById = new Map(entries.map((entry) => [entry.id, entry]));
585
+ return nodes.map((node) => {
586
+ const entry = node.entryId ? entriesById.get(node.entryId) : undefined;
587
+ return {
588
+ ...node,
589
+ ...(node.children
590
+ ? { children: applyProjectNavigationPresentationPaths(node.children, entries, informationArchitecture) }
591
+ : {}),
592
+ ...(entry ? { contentPath: createProjectEntryContentPath(entry.id) } : {}),
593
+ ...(entry && informationArchitecture
594
+ ? {
595
+ presentationPath: createProjectEntryPresentationPath(entry, entries, informationArchitecture),
596
+ memberAnchor: entry.id
597
+ }
598
+ : {})
599
+ };
600
+ });
601
+ }
602
+ /**
603
+ * 按 presentation path 生成 container fragment;with-parent child 由 parent topic 的 members section 承载。
604
+ * Emits container fragments by presentation path; with-parent children are carried by the parent topic's members section.
605
+ */
606
+ function createProjectSemanticContainerFiles(projectInput, localeModel, portalContext) {
607
+ const informationArchitecture = portalContext.informationArchitecture;
608
+ if (!informationArchitecture) {
609
+ return [];
610
+ }
611
+ const groups = new Map();
612
+ for (const entry of projectInput.entries) {
613
+ const path = createProjectEntryPresentationPath(entry, projectInput.entries, informationArchitecture);
614
+ const bucket = groups.get(path) ?? [];
615
+ bucket.push(entry);
616
+ groups.set(path, bucket);
617
+ }
618
+ return [...groups.entries()]
619
+ .sort(([left], [right]) => compareStableText(left, right))
620
+ .map(([path, entries]) => {
621
+ const visibleEntries = informationArchitecture.memberPlacement === "with-parent"
622
+ ? entries.filter((entry) => {
623
+ const parent = findProjectParentEntry(entry, projectInput.entries);
624
+ return !parent || createProjectEntryPresentationPath(parent, projectInput.entries, informationArchitecture) !== path;
625
+ })
626
+ : entries;
627
+ return {
628
+ path,
629
+ contents: visibleEntries
630
+ .sort(compareProjectNavigationEntries)
631
+ .map((entry) => renderProjectSemanticTopic(entry, projectInput, localeModel.locales, localeModel.selectedLocale, portalContext, informationArchitecture.memberPlacement === "with-parent"))
632
+ .join(""),
633
+ contentType: "text/html; charset=utf-8",
634
+ role: "asset"
635
+ };
636
+ });
637
+ }
327
638
  function createProjectNavigationChildrenPath(nodeId) {
328
639
  return `navigation/${stableProjectArtifactName(nodeId)}.json`;
329
640
  }
@@ -385,33 +696,12 @@ function renderIndexHtml(pageTitle, document, options) {
385
696
  "</html>"
386
697
  ].join("");
387
698
  }
388
- function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
699
+ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext) {
389
700
  const projectName = projectInput.project.title ?? projectInput.project.name;
390
701
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
391
702
  const views = collectProjectViews(projectInput.entries);
392
703
  const entryCounts = countEntriesByView(projectInput.entries);
393
- const selectedChinese = localeModel.selectedLocale.toLowerCase().startsWith("zh");
394
- const labels = selectedChinese
395
- ? {
396
- hierarchy: "层级导航",
397
- loading: "正在加载文档导航...",
398
- open: "打开",
399
- relations: "项目关系",
400
- select: "请从左侧层级树选择一个文档节点。",
401
- search: "搜索",
402
- searchPlaceholder: "名称、类型、源码或选择器",
403
- requiresServer: "按需加载站点需要通过 HTTP(S) 提供;请使用本地静态服务器打开该目录。"
404
- }
405
- : {
406
- hierarchy: "Hierarchy",
407
- loading: "Loading documentation navigation...",
408
- open: "Open",
409
- relations: "Project relations",
410
- select: "Select a documentation node from the hierarchy.",
411
- search: "Search",
412
- searchPlaceholder: "Name, kind, source, selector",
413
- requiresServer: "The lazy site must be served over HTTP(S); open this directory through a local static server."
414
- };
704
+ const labels = portalContext.labels;
415
705
  return [
416
706
  "<!doctype html>",
417
707
  `<html lang="${escapeHtml(localeModel.selectedLocale)}">`,
@@ -428,6 +718,7 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
428
718
  `<h1>${escapeHtml(projectName)}</h1>`,
429
719
  renderLocaleControl(localeModel.locales, localeModel.selectedLocale),
430
720
  renderProjectViewControl(views, entryCounts),
721
+ renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection),
431
722
  [
432
723
  "<label class=\"hia-project-search\">",
433
724
  `<span>${escapeHtml(labels.search)}</span>`,
@@ -440,7 +731,7 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
440
731
  `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${escapeHtml(labels.select)}</p></main>`,
441
732
  "</div>",
442
733
  `<script src="${escapeHtml(DEFAULT_THEME_JS_PATH)}"></script>`,
443
- renderProjectSplitSiteScript(labels.requiresServer, labels.open),
734
+ renderProjectSplitSiteScript(labels.requiresServer, labels.open, portalContext.informationArchitecture?.loadingStrategy ?? "lazy", labels.relations),
444
735
  "</body>",
445
736
  "</html>"
446
737
  ].join("");
@@ -501,11 +792,11 @@ function renderProjectSourceFetchClientLines(rootExpression) {
501
792
  " }"
502
793
  ];
503
794
  }
504
- function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
795
+ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStrategy, relationsLabel) {
505
796
  return [
506
797
  "<script>",
507
798
  "(() => {",
508
- " const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json' };",
799
+ ` const config = { navigation: 'navigation/root.json', search: 'search/index.json', relations: 'relations/project.json', loadingStrategy: ${JSON.stringify(loadingStrategy)}, eagerContent: 'content/eager.json' };`,
509
800
  " const treeHost = document.querySelector('[data-hia-project-tree]');",
510
801
  " const contentHost = document.querySelector('[data-hia-project-content]');",
511
802
  " const search = document.querySelector('[data-hia-project-search]');",
@@ -513,6 +804,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
513
804
  " const viewButtons = Array.from(document.querySelectorAll('[data-hia-project-view]'));",
514
805
  " let rootNodes = [];",
515
806
  " let searchEntries = null;",
807
+ " let eagerFragments = null;",
516
808
  " let activeView = 'all';",
517
809
  " async function readJson(target) {",
518
810
  " const response = await fetch(target, { credentials: 'omit' });",
@@ -539,8 +831,12 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
539
831
  " function createTreeNode(node) {",
540
832
  " const item = document.createElement('li');",
541
833
  " item.dataset.hiaProjectNav = node.views?.[0] || 'other';",
542
- " if (node.childrenPath) {",
834
+ " item.dataset.hiaProjectNodeId = node.id || '';",
835
+ " if (node.entryId) item.dataset.hiaProjectEntryId = node.entryId;",
836
+ " const inlineChildren = Array.isArray(node.children) ? node.children : [];",
837
+ " if (node.childrenPath || inlineChildren.length > 0) {",
543
838
  " const details = document.createElement('details');",
839
+ " details.dataset.hiaProjectDisclosure = node.id || '';",
544
840
  " const summary = document.createElement('summary');",
545
841
  " const summaryLabel = document.createElement('span');",
546
842
  " summaryLabel.textContent = `${node.label} (${node.entryCount})`;",
@@ -553,32 +849,37 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
553
849
  " openButton.addEventListener('click', (event) => {",
554
850
  " event.preventDefault();",
555
851
  " event.stopPropagation();",
556
- " loadEntry(node.entryId, node.contentPath, true);",
852
+ " loadEntry(node, true);",
557
853
  " });",
558
854
  " summary.append(openButton);",
559
855
  " }",
560
856
  " details.append(summary);",
561
- " details.addEventListener('toggle', async () => {",
562
- " if (!details.open || details.dataset.loaded === 'true') return;",
857
+ " if (inlineChildren.length > 0) {",
563
858
  " details.dataset.loaded = 'true';",
564
- " const loading = document.createElement('p');",
565
- " loading.className = 'hia-project-loading';",
566
- " loading.textContent = '...';",
567
- " details.append(loading);",
568
- " try {",
569
- " const shard = await readJson(node.childrenPath);",
570
- " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
571
- " } catch (error) {",
572
- " loading.textContent = String(error?.message || error);",
573
- " }",
574
- " });",
859
+ " details.append(createTreeList(inlineChildren));",
860
+ " } else {",
861
+ " details.addEventListener('toggle', async () => {",
862
+ " if (!details.open || details.dataset.loaded === 'true') return;",
863
+ " details.dataset.loaded = 'true';",
864
+ " const loading = document.createElement('p');",
865
+ " loading.className = 'hia-project-loading';",
866
+ " loading.textContent = '...';",
867
+ " details.append(loading);",
868
+ " try {",
869
+ " const shard = await readJson(node.childrenPath);",
870
+ " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
871
+ " } catch (error) {",
872
+ " loading.textContent = String(error?.message || error);",
873
+ " }",
874
+ " });",
875
+ " }",
575
876
  " item.append(details);",
576
877
  " } else if (node.entryId && node.contentPath) {",
577
878
  " const button = document.createElement('button');",
578
879
  " button.type = 'button';",
579
880
  " button.className = 'hia-project-entry-link';",
580
881
  " button.textContent = node.label;",
581
- " button.addEventListener('click', () => loadEntry(node.entryId, node.contentPath, true));",
882
+ " button.addEventListener('click', () => loadEntry(node, true));",
582
883
  " item.append(button);",
583
884
  " } else {",
584
885
  " const label = document.createElement('span');",
@@ -600,16 +901,46 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
600
901
  " }",
601
902
  " }",
602
903
  ...renderProjectSourceFetchClientLines("contentHost"),
603
- " async function loadEntry(entryId, contentPath, updateHash) {",
904
+ " async function ensureEagerFragments() {",
905
+ " if (config.loadingStrategy !== 'eager') return null;",
906
+ " if (eagerFragments) return eagerFragments;",
907
+ " const index = await readJson(config.eagerContent);",
908
+ " eagerFragments = new Map((Array.isArray(index.fragments) ? index.fragments : []).map((fragment) => [fragment.path, fragment.contents]));",
909
+ " return eagerFragments;",
910
+ " }",
911
+ " async function readFragment(path) {",
912
+ " const eager = await ensureEagerFragments();",
913
+ " if (eager?.has(path)) return eager.get(path);",
914
+ " const response = await fetch(path, { credentials: 'omit' });",
915
+ " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
916
+ " return response.text();",
917
+ " }",
918
+ " function markActiveEntry(entryId) {",
919
+ " for (const item of document.querySelectorAll('[data-hia-project-node-id]')) {",
920
+ " delete item.dataset.hiaActiveEntry;",
921
+ " for (const details of item.querySelectorAll(':scope > details')) delete details.dataset.hiaActiveAncestor;",
922
+ " }",
923
+ " const leaf = Array.from(document.querySelectorAll('[data-hia-project-entry-id]')).find((item) => item.dataset.hiaProjectEntryId === entryId);",
924
+ " if (!leaf) return;",
925
+ " leaf.dataset.hiaActiveEntry = 'true';",
926
+ " for (const details of leaf.parentElement?.closest('details') ? [leaf.parentElement.closest('details')] : []) {",
927
+ " let current = details;",
928
+ " while (current) { current.open = true; current.dataset.hiaActiveAncestor = 'true'; current = current.parentElement?.closest('details'); }",
929
+ " }",
930
+ " }",
931
+ " async function loadEntry(entry, updateHash) {",
604
932
  " if (!contentHost) return;",
605
933
  " contentHost.innerHTML = '<p class=\"hia-project-loading\">...</p>';",
606
934
  " try {",
607
- " const response = await fetch(contentPath, { credentials: 'omit' });",
608
- " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
609
- " contentHost.innerHTML = await response.text();",
935
+ " const contentPath = entry.presentationPath || entry.contentPath;",
936
+ " contentHost.innerHTML = await readFragment(contentPath);",
610
937
  " applyLocale();",
611
938
  " bindSourceFetch();",
612
- " if (updateHash) history.replaceState(null, '', `#entry=${encodeURIComponent(entryId)}`);",
939
+ " const anchor = entry.memberAnchor || entry.entryId || entry.id;",
940
+ " const target = Array.from(contentHost.querySelectorAll('[id]')).find((item) => item.id === anchor);",
941
+ " target?.scrollIntoView({ block: 'start' });",
942
+ " markActiveEntry(entry.entryId || entry.id);",
943
+ " if (updateHash) history.replaceState(null, '', `#entry=${encodeURIComponent(entry.entryId || entry.id)}`);",
613
944
  " } catch (error) {",
614
945
  " showLoadError(error);",
615
946
  " }",
@@ -628,7 +959,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
628
959
  " const matches = entries.filter((entry) => (activeView === 'all' || entry.view === activeView) && String(entry.searchText || '').includes(query)).slice(0, 200);",
629
960
  " if (!treeHost) return;",
630
961
  " treeHost.innerHTML = '';",
631
- " const nodes = matches.map((entry) => ({ id: entry.id, label: `${entry.name} · ${entry.kind}`, entryId: entry.id, contentPath: entry.contentPath, views: [entry.view], entryCount: 1 }));",
962
+ " const nodes = matches.map((entry) => ({ id: entry.id, label: `${entry.name} · ${entry.kind}`, entryId: entry.id, contentPath: entry.contentPath, presentationPath: entry.presentationPath, memberAnchor: entry.memberAnchor, views: [entry.view], entryCount: 1 }));",
632
963
  " treeHost.append(createTreeList(nodes));",
633
964
  " } catch (error) { showLoadError(error); }",
634
965
  " }",
@@ -649,7 +980,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
649
980
  " const article = document.createElement('article');",
650
981
  " article.className = 'hia-symbol';",
651
982
  " const heading = document.createElement('h2');",
652
- " heading.textContent = 'Relations';",
983
+ ` heading.textContent = ${JSON.stringify(relationsLabel)};`,
653
984
  " const summary = document.createElement('p');",
654
985
  " summary.textContent = `${graph.nodeCount || 0} node(s), ${graph.relationCount || 0} relation(s).`;",
655
986
  " article.append(heading, summary);",
@@ -662,7 +993,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
662
993
  " const hash = location.hash.startsWith('#entry=') ? decodeURIComponent(location.hash.slice(7)) : '';",
663
994
  " if (hash) ensureSearchIndex().then((entries) => {",
664
995
  " const entry = entries.find((candidate) => candidate.id === hash);",
665
- " if (entry) loadEntry(entry.id, entry.contentPath, false);",
996
+ " if (entry) loadEntry({ ...entry, entryId: entry.id }, false);",
666
997
  " });",
667
998
  " }).catch(showLoadError);",
668
999
  " viewButtons.find((button) => button.dataset.hiaProjectView === 'all')?.setAttribute('aria-pressed', 'true');",
@@ -687,6 +1018,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
687
1018
  const docSourceMapSummary = renderProjectDocSourceMaps(projectInput.docSourceMaps ?? []);
688
1019
  const relationGraphSummary = renderProjectRelationGraphSummary(projectInput.relationGraph);
689
1020
  const relationGraph = renderProjectRelationGraph(projectInput.relationGraph);
1021
+ const generatedDocumentationBindingProjection = renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection);
690
1022
  const diagnostics = renderProjectDiagnostics(projectInput.diagnostics ?? []);
691
1023
  return [
692
1024
  "<!doctype html>",
@@ -711,6 +1043,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
711
1043
  profileSummary,
712
1044
  docSourceMapSummary,
713
1045
  relationGraphSummary,
1046
+ generatedDocumentationBindingProjection,
714
1047
  diagnostics,
715
1048
  "</aside>",
716
1049
  "<main class=\"hia-main hia-project-main\">",
@@ -807,6 +1140,7 @@ function renderProjectEntry(entry, locales, selectedLocale) {
807
1140
  const profile = entry.profile ? renderProjectEntryProfile(entry.profile) : "";
808
1141
  const hierarchy = entry.hierarchy ? renderProjectEntryHierarchy(entry.hierarchy) : "";
809
1142
  const source = entry.source ? renderProjectEntrySource(entry.source) : "";
1143
+ const sourceUsability = entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability) : "";
810
1144
  const docSourceMap = entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap) : "";
811
1145
  const diagnostics = renderProjectDiagnostics(entry.diagnostics ?? []);
812
1146
  const searchText = createProjectEntrySearchText(entry);
@@ -821,11 +1155,240 @@ function renderProjectEntry(entry, locales, selectedLocale) {
821
1155
  profile,
822
1156
  hierarchy,
823
1157
  source,
1158
+ sourceUsability,
824
1159
  docSourceMap,
825
1160
  diagnostics,
826
1161
  "</article>"
827
1162
  ].join("");
828
1163
  }
1164
+ /**
1165
+ * 按固定 section order 渲染显式 IA topic;不适用 section 可省略,但 coverage/provenance 明示 unavailable。
1166
+ * Renders an explicit IA topic in fixed section order; inapplicable sections may be omitted while coverage/provenance state unavailability explicitly.
1167
+ */
1168
+ function renderProjectSemanticTopic(entry, projectInput, locales, selectedLocale, portalContext, includeMemberBodies) {
1169
+ return renderProjectSemanticTopicInternal(entry, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, new Set());
1170
+ }
1171
+ /** 递归 member projection 保持 cycle-safe;cycle 时回退 canonical link。Recursive member projection is cycle-safe and falls back to canonical links on cycles. */
1172
+ function renderProjectSemanticTopicInternal(entry, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, ancestors) {
1173
+ const labels = portalContext.labels;
1174
+ const nextAncestors = new Set(ancestors);
1175
+ nextAncestors.add(entry.id);
1176
+ const members = collectProjectEntryMembers(entry, projectInput.entries);
1177
+ const sections = [
1178
+ renderProjectTopicSection("summary", labels.summary, renderProjectEntrySummary(entry, locales, selectedLocale)),
1179
+ renderProjectTopicSection("declaration", labels.declaration, entry.signature ? `<pre class="hia-signature"><code>${escapeHtml(entry.signature)}</code></pre>` : ""),
1180
+ renderProjectTopicSection("metadata", labels.metadata, renderProjectTopicMetadata(entry, projectInput.project.productVersion)),
1181
+ renderProjectTopicSection("contract", labels.contract, renderProjectTopicContract(entry)),
1182
+ renderProjectTopicSection("coverage", labels.coverage, renderProjectTopicCoverage(projectInput.documentationContinuity, projectInput.ownerAdoption, labels)),
1183
+ renderProjectTopicSection("provenance", labels.provenance, renderProjectTopicProvenance(projectInput.documentationContinuity, projectInput.ownerAdoption, labels)),
1184
+ renderProjectTopicSection("members", labels.members, renderProjectTopicMembers(members, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, nextAncestors)),
1185
+ renderProjectTopicSection("relations", labels.relations, renderProjectTopicRelations(entry, projectInput.relationGraph)),
1186
+ renderProjectTopicSection("source", labels.source, renderProjectTopicSource(entry, portalContext.sourceCommentProjection)),
1187
+ renderProjectTopicSection("diagnostics", labels.diagnostics, renderProjectTopicDiagnostics(entry.diagnostics ?? []))
1188
+ ].join("");
1189
+ const searchText = createProjectEntrySearchText(entry);
1190
+ return [
1191
+ `<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)}">`,
1192
+ `<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>`,
1193
+ sections,
1194
+ "</article>"
1195
+ ].join("");
1196
+ }
1197
+ /** 空 section 不输出,从而保持“按适用性呈现”。Omits empty sections so topics remain applicability-aware. */
1198
+ function renderProjectTopicSection(section, label, body) {
1199
+ return body
1200
+ ? `<section class="hia-project-topic-section" data-hia-topic-section="${section}"><h3>${escapeHtml(label)}</h3>${body}</section>`
1201
+ : "";
1202
+ }
1203
+ /** metadata 只含公开 entry/project facts;关系由 relations section 独立承载。Metadata contains public entry/project facts only; relations stay in their own section. */
1204
+ function renderProjectTopicMetadata(entry, productVersion) {
1205
+ const items = [
1206
+ `<dt>Kind</dt><dd>${escapeHtml(entry.kind)}</dd>`,
1207
+ `<dt>View</dt><dd>${escapeHtml(entry.view)}</dd>`,
1208
+ productVersion ? `<dt>Product Version</dt><dd>${escapeHtml(productVersion)}</dd>` : "",
1209
+ entry.input ? `<dt>Input</dt><dd>${escapeHtml(entry.input.kind)}</dd>` : "",
1210
+ entry.input?.path ? `<dt>Input Path</dt><dd>${escapeHtml(entry.input.path)}</dd>` : "",
1211
+ entry.profile ? `<dt>Profile</dt><dd>${escapeHtml(entry.profile.profileId)}${entry.profile.profileVersion ? `@${escapeHtml(entry.profile.profileVersion)}` : ""}</dd>` : "",
1212
+ entry.hierarchy?.assembly ? `<dt>Assembly</dt><dd>${escapeHtml(entry.hierarchy.assembly)}</dd>` : "",
1213
+ entry.hierarchy?.namespace ? `<dt>Namespace</dt><dd>${escapeHtml(entry.hierarchy.namespace)}</dd>` : "",
1214
+ entry.hierarchy?.containingType ? `<dt>Containing Type</dt><dd>${escapeHtml(entry.hierarchy.containingType)}</dd>` : "",
1215
+ entry.hierarchy?.symbolDocumentationId ? `<dt>Documentation ID</dt><dd>${escapeHtml(entry.hierarchy.symbolDocumentationId)}</dd>` : ""
1216
+ ].join("");
1217
+ return `<dl class="hia-project-meta">${items}</dl>`;
1218
+ }
1219
+ /** contract section 与 input locator 分离,避免 path 被误当 contract identity。Separates contract identity from the input locator so paths are not mistaken for contracts. */
1220
+ function renderProjectTopicContract(entry) {
1221
+ if (!entry.input?.contract && !entry.input?.contractVersion && !entry.input?.artifactId) {
1222
+ return "";
1223
+ }
1224
+ const items = [
1225
+ entry.input.contract ? `<dt>Contract</dt><dd>${escapeHtml(entry.input.contract)}</dd>` : "",
1226
+ entry.input.contractVersion ? `<dt>Version</dt><dd>${escapeHtml(entry.input.contractVersion)}</dd>` : "",
1227
+ entry.input.artifactId ? `<dt>Artifact</dt><dd>${escapeHtml(entry.input.artifactId)}</dd>` : ""
1228
+ ].join("");
1229
+ return `<dl class="hia-project-meta">${items}</dl>`;
1230
+ }
1231
+ /** continuity 缺失时不猜测成功,明确输出 unavailable。Never guesses continuity success; absence is rendered as unavailable. */
1232
+ function renderProjectTopicCoverage(continuity, ownerAdoption, labels) {
1233
+ if (!continuity && !ownerAdoption) {
1234
+ return `<p class="hia-project-unavailable">${escapeHtml(labels.unavailable)}</p>`;
1235
+ }
1236
+ return [
1237
+ "<dl class=\"hia-project-meta\">",
1238
+ ...(continuity ? [
1239
+ `<dt>Continuity Status</dt><dd>${escapeHtml(continuity.status)}</dd>`,
1240
+ `<dt>Entries</dt><dd>${escapeHtml(String(continuity.entries.baselineCount))} → ${escapeHtml(String(continuity.entries.currentCount))}</dd>`,
1241
+ `<dt>Added / Removed / Unchanged</dt><dd>${escapeHtml(String(continuity.entries.addedCount))} / ${escapeHtml(String(continuity.entries.removedCount))} / ${escapeHtml(String(continuity.entries.unchangedCount))}</dd>`,
1242
+ `<dt>Required Outputs</dt><dd>${continuity.requiredOutputsPreserved ? "preserved" : "not-preserved"}</dd>`
1243
+ ] : []),
1244
+ ...(ownerAdoption ? [
1245
+ `<dt>Owner Review Readiness</dt><dd>${escapeHtml(ownerAdoption.status)}</dd>`,
1246
+ `<dt>Owner Input / Consent</dt><dd>${ownerAdoption.ownerInput.submitted ? "submitted" : "not-submitted"} / ${escapeHtml(ownerAdoption.ownerInput.consent)}</dd>`,
1247
+ `<dt>Contract References</dt><dd>${escapeHtml(String(ownerAdoption.contracts.providedCount))} / ${escapeHtml(String(ownerAdoption.contracts.requiredCount))}</dd>`,
1248
+ ...(ownerAdoption.workspaceHandoff ? [
1249
+ `<dt>Repository Owners / Handoff Edges</dt><dd>${escapeHtml(String(ownerAdoption.workspaceHandoff.repositoryOwnerCount))} / ${escapeHtml(String(ownerAdoption.workspaceHandoff.handoffEdgeCount))}</dd>`
1250
+ ] : [])
1251
+ ] : []),
1252
+ "</dl>"
1253
+ ].join("");
1254
+ }
1255
+ /** provenance 只显示 exact contract 与三维 semantics,不回读 evidence body。Provenance shows only the exact contract and three semantic dimensions, without reading evidence bodies. */
1256
+ function renderProjectTopicProvenance(continuity, ownerAdoption, labels) {
1257
+ if (!continuity && !ownerAdoption) {
1258
+ return `<p class="hia-project-unavailable">${escapeHtml(labels.unavailable)}</p>`;
1259
+ }
1260
+ return [
1261
+ "<dl class=\"hia-project-meta\">",
1262
+ ...(continuity ? [
1263
+ `<dt>Continuity Contract</dt><dd>${escapeHtml(continuity.contract)}@${escapeHtml(continuity.contractVersion)}</dd>`,
1264
+ `<dt>Continuity Resolution</dt><dd>${escapeHtml(continuity.semantics.resolution)}</dd>`,
1265
+ `<dt>Continuity Confidence</dt><dd>${escapeHtml(continuity.semantics.confidence)}</dd>`,
1266
+ `<dt>Continuity Provenance</dt><dd>${escapeHtml(continuity.semantics.provenance)}</dd>`
1267
+ ] : []),
1268
+ ...(ownerAdoption ? [
1269
+ `<dt>Owner Kit Contract</dt><dd>${escapeHtml(ownerAdoption.contract)}@${escapeHtml(ownerAdoption.contractVersion)}</dd>`,
1270
+ `<dt>Owner Kit Resolution</dt><dd>${escapeHtml(ownerAdoption.semantics.resolution)}</dd>`,
1271
+ `<dt>Owner Kit Confidence</dt><dd>${escapeHtml(ownerAdoption.semantics.confidence)}</dd>`,
1272
+ `<dt>Owner Kit Provenance</dt><dd>${escapeHtml(ownerAdoption.semantics.provenance)}</dd>`
1273
+ ] : []),
1274
+ "</dl>"
1275
+ ].join("");
1276
+ }
1277
+ /** direct members 只通过 explicit symbol relation 收集。Collects direct members only through explicit symbol relations. */
1278
+ function collectProjectEntryMembers(entry, entries) {
1279
+ if (!entry.symbolId) {
1280
+ return [];
1281
+ }
1282
+ return entries
1283
+ .filter((candidate) => candidate.hierarchy?.parentSymbolId === entry.symbolId)
1284
+ .sort(compareProjectNavigationEntries);
1285
+ }
1286
+ /** separate 输出 canonical links;with-parent 输出嵌套完整 topic,并对 cycle 回退 link。Separate mode emits canonical links; with-parent emits nested topics with cycle-safe link fallback. */
1287
+ function renderProjectTopicMembers(members, projectInput, locales, selectedLocale, portalContext, includeMemberBodies, ancestors) {
1288
+ if (members.length === 0) {
1289
+ return "";
1290
+ }
1291
+ if (!includeMemberBodies) {
1292
+ return `<ul class="hia-project-member-list">${members.map((member) => `<li><a href="${escapeHtml(createProjectEntryContentPath(member.id))}#${escapeHtml(member.id)}">${escapeHtml(member.name)}</a></li>`).join("")}</ul>`;
1293
+ }
1294
+ return `<div class="hia-project-member-topics">${members.map((member) => {
1295
+ if (ancestors.has(member.id)) {
1296
+ return `<p><a href="${escapeHtml(createProjectEntryContentPath(member.id))}#${escapeHtml(member.id)}">${escapeHtml(member.name)}</a></p>`;
1297
+ }
1298
+ return renderProjectSemanticTopicInternal(member, projectInput, locales, selectedLocale, portalContext, true, ancestors);
1299
+ }).join("")}</div>`;
1300
+ }
1301
+ /** inheritance/implements 与 project relation graph 都只进入 relations section。Inheritance, implements, and project graph edges appear only in the relations section. */
1302
+ function renderProjectTopicRelations(entry, relationGraph) {
1303
+ const semanticItems = [
1304
+ ...(entry.hierarchy?.baseTypeIds ?? []).map((id) => `<li><span class="hia-kind">inherits</span> ${escapeHtml(id)}</li>`),
1305
+ ...(entry.hierarchy?.interfaceIds ?? []).map((id) => `<li><span class="hia-kind">implements</span> ${escapeHtml(id)}</li>`)
1306
+ ];
1307
+ const entryNodeIds = new Set(relationGraph?.nodes.filter((node) => node.entryId === entry.id).map((node) => node.id) ?? []);
1308
+ const graphItems = relationGraph?.relations
1309
+ .filter((relation) => relation.entryId === entry.id || entryNodeIds.has(relation.from) || entryNodeIds.has(relation.to))
1310
+ .map((relation) => `<li><span class="hia-kind">${escapeHtml(relation.kind)}</span> ${escapeHtml(relation.label)}</li>`) ?? [];
1311
+ const items = [...semanticItems, ...graphItems].join("");
1312
+ return items ? `<ul class="hia-project-relation-list">${items}</ul>` : "";
1313
+ }
1314
+ /** source 与 doc-source-map 保持既有 privacy policy;本函数不新增 source body。Source and doc-source-map retain the existing privacy policy; this function adds no source body. */
1315
+ function renderProjectTopicSource(entry, options) {
1316
+ return [
1317
+ entry.source ? renderProjectEntrySource(entry.source, false) : "",
1318
+ entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability, false) : "",
1319
+ entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap, false) : "",
1320
+ entry.sourceCommentProjection && options ? renderProjectSourceCommentProjection(entry.sourceCommentProjection, options) : ""
1321
+ ].join("");
1322
+ }
1323
+ /**
1324
+ * @lang zh-CN
1325
+ * 将 source-comment projection 缩减为 navigation allowlist;正文与 producer 的正文授权事实都不进入 index。
1326
+ *
1327
+ * @lang en
1328
+ * Reduces a source-comment projection to a navigation allowlist; neither bodies nor the producer body-authorization fact enters the index.
1329
+ */
1330
+ function selectProjectSourceCommentProjection(projection) {
1331
+ return {
1332
+ contract: projection.contract,
1333
+ contractVersion: projection.contractVersion,
1334
+ defaultLocale: projection.defaultLocale,
1335
+ entryCount: projection.entries.length,
1336
+ privacy: {
1337
+ projectedCommentTextIncluded: false,
1338
+ rawCommentIncluded: false,
1339
+ sourceBodyIncluded: false,
1340
+ sourcesContentPolicy: "none"
1341
+ },
1342
+ projectionId: projection.projectionId,
1343
+ requestedLocale: projection.requestedLocale,
1344
+ resolvedCount: projection.entries.filter((entry) => entry.resolution !== "missing").length,
1345
+ status: projection.status
1346
+ };
1347
+ }
1348
+ /**
1349
+ * @lang zh-CN
1350
+ * 渲染 metadata 与可选纯文本正文。正文必须同时得到 producer projection 与 renderer config 授权。
1351
+ *
1352
+ * @lang en
1353
+ * Renders metadata and optional plain-text bodies. Bodies require authorization from both the producer projection and renderer config.
1354
+ */
1355
+ function renderProjectSourceCommentProjection(projection, options) {
1356
+ const bodyAuthorized = options.contentPolicy === "explicit-projected-text"
1357
+ && projection.contentPolicy === "explicit-projected-text"
1358
+ && projection.privacy.projectedCommentTextIncluded;
1359
+ const metadata = [
1360
+ `<dt>Comment Contract</dt><dd>${escapeHtml(`${projection.contract}@${projection.contractVersion}`)}</dd>`,
1361
+ `<dt>Comment Locale</dt><dd>${escapeHtml(projection.requestedLocale)}</dd>`,
1362
+ `<dt>Comment Status</dt><dd>${escapeHtml(projection.status)}</dd>`,
1363
+ `<dt>Comment Entries</dt><dd>${escapeHtml(String(projection.entries.length))}</dd>`,
1364
+ `<dt>Source Content Policy</dt><dd>${escapeHtml(projection.privacy.sourcesContentPolicy)}</dd>`
1365
+ ].join("");
1366
+ const entries = projection.entries.map((entry) => {
1367
+ const range = entry.range
1368
+ ? `<dt>Range</dt><dd>${escapeHtml(`${entry.range.start.line}:${entry.range.start.column}-${entry.range.end.line}:${entry.range.end.column}`)}</dd>`
1369
+ : "";
1370
+ const body = bodyAuthorized && entry.projectedText !== undefined
1371
+ ? `<pre class="hia-source-comment"><code>${escapeHtml(entry.projectedText)}</code></pre>`
1372
+ : "";
1373
+ return [
1374
+ `<article class="hia-source-comment-entry" data-hia-source-comment-id="${escapeHtml(entry.commentId)}">`,
1375
+ `<dl class="hia-project-meta"><dt>Comment</dt><dd>${escapeHtml(entry.commentId)}</dd>`,
1376
+ `<dt>Resolution</dt><dd>${escapeHtml(entry.resolution)}</dd>`,
1377
+ `<dt>Confidence</dt><dd>${escapeHtml(entry.confidence)}</dd>`,
1378
+ `<dt>Provenance</dt><dd>${escapeHtml(entry.provenance.kind)}</dd>${range}</dl>`,
1379
+ body,
1380
+ "</article>"
1381
+ ].join("");
1382
+ }).join("");
1383
+ return `<section class="hia-source-section hia-source-comment-section"><dl class="hia-project-meta">${metadata}</dl>${entries}</section>`;
1384
+ }
1385
+ /** topic diagnostics 使用已有 structured diagnostic,空集合不输出。Topic diagnostics reuse structured diagnostics and omit an empty set. */
1386
+ function renderProjectTopicDiagnostics(diagnostics) {
1387
+ if (diagnostics.length === 0) {
1388
+ return "";
1389
+ }
1390
+ return `<ul>${diagnostics.map((diagnostic) => `<li>${escapeHtml(diagnostic.severity)}:${escapeHtml(diagnostic.code)} - ${escapeHtml(diagnostic.message)}</li>`).join("")}</ul>`;
1391
+ }
829
1392
  function renderProjectEntryHierarchy(hierarchy) {
830
1393
  const details = [
831
1394
  hierarchy.assembly ? `<dt>Assembly</dt><dd>${escapeHtml(hierarchy.assembly)}</dd>` : "",
@@ -866,7 +1429,7 @@ function renderProjectEntryProfile(profile) {
866
1429
  const version = profile.profileVersion ? `@${profile.profileVersion}` : "";
867
1430
  return `<p class="hia-project-profile">Profile ${escapeHtml(profile.profileId)}${escapeHtml(version)}</p>`;
868
1431
  }
869
- function renderProjectEntrySource(source) {
1432
+ function renderProjectEntrySource(source, includeHeading = true) {
870
1433
  const range = source.range ? `:${source.range.start.line}${source.range.end ? `-${source.range.end.line}` : ""}` : "";
871
1434
  const label = `${source.path}${range}`;
872
1435
  const sourceLabel = source.linkUrl
@@ -880,7 +1443,57 @@ function renderProjectEntrySource(source) {
880
1443
  ].join("");
881
1444
  const preview = source.preview ? renderProjectSourcePreview(source.preview, source.path) : "";
882
1445
  const fetchPreview = source.fetchUrl ? renderProjectSourceFetch(source) : "";
883
- return `<section class="hia-source-section"><h3>Source</h3><dl class="hia-project-meta">${sourceDetails}</dl>${preview}${fetchPreview}</section>`;
1446
+ const heading = includeHeading ? "<h3>Source</h3>" : "";
1447
+ return `<section class="hia-source-section">${heading}<dl class="hia-project-meta">${sourceDetails}</dl>${preview}${fetchPreview}</section>`;
1448
+ }
1449
+ /**
1450
+ * @lang zh-CN 只渲染 source-usability allowlist metadata,不生成 link、fetch request、preview 或 source body。
1451
+ * @lang en Renders only allowlisted source-usability metadata and creates no link, fetch request, preview, or source body.
1452
+ */
1453
+ function renderProjectEntrySourceUsability(sourceUsability, includeHeading = true) {
1454
+ const projectIdentity = sourceUsability.projectIdentity;
1455
+ const details = [
1456
+ `<dt>Resolution</dt><dd>${escapeHtml(sourceUsability.resolution)}</dd>`,
1457
+ `<dt>Confidence</dt><dd>${escapeHtml(sourceUsability.confidence)}</dd>`,
1458
+ projectIdentity ? `<dt>Project</dt><dd>${escapeHtml(projectIdentity.path)}</dd>` : "",
1459
+ projectIdentity ? `<dt>Project Identity</dt><dd>${escapeHtml(projectIdentity.id)}</dd>` : "",
1460
+ projectIdentity ? `<dt>Identity Policy</dt><dd>${escapeHtml(projectIdentity.policy)}</dd>` : "",
1461
+ `<dt>Provenance</dt><dd>${escapeHtml(`${sourceUsability.provenance.producer}:${sourceUsability.provenance.activity}`)}</dd>`,
1462
+ `<dt>Source Content Policy</dt><dd>${escapeHtml(sourceUsability.privacy.sourcesContentPolicy)}</dd>`
1463
+ ].join("");
1464
+ const heading = includeHeading ? "<h3>Source Usability</h3>" : "";
1465
+ return `<section class="hia-source-section hia-source-usability-section">${heading}<dl class="hia-project-meta">${details}</dl></section>`;
1466
+ }
1467
+ /**
1468
+ * @lang zh-CN 将 runtime source-usability 输入收窄为 navigation index allowlist,额外字段不会跨越 privacy boundary。
1469
+ * @lang en Narrows runtime source-usability input to the navigation-index allowlist so extra fields cannot cross the privacy boundary.
1470
+ */
1471
+ function selectProjectSourceUsability(sourceUsability) {
1472
+ return {
1473
+ relationId: sourceUsability.relationId,
1474
+ resolution: sourceUsability.resolution,
1475
+ confidence: sourceUsability.confidence,
1476
+ provenance: {
1477
+ producer: sourceUsability.provenance.producer,
1478
+ activity: sourceUsability.provenance.activity,
1479
+ contract: sourceUsability.provenance.contract,
1480
+ contractVersion: sourceUsability.provenance.contractVersion
1481
+ },
1482
+ ...(sourceUsability.projectIdentity
1483
+ ? {
1484
+ projectIdentity: {
1485
+ id: sourceUsability.projectIdentity.id,
1486
+ path: sourceUsability.projectIdentity.path,
1487
+ policy: sourceUsability.projectIdentity.policy
1488
+ }
1489
+ }
1490
+ : {}),
1491
+ privacy: {
1492
+ sourcesContentPolicy: "none",
1493
+ sourcePreviewPolicy: "none",
1494
+ embedsSourcesContent: false
1495
+ }
1496
+ };
884
1497
  }
885
1498
  function renderProjectSourceFetch(source) {
886
1499
  const startLine = source.range?.start.line ?? 1;
@@ -901,7 +1514,7 @@ function renderProjectSourceFetch(source) {
901
1514
  "</details>"
902
1515
  ].join("");
903
1516
  }
904
- function renderProjectEntryDocSourceMap(docSourceMap) {
1517
+ function renderProjectEntryDocSourceMap(docSourceMap, includeHeading = true) {
905
1518
  const sourceRange = docSourceMap.sourceRange ? `:${docSourceMap.sourceRange.start.line}${docSourceMap.sourceRange.end ? `-${docSourceMap.sourceRange.end.line}` : ""}` : "";
906
1519
  const diagnostics = docSourceMap.diagnostics && docSourceMap.diagnostics.length > 0
907
1520
  ? `<dt>Diagnostics</dt><dd>${escapeHtml(docSourceMap.diagnostics.join(", "))}</dd>`
@@ -918,7 +1531,8 @@ function renderProjectEntryDocSourceMap(docSourceMap) {
918
1531
  diagnostics
919
1532
  ].join("");
920
1533
  const actions = renderProjectDocSourceMapOpenRequests(docSourceMap);
921
- return `<section class="hia-source-section"><h3>Doc Source Map</h3><dl class="hia-project-meta">${details}</dl>${actions}</section>`;
1534
+ const heading = includeHeading ? "<h3>Doc Source Map</h3>" : "";
1535
+ return `<section class="hia-source-section">${heading}<dl class="hia-project-meta">${details}</dl>${actions}</section>`;
922
1536
  }
923
1537
  function renderProjectSourcePreview(preview, fallbackPath) {
924
1538
  if (!preview.content) {
@@ -986,6 +1600,60 @@ function renderProjectDocSourceMaps(docSourceMaps) {
986
1600
  .join("");
987
1601
  return `<section class="hia-project-summary"><h2>Doc Source Maps</h2><ul>${items}</ul></section>`;
988
1602
  }
1603
+ /**
1604
+ * 中文:渲染由 source-linkage index 产生的一对多 generated binding 只读关系。
1605
+ * English: Renders the read-only one-to-many generated-binding relation created
1606
+ * by the source-linkage index.
1607
+ *
1608
+ * @remarks
1609
+ * 中文:这里不回读 sidecar、不展开 source body,也不显示 locals/digest;页面只显示
1610
+ * 安全投影里的 source intent、受限 member path、实例键状态、targets 与质量维度。
1611
+ * English: This renderer does not read a sidecar back, expand source bodies, or
1612
+ * display locals/digests; it shows only safe source intent, restricted member
1613
+ * paths, instance-key state, targets, and quality dimensions.
1614
+ */
1615
+ function renderProjectGeneratedDocumentationBindingProjection(projection) {
1616
+ if (!projection) {
1617
+ return "";
1618
+ }
1619
+ const summaryItems = [
1620
+ `<li><span>Bindings / 绑定</span><strong>${escapeHtml(String(projection.summary.bindingCount))}</strong></li>`,
1621
+ `<li><span>Expansions / 展开</span><strong>${escapeHtml(String(projection.summary.expansionCount))}</strong></li>`,
1622
+ `<li><span>Targets / 目标</span><strong>${escapeHtml(String(projection.summary.targetCount))}</strong></li>`,
1623
+ `<li><span>Diagnostics / 诊断</span><strong>${escapeHtml(String(projection.summary.diagnosticCount))}</strong></li>`,
1624
+ `<li><span>sourcesContent</span><strong>${escapeHtml(projection.privacy.sourcesContentPolicy)}</strong></li>`
1625
+ ].join("");
1626
+ const bindings = projection.bindings.map((binding) => {
1627
+ const memberPath = binding.bindingRef.memberPath.join(".") || binding.bindingRef.rootDeclarationId;
1628
+ const quality = `${binding.quality.resolutionKind} / ${binding.quality.confidence} / ${binding.quality.provenanceCoverage}`;
1629
+ const expansions = binding.expansions
1630
+ .map((expansion) => {
1631
+ const key = expansion.instanceKey.displayKey ?? expansion.instanceKey.status;
1632
+ return `<li>${escapeHtml(expansion.id)} · key=${escapeHtml(key)} · ${escapeHtml(expansion.quality.resolutionKind)} / ${escapeHtml(expansion.quality.confidence)} / ${escapeHtml(expansion.quality.provenanceCoverage)} · ${escapeHtml(String(expansion.targetIds.length))} target(s)</li>`;
1633
+ })
1634
+ .join("");
1635
+ const targets = binding.targets
1636
+ .map((target) => `<li>${escapeHtml(target.id)} · ${escapeHtml(target.identity.kind)}${target.identity.selector ? ` · ${escapeHtml(target.identity.selector)}` : ""}</li>`)
1637
+ .join("");
1638
+ return [
1639
+ "<li>",
1640
+ `<strong>${escapeHtml(binding.id)}</strong>`,
1641
+ `<p>${escapeHtml(binding.sourceIntent.kind)}${binding.sourceIntent.field ? ` / ${escapeHtml(binding.sourceIntent.field)}` : ""} · ${escapeHtml(memberPath)} · ${escapeHtml(quality)}</p>`,
1642
+ `<p>scope=${escapeHtml(binding.scopeId)} · ${escapeHtml(binding.composition.relation)} / ${escapeHtml(binding.composition.mergePolicy)}</p>`,
1643
+ expansions ? `<details><summary>Expansions / 展开 (${escapeHtml(String(binding.expansions.length))})</summary><ul>${expansions}</ul></details>` : "",
1644
+ targets ? `<details><summary>Targets / 目标 (${escapeHtml(String(binding.targets.length))})</summary><ul>${targets}</ul></details>` : "",
1645
+ "</li>"
1646
+ ].join("");
1647
+ }).join("");
1648
+ return [
1649
+ "<section class=\"hia-project-summary hia-generated-binding-relations\">",
1650
+ "<h2>Generated Documentation Bindings / 生成式文档绑定</h2>",
1651
+ `<p>${escapeHtml(projection.contract)}@${escapeHtml(projection.contractVersion)} · ${escapeHtml(projection.status)}</p>`,
1652
+ `<ul class=\"hia-project-group-list\">${summaryItems}</ul>`,
1653
+ bindings ? `<ul class=\"hia-project-relation-list\">${bindings}</ul>` : "<p>No binding relations available.</p>",
1654
+ "</section>"
1655
+ ].join("");
1656
+ }
989
1657
  function renderProjectRelationGraphSummary(relationGraph) {
990
1658
  if (!relationGraph || relationGraph.relationCount === 0) {
991
1659
  return "";
@@ -1280,7 +1948,7 @@ function collectProjectNavigationGroups(entries) {
1280
1948
  ...collectProjectNavigationGroupsBy(entries, "source-root", (entry) => getProjectSourceRoot(entry.source?.path))
1281
1949
  ].sort(compareProjectNavigationGroups);
1282
1950
  }
1283
- function collectProjectNavigationTree(entries) {
1951
+ function collectProjectNavigationTree(entries, informationArchitecture) {
1284
1952
  return PROJECT_VIEW_ORDER
1285
1953
  .filter((view) => view !== "all")
1286
1954
  .flatMap((view) => {
@@ -1288,9 +1956,11 @@ function collectProjectNavigationTree(entries) {
1288
1956
  if (viewEntries.length === 0) {
1289
1957
  return [];
1290
1958
  }
1291
- const children = view === "dotnet"
1292
- ? collectDotNetNavigationTree(viewEntries)
1293
- : collectSemanticSourceNavigationTree(viewEntries);
1959
+ const children = informationArchitecture
1960
+ ? collectManifestSemanticNavigationTree(viewEntries, view)
1961
+ : view === "dotnet"
1962
+ ? collectDotNetNavigationTree(viewEntries)
1963
+ : collectSemanticSourceNavigationTree(viewEntries);
1294
1964
  return [{
1295
1965
  id: `view:${view}`,
1296
1966
  kind: "view",
@@ -1301,7 +1971,7 @@ function collectProjectNavigationTree(entries) {
1301
1971
  }];
1302
1972
  });
1303
1973
  }
1304
- function collectDotNetNavigationTree(entries) {
1974
+ function collectDotNetNavigationTree(entries, includeTypeRelations = true) {
1305
1975
  const roots = new Map();
1306
1976
  for (const entry of entries) {
1307
1977
  const parts = getDotNetNavigationParts(entry);
@@ -1327,7 +1997,7 @@ function collectDotNetNavigationTree(entries) {
1327
1997
  if (isDotNetTypeNavigationEntry(entry)) {
1328
1998
  typeNode.entryId = entry.id;
1329
1999
  assignProjectTreeEntryRefs(typeNode, entry);
1330
- if (entry.kind === "dotnet-type") {
2000
+ if (includeTypeRelations && entry.kind === "dotnet-type") {
1331
2001
  addDotNetInheritanceNodes(typeNode, entry);
1332
2002
  }
1333
2003
  continue;
@@ -1340,6 +2010,125 @@ function collectDotNetNavigationTree(entries) {
1340
2010
  }
1341
2011
  return sortProjectTreeNodes([...roots.values()].map(finalizeProjectTreeBuilder));
1342
2012
  }
2013
+ /**
2014
+ * 构造 manifest-only semantic prefix,再接既有语言 containment;显式 IA 不使用 source path 分组。
2015
+ * Builds a manifest-only semantic prefix followed by language containment; explicit IA never groups by source path.
2016
+ */
2017
+ function collectManifestSemanticNavigationTree(entries, view) {
2018
+ const semanticRoots = new Map();
2019
+ const groupedEntries = new Map();
2020
+ for (const entry of entries) {
2021
+ assertRenderProjectSemanticPath(entry.semanticPath);
2022
+ const path = entry.semanticPath ?? [];
2023
+ const key = path.length > 0
2024
+ ? path.map((segment) => `${segment.kind}:${segment.id}`).join("|")
2025
+ : `unscoped:${view}`;
2026
+ const group = groupedEntries.get(key) ?? { path, entries: [] };
2027
+ group.entries.push(entry);
2028
+ groupedEntries.set(key, group);
2029
+ }
2030
+ const unscopedChildren = [];
2031
+ for (const [groupKey, group] of [...groupedEntries.entries()].sort(([left], [right]) => compareStableText(left, right))) {
2032
+ const languageChildren = view === "dotnet"
2033
+ ? collectDotNetNavigationTree(group.entries, false)
2034
+ : collectSymbolContainmentNavigationTree(group.entries);
2035
+ const namespacedChildren = languageChildren.map((node) => namespaceProjectNavigationNode(node, `semantic:${groupKey}`));
2036
+ if (group.path.length === 0) {
2037
+ unscopedChildren.push(...namespacedChildren);
2038
+ continue;
2039
+ }
2040
+ let parentMap = semanticRoots;
2041
+ let parentBuilder;
2042
+ let qualifiedId = "semantic";
2043
+ for (const segment of group.path) {
2044
+ qualifiedId = `${qualifiedId}:${segment.kind}:${segment.id}`;
2045
+ const builder = getOrCreateProjectTreeChild(parentMap, qualifiedId, segment.kind, segment.label);
2046
+ for (const entry of group.entries) {
2047
+ addProjectTreeEntry(builder, entry);
2048
+ }
2049
+ parentBuilder = builder;
2050
+ parentMap = builder.childrenById;
2051
+ }
2052
+ if (parentBuilder) {
2053
+ parentBuilder.terminalChildren.push(...namespacedChildren);
2054
+ }
2055
+ }
2056
+ const semanticChildren = [...semanticRoots.values()].map(finalizeProjectTreeBuilder);
2057
+ return sortProjectTreeNodes([...semanticChildren, ...unscopedChildren]);
2058
+ }
2059
+ /** 非 DotNet 显式 IA 下只使用 symbol containment,不回退到 source-root/source-file。Non-.NET explicit IA uses symbol containment only, without source grouping fallback. */
2060
+ function collectSymbolContainmentNavigationTree(entries) {
2061
+ const roots = new Map();
2062
+ const nodesByEntryId = new Map();
2063
+ const entriesBySymbolId = new Map();
2064
+ for (const entry of entries) {
2065
+ if (entry.symbolId) {
2066
+ entriesBySymbolId.set(entry.symbolId, entry);
2067
+ }
2068
+ const entryNode = getOrCreateProjectTreeChild(nodesByEntryId, `entry:${entry.id}`, isProjectTypeLikeKind(entry.kind) ? "type" : "entry", entry.name);
2069
+ addProjectTreeEntry(entryNode, entry);
2070
+ entryNode.entryId = entry.id;
2071
+ assignProjectTreeEntryRefs(entryNode, entry);
2072
+ }
2073
+ for (const entry of entries) {
2074
+ const entryNode = nodesByEntryId.get(`entry:${entry.id}`);
2075
+ const parentEntry = entry.hierarchy?.parentSymbolId
2076
+ ? entriesBySymbolId.get(entry.hierarchy.parentSymbolId)
2077
+ : undefined;
2078
+ const parentNode = parentEntry ? nodesByEntryId.get(`entry:${parentEntry.id}`) : undefined;
2079
+ if (entryNode && parentEntry && parentNode && parentNode !== entryNode) {
2080
+ parentNode.childrenById.set(entryNode.id, entryNode);
2081
+ incrementProjectNavigationAncestorCounts(parentEntry, entriesBySymbolId, nodesByEntryId);
2082
+ }
2083
+ else if (entryNode) {
2084
+ roots.set(entryNode.id, entryNode);
2085
+ }
2086
+ }
2087
+ return sortProjectTreeNodes([...roots.values()].map(finalizeProjectTreeBuilder));
2088
+ }
2089
+ /** 为跨 semantic container 的 shard node id 增加 namespace,entry id 本身保持不变。Namespaces shard node ids across semantic containers while preserving entry identity. */
2090
+ function namespaceProjectNavigationNode(node, namespace) {
2091
+ return {
2092
+ ...node,
2093
+ id: `${namespace}:${node.id}`,
2094
+ ...(node.children
2095
+ ? { children: node.children.map((child) => namespaceProjectNavigationNode(child, namespace)) }
2096
+ : {})
2097
+ };
2098
+ }
2099
+ /** direct renderer API 的 semantic path 同样 fail closed,防止绕过 manifest validator。Semantic paths passed directly to the renderer also fail closed. */
2100
+ function assertRenderProjectSemanticPath(path) {
2101
+ if (!path) {
2102
+ return;
2103
+ }
2104
+ if (!Array.isArray(path) || path.length === 0) {
2105
+ throw new TypeError("HIA_PORTAL_IA_SEMANTIC_PATH_INVALID: semanticPath must be a non-empty array.");
2106
+ }
2107
+ const seen = new Set();
2108
+ for (const segment of path) {
2109
+ const exactSegment = isExactObject(segment, ["kind", "id", "label"]);
2110
+ const normalizedLabel = exactSegment && typeof segment.label === "string"
2111
+ ? segment.label.replaceAll("\\", "/")
2112
+ : "";
2113
+ const safeLabel = exactSegment
2114
+ && Boolean(segment.label)
2115
+ && segment.label.length <= 160
2116
+ && !/[\u0000-\u001F\u007F]/u.test(segment.label)
2117
+ && !normalizedLabel.includes("../")
2118
+ && normalizedLabel !== ".."
2119
+ && !normalizedLabel.startsWith("/")
2120
+ && !/^[A-Za-z]:\//u.test(normalizedLabel)
2121
+ && !/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(normalizedLabel);
2122
+ if (!exactSegment
2123
+ || !DOCUMENTATION_PORTAL_SEMANTIC_PATH_KINDS.includes(segment.kind)
2124
+ || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(segment.id)
2125
+ || !safeLabel
2126
+ || seen.has(segment.id)) {
2127
+ throw new TypeError("HIA_PORTAL_IA_SEMANTIC_PATH_INVALID: semanticPath must contain unique, public kind/id/label segments.");
2128
+ }
2129
+ seen.add(segment.id);
2130
+ }
2131
+ }
1343
2132
  function addDotNetInheritanceNodes(typeNode, entry) {
1344
2133
  for (const baseTypeId of entry.hierarchy?.baseTypeIds ?? []) {
1345
2134
  const relationNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:base:${slugProjectGroupLabel(baseTypeId)}`, "relation", `Base: ${baseTypeId.replace(/^T:/u, "")}`);
@@ -1428,7 +2217,8 @@ function getOrCreateProjectTreeChild(map, id, kind, label) {
1428
2217
  entryCount: 0,
1429
2218
  views: new Set(),
1430
2219
  children: [],
1431
- childrenById: new Map()
2220
+ childrenById: new Map(),
2221
+ terminalChildren: []
1432
2222
  };
1433
2223
  map.set(id, created);
1434
2224
  return created;
@@ -1450,7 +2240,10 @@ function assignProjectTreeSourcePath(node, sourcePath) {
1450
2240
  }
1451
2241
  function finalizeProjectTreeBuilder(node) {
1452
2242
  const childBuilders = node.childrenById.size > 0 ? [...node.childrenById.values()] : node.children;
1453
- const children = sortProjectTreeNodes(childBuilders.map(finalizeProjectTreeBuilder));
2243
+ const children = sortProjectTreeNodes([
2244
+ ...childBuilders.map(finalizeProjectTreeBuilder),
2245
+ ...node.terminalChildren
2246
+ ]);
1454
2247
  return {
1455
2248
  id: node.id,
1456
2249
  kind: node.kind,
@@ -1476,28 +2269,40 @@ function projectTreeKindOrder(kind) {
1476
2269
  if (kind === "view") {
1477
2270
  return 0;
1478
2271
  }
1479
- if (kind === "surface" || kind === "project") {
2272
+ if (kind === "repository") {
2273
+ return 1;
2274
+ }
2275
+ if (kind === "package") {
1480
2276
  return 2;
1481
2277
  }
1482
- if (kind === "namespace") {
2278
+ if (kind === "layer") {
1483
2279
  return 3;
1484
2280
  }
1485
- if (kind === "type") {
2281
+ if (kind === "contract" || kind === "operation") {
1486
2282
  return 4;
1487
2283
  }
1488
- if (kind === "relation") {
2284
+ if (kind === "surface" || kind === "project") {
1489
2285
  return 5;
1490
2286
  }
1491
2287
  if (kind === "assembly") {
1492
- return 1;
2288
+ return 6;
2289
+ }
2290
+ if (kind === "namespace") {
2291
+ return 7;
2292
+ }
2293
+ if (kind === "type") {
2294
+ return 8;
2295
+ }
2296
+ if (kind === "relation") {
2297
+ return 9;
1493
2298
  }
1494
2299
  if (kind === "source-root") {
1495
- return 6;
2300
+ return 10;
1496
2301
  }
1497
2302
  if (kind === "source-file") {
1498
- return 7;
2303
+ return 11;
1499
2304
  }
1500
- return 8;
2305
+ return 12;
1501
2306
  }
1502
2307
  function getDotNetNavigationParts(entry) {
1503
2308
  const fallback = getDotNetNonAssemblyNavigationParts(entry);