@hia-doc/renderer-html 0.1.2 → 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.
@@ -110,7 +256,11 @@ function applyProjectSourcePresentationPolicy(projectInput, options) {
110
256
  ...(previewDefaultExpanded !== undefined ? { defaultExpanded: previewDefaultExpanded } : {})
111
257
  }
112
258
  } : {}),
113
- ...(presentation === "fetch" && fetchUrl ? { fetchUrl } : {})
259
+ ...(presentation === "fetch" && fetchUrl ? {
260
+ fetchUrl,
261
+ fetchTrigger: options.projectSite?.source?.fetchTrigger ?? entry.source.fetchTrigger ?? "on-expand",
262
+ fetchMaxLines: options.projectSite?.source?.maxLines ?? entry.source.fetchMaxLines ?? 400
263
+ } : {})
114
264
  };
115
265
  return {
116
266
  ...entry,
@@ -157,6 +307,7 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
157
307
  name: projectInput.project.name,
158
308
  views,
159
309
  entryCounts: countEntriesByView(projectInput.entries),
310
+ ...(projectInput.project.productVersion ? { productVersion: projectInput.project.productVersion } : {}),
160
311
  navigationIndex: {
161
312
  contract: navigationIndex.contract,
162
313
  contractVersion: navigationIndex.contractVersion,
@@ -165,6 +316,18 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
165
316
  },
166
317
  ...(projectInput.profiles && projectInput.profiles.length > 0 ? { profiles: projectInput.profiles } : {}),
167
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
+ : {}),
168
331
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
169
332
  ? {
170
333
  relationGraph: {
@@ -175,11 +338,14 @@ function createProjectManifest(projectInput, files, pageTitle, options, navigati
175
338
  path: "project-index.json"
176
339
  }
177
340
  }
341
+ : {}),
342
+ ...(navigationIndex.site?.informationArchitecture
343
+ ? { informationArchitecture: navigationIndex.site.informationArchitecture }
178
344
  : {})
179
345
  }
180
346
  };
181
347
  }
182
- function createProjectNavigationIndex(projectInput, pageTitle, options) {
348
+ function createProjectNavigationIndex(projectInput, pageTitle, options, portalContext) {
183
349
  const projectId = projectInput.project.id ?? `project:${projectInput.project.name}`;
184
350
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
185
351
  return {
@@ -192,7 +358,8 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
192
358
  locales: localeModel.locales,
193
359
  name: projectInput.project.name,
194
360
  title: pageTitle,
195
- views: collectProjectViews(projectInput.entries)
361
+ views: collectProjectViews(projectInput.entries),
362
+ ...(projectInput.project.productVersion ? { productVersion: projectInput.project.productVersion } : {})
196
363
  },
197
364
  entries: projectInput.entries
198
365
  .map((entry) => ({
@@ -206,16 +373,32 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
206
373
  ...(entry.profile ? { profile: entry.profile } : {}),
207
374
  ...(entry.input ? { input: entry.input } : {}),
208
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
+ : {}),
209
380
  ...(entry.symbolId ? { symbolId: entry.symbolId } : {}),
210
381
  ...(entry.hierarchy ? { hierarchy: entry.hierarchy } : {}),
211
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
+ : {}),
212
390
  ...(entry.docSourceMap ? { docSourceMap: entry.docSourceMap } : {})
213
391
  }))
214
392
  .sort(compareProjectNavigationEntries),
215
393
  groups: collectProjectNavigationGroups(projectInput.entries),
216
- navigationTree: collectProjectNavigationTree(projectInput.entries),
394
+ navigationTree: applyProjectNavigationPresentationPaths(collectProjectNavigationTree(projectInput.entries, portalContext.informationArchitecture), projectInput.entries, portalContext.informationArchitecture),
217
395
  profiles: [...(projectInput.profiles ?? [])].sort(compareProjectProfiles),
218
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 } : {}),
219
402
  site: {
220
403
  layout: options.projectSite?.layout ?? "split-site",
221
404
  ...(options.projectSite?.layout === "single-page" ? {} : {
@@ -223,7 +406,10 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
223
406
  searchIndexPath: "search/index.json",
224
407
  relationIndexPath: "relations/project.json"
225
408
  }),
226
- sourcePresentation: options.projectSite?.source?.presentation ?? "link"
409
+ sourcePresentation: options.projectSite?.source?.presentation ?? "link",
410
+ ...(portalContext.informationArchitecture
411
+ ? { informationArchitecture: portalContext.informationArchitecture }
412
+ : {})
227
413
  },
228
414
  ...(projectInput.relationGraph && projectInput.relationGraph.relationCount > 0
229
415
  ? { relationGraph: projectInput.relationGraph }
@@ -234,16 +420,17 @@ function createProjectNavigationIndex(projectInput, pageTitle, options) {
234
420
  * 生成大型项目默认使用的 split-site 文件集合;入口页只保留应用壳。
235
421
  * Generates the split-site file set used by large projects by default; the entry page only keeps the application shell.
236
422
  */
237
- function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options) {
423
+ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, options, portalContext) {
238
424
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
425
+ const informationArchitecture = portalContext.informationArchitecture;
239
426
  const files = [
240
427
  {
241
428
  path: "index.html",
242
- contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options),
429
+ contents: renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext),
243
430
  contentType: "text/html; charset=utf-8",
244
431
  role: "entry"
245
432
  },
246
- ...createProjectNavigationShardFiles(navigationIndex.navigationTree),
433
+ ...createProjectNavigationShardFiles(navigationIndex.navigationTree, informationArchitecture?.loadingStrategy ?? "lazy"),
247
434
  {
248
435
  path: "search/index.json",
249
436
  contents: `${JSON.stringify({
@@ -255,6 +442,12 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
255
442
  kind: entry.kind,
256
443
  view: entry.view,
257
444
  contentPath: createProjectEntryContentPath(entry.id),
445
+ ...(informationArchitecture
446
+ ? {
447
+ presentationPath: createProjectEntryPresentationPath(entry, projectInput.entries, informationArchitecture),
448
+ memberAnchor: entry.id
449
+ }
450
+ : {}),
258
451
  searchText: createProjectEntrySearchText(entry)
259
452
  }))
260
453
  }, null, 2)}\n`,
@@ -268,19 +461,60 @@ function createProjectSplitSiteFiles(pageTitle, projectInput, navigationIndex, o
268
461
  role: "index"
269
462
  }
270
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>
271
466
  for (const entry of projectInput.entries) {
272
467
  files.push({
273
468
  path: createProjectEntryContentPath(entry.id),
274
- 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),
275
472
  contentType: "text/html; charset=utf-8",
276
473
  role: "asset"
277
474
  });
278
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
+ }
279
500
  return files;
280
501
  }
281
- function createProjectNavigationShardFiles(nodes) {
502
+ function createProjectNavigationShardFiles(nodes, loadingStrategy) {
282
503
  const files = [];
283
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
+ }
284
518
  const emitChildren = (nodeId, children, root = false) => {
285
519
  const shardPath = root ? "navigation/root.json" : createProjectNavigationChildrenPath(nodeId);
286
520
  if (emittedPaths.has(shardPath)) {
@@ -314,12 +548,93 @@ function toLazyProjectNavigationNode(node) {
314
548
  ...(node.children && node.children.length > 0
315
549
  ? { childrenPath: createProjectNavigationChildrenPath(node.id) }
316
550
  : {}),
317
- ...(node.entryId ? { contentPath: createProjectEntryContentPath(node.entryId) } : {})
551
+ ...(node.entryId && !node.contentPath ? { contentPath: createProjectEntryContentPath(node.entryId) } : {})
318
552
  };
319
553
  }
320
554
  function createProjectEntryContentPath(entryId) {
321
555
  return `entries/${stableProjectArtifactName(entryId)}.html`;
322
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
+ }
323
638
  function createProjectNavigationChildrenPath(nodeId) {
324
639
  return `navigation/${stableProjectArtifactName(nodeId)}.json`;
325
640
  }
@@ -381,33 +696,12 @@ function renderIndexHtml(pageTitle, document, options) {
381
696
  "</html>"
382
697
  ].join("");
383
698
  }
384
- function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
699
+ function renderProjectSplitSiteHtml(pageTitle, projectInput, options, portalContext) {
385
700
  const projectName = projectInput.project.title ?? projectInput.project.name;
386
701
  const localeModel = resolveProjectLocaleModel(projectInput, options.locale);
387
702
  const views = collectProjectViews(projectInput.entries);
388
703
  const entryCounts = countEntriesByView(projectInput.entries);
389
- const selectedChinese = localeModel.selectedLocale.toLowerCase().startsWith("zh");
390
- const labels = selectedChinese
391
- ? {
392
- hierarchy: "层级导航",
393
- loading: "正在加载文档导航...",
394
- open: "打开",
395
- relations: "项目关系",
396
- select: "请从左侧层级树选择一个文档节点。",
397
- search: "搜索",
398
- searchPlaceholder: "名称、类型、源码或选择器",
399
- requiresServer: "按需加载站点需要通过 HTTP(S) 提供;请使用本地静态服务器打开该目录。"
400
- }
401
- : {
402
- hierarchy: "Hierarchy",
403
- loading: "Loading documentation navigation...",
404
- open: "Open",
405
- relations: "Project relations",
406
- select: "Select a documentation node from the hierarchy.",
407
- search: "Search",
408
- searchPlaceholder: "Name, kind, source, selector",
409
- requiresServer: "The lazy site must be served over HTTP(S); open this directory through a local static server."
410
- };
704
+ const labels = portalContext.labels;
411
705
  return [
412
706
  "<!doctype html>",
413
707
  `<html lang="${escapeHtml(localeModel.selectedLocale)}">`,
@@ -424,6 +718,7 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
424
718
  `<h1>${escapeHtml(projectName)}</h1>`,
425
719
  renderLocaleControl(localeModel.locales, localeModel.selectedLocale),
426
720
  renderProjectViewControl(views, entryCounts),
721
+ renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection),
427
722
  [
428
723
  "<label class=\"hia-project-search\">",
429
724
  `<span>${escapeHtml(labels.search)}</span>`,
@@ -436,16 +731,72 @@ function renderProjectSplitSiteHtml(pageTitle, projectInput, options) {
436
731
  `<main class="hia-main hia-project-main" data-hia-project-content><p class="hia-project-empty">${escapeHtml(labels.select)}</p></main>`,
437
732
  "</div>",
438
733
  `<script src="${escapeHtml(DEFAULT_THEME_JS_PATH)}"></script>`,
439
- renderProjectSplitSiteScript(labels.requiresServer, labels.open),
734
+ renderProjectSplitSiteScript(labels.requiresServer, labels.open, portalContext.informationArchitecture?.loadingStrategy ?? "lazy", labels.relations),
440
735
  "</body>",
441
736
  "</html>"
442
737
  ].join("");
443
738
  }
444
- function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
739
+ /**
740
+ * 生成 split-site 与 single-page 共用的 fetch 源码加载逻辑。
741
+ *
742
+ * @lang zh-CN 该脚本默认在 details 展开时加载源码,并保留 manual 按钮模式作为显式配置。
743
+ * @lang en Generates the shared fetch-source loader for split-site and single-page layouts, loading on details expansion by default while retaining an explicit manual button mode.
744
+ */
745
+ function renderProjectSourceFetchClientLines(rootExpression) {
746
+ return [
747
+ " async function loadSourceFetch(details) {",
748
+ " if (details.dataset.loaded === 'true' || details.dataset.loading === 'true') return;",
749
+ " const code = details.querySelector('code');",
750
+ " const button = details.querySelector('[data-hia-source-fetch-button]');",
751
+ " const status = details.querySelector('[data-hia-source-fetch-status]');",
752
+ " details.dataset.loading = 'true';",
753
+ " details.setAttribute('aria-busy', 'true');",
754
+ " if (status) {",
755
+ " status.hidden = false;",
756
+ " status.textContent = 'Loading source / 正在加载源码...';",
757
+ " }",
758
+ " try {",
759
+ " const response = await fetch(details.dataset.hiaSourceFetch || '', { credentials: 'omit' });",
760
+ " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
761
+ " const lines = (await response.text()).split(/\\r?\\n/u);",
762
+ " const start = Math.max(1, Number(details.dataset.hiaSourceStart || 1));",
763
+ " const maxLines = Math.max(1, Number(details.dataset.hiaSourceMaxLines || 400));",
764
+ " const declaredEnd = Number(details.dataset.hiaSourceEnd || 0);",
765
+ " const end = declaredEnd >= start ? Math.min(declaredEnd, start + maxLines - 1) : start + maxLines - 1;",
766
+ " if (code) code.textContent = lines.slice(start - 1, end).join('\\n');",
767
+ " details.dataset.loaded = 'true';",
768
+ " if (button) button.hidden = true;",
769
+ " if (status) status.hidden = true;",
770
+ " } catch (error) {",
771
+ " if (status) status.textContent = `Source load failed / 源码加载失败: ${String(error?.message || error)}`;",
772
+ " if (button) {",
773
+ " button.hidden = false;",
774
+ " button.textContent = 'Retry source / 重试加载源码';",
775
+ " }",
776
+ " } finally {",
777
+ " delete details.dataset.loading;",
778
+ " details.removeAttribute('aria-busy');",
779
+ " }",
780
+ " }",
781
+ ` function bindSourceFetch(root = ${rootExpression}) {`,
782
+ " for (const details of root?.querySelectorAll('details[data-hia-source-fetch]') || []) {",
783
+ " const button = details.querySelector('[data-hia-source-fetch-button]');",
784
+ " if (button) button.addEventListener('click', () => loadSourceFetch(details));",
785
+ " if (details.dataset.hiaSourceFetchTrigger !== 'manual') {",
786
+ " details.addEventListener('toggle', () => {",
787
+ " if (details.open) void loadSourceFetch(details);",
788
+ " });",
789
+ " if (details.open) void loadSourceFetch(details);",
790
+ " }",
791
+ " }",
792
+ " }"
793
+ ];
794
+ }
795
+ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel, loadingStrategy, relationsLabel) {
445
796
  return [
446
797
  "<script>",
447
798
  "(() => {",
448
- " 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' };`,
449
800
  " const treeHost = document.querySelector('[data-hia-project-tree]');",
450
801
  " const contentHost = document.querySelector('[data-hia-project-content]');",
451
802
  " const search = document.querySelector('[data-hia-project-search]');",
@@ -453,6 +804,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
453
804
  " const viewButtons = Array.from(document.querySelectorAll('[data-hia-project-view]'));",
454
805
  " let rootNodes = [];",
455
806
  " let searchEntries = null;",
807
+ " let eagerFragments = null;",
456
808
  " let activeView = 'all';",
457
809
  " async function readJson(target) {",
458
810
  " const response = await fetch(target, { credentials: 'omit' });",
@@ -479,8 +831,12 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
479
831
  " function createTreeNode(node) {",
480
832
  " const item = document.createElement('li');",
481
833
  " item.dataset.hiaProjectNav = node.views?.[0] || 'other';",
482
- " 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) {",
483
838
  " const details = document.createElement('details');",
839
+ " details.dataset.hiaProjectDisclosure = node.id || '';",
484
840
  " const summary = document.createElement('summary');",
485
841
  " const summaryLabel = document.createElement('span');",
486
842
  " summaryLabel.textContent = `${node.label} (${node.entryCount})`;",
@@ -493,32 +849,37 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
493
849
  " openButton.addEventListener('click', (event) => {",
494
850
  " event.preventDefault();",
495
851
  " event.stopPropagation();",
496
- " loadEntry(node.entryId, node.contentPath, true);",
852
+ " loadEntry(node, true);",
497
853
  " });",
498
854
  " summary.append(openButton);",
499
855
  " }",
500
856
  " details.append(summary);",
501
- " details.addEventListener('toggle', async () => {",
502
- " if (!details.open || details.dataset.loaded === 'true') return;",
857
+ " if (inlineChildren.length > 0) {",
503
858
  " details.dataset.loaded = 'true';",
504
- " const loading = document.createElement('p');",
505
- " loading.className = 'hia-project-loading';",
506
- " loading.textContent = '...';",
507
- " details.append(loading);",
508
- " try {",
509
- " const shard = await readJson(node.childrenPath);",
510
- " loading.replaceWith(createTreeList(Array.isArray(shard.children) ? shard.children : []));",
511
- " } catch (error) {",
512
- " loading.textContent = String(error?.message || error);",
513
- " }",
514
- " });",
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
+ " }",
515
876
  " item.append(details);",
516
877
  " } else if (node.entryId && node.contentPath) {",
517
878
  " const button = document.createElement('button');",
518
879
  " button.type = 'button';",
519
880
  " button.className = 'hia-project-entry-link';",
520
881
  " button.textContent = node.label;",
521
- " button.addEventListener('click', () => loadEntry(node.entryId, node.contentPath, true));",
882
+ " button.addEventListener('click', () => loadEntry(node, true));",
522
883
  " item.append(button);",
523
884
  " } else {",
524
885
  " const label = document.createElement('span');",
@@ -539,36 +900,47 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
539
900
  " block.hidden = block.getAttribute('data-hia-locale') !== selected;",
540
901
  " }",
541
902
  " }",
542
- " function bindSourceFetch() {",
543
- " for (const button of contentHost?.querySelectorAll('[data-hia-source-fetch]') || []) {",
544
- " button.addEventListener('click', async () => {",
545
- " if (button.dataset.loaded === 'true') return;",
546
- " const code = button.parentElement?.querySelector('code');",
547
- " try {",
548
- " const response = await fetch(button.dataset.hiaSourceFetch || '', { credentials: 'omit' });",
549
- " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
550
- " const lines = (await response.text()).split(/\\r?\\n/u);",
551
- " const start = Math.max(1, Number(button.dataset.hiaSourceStart || 1));",
552
- " const end = Math.max(start, Number(button.dataset.hiaSourceEnd || lines.length));",
553
- " if (code) code.textContent = lines.slice(start - 1, end).join('\\n');",
554
- " button.dataset.loaded = 'true';",
555
- " button.hidden = true;",
556
- " } catch (error) {",
557
- " button.textContent = String(error?.message || error);",
558
- " }",
559
- " });",
903
+ ...renderProjectSourceFetchClientLines("contentHost"),
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'); }",
560
929
  " }",
561
930
  " }",
562
- " async function loadEntry(entryId, contentPath, updateHash) {",
931
+ " async function loadEntry(entry, updateHash) {",
563
932
  " if (!contentHost) return;",
564
933
  " contentHost.innerHTML = '<p class=\"hia-project-loading\">...</p>';",
565
934
  " try {",
566
- " const response = await fetch(contentPath, { credentials: 'omit' });",
567
- " if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);",
568
- " contentHost.innerHTML = await response.text();",
935
+ " const contentPath = entry.presentationPath || entry.contentPath;",
936
+ " contentHost.innerHTML = await readFragment(contentPath);",
569
937
  " applyLocale();",
570
938
  " bindSourceFetch();",
571
- " 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)}`);",
572
944
  " } catch (error) {",
573
945
  " showLoadError(error);",
574
946
  " }",
@@ -587,7 +959,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
587
959
  " const matches = entries.filter((entry) => (activeView === 'all' || entry.view === activeView) && String(entry.searchText || '').includes(query)).slice(0, 200);",
588
960
  " if (!treeHost) return;",
589
961
  " treeHost.innerHTML = '';",
590
- " 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 }));",
591
963
  " treeHost.append(createTreeList(nodes));",
592
964
  " } catch (error) { showLoadError(error); }",
593
965
  " }",
@@ -608,7 +980,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
608
980
  " const article = document.createElement('article');",
609
981
  " article.className = 'hia-symbol';",
610
982
  " const heading = document.createElement('h2');",
611
- " heading.textContent = 'Relations';",
983
+ ` heading.textContent = ${JSON.stringify(relationsLabel)};`,
612
984
  " const summary = document.createElement('p');",
613
985
  " summary.textContent = `${graph.nodeCount || 0} node(s), ${graph.relationCount || 0} relation(s).`;",
614
986
  " article.append(heading, summary);",
@@ -621,7 +993,7 @@ function renderProjectSplitSiteScript(fileProtocolMessage, openLabel) {
621
993
  " const hash = location.hash.startsWith('#entry=') ? decodeURIComponent(location.hash.slice(7)) : '';",
622
994
  " if (hash) ensureSearchIndex().then((entries) => {",
623
995
  " const entry = entries.find((candidate) => candidate.id === hash);",
624
- " if (entry) loadEntry(entry.id, entry.contentPath, false);",
996
+ " if (entry) loadEntry({ ...entry, entryId: entry.id }, false);",
625
997
  " });",
626
998
  " }).catch(showLoadError);",
627
999
  " viewButtons.find((button) => button.dataset.hiaProjectView === 'all')?.setAttribute('aria-pressed', 'true');",
@@ -646,6 +1018,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
646
1018
  const docSourceMapSummary = renderProjectDocSourceMaps(projectInput.docSourceMaps ?? []);
647
1019
  const relationGraphSummary = renderProjectRelationGraphSummary(projectInput.relationGraph);
648
1020
  const relationGraph = renderProjectRelationGraph(projectInput.relationGraph);
1021
+ const generatedDocumentationBindingProjection = renderProjectGeneratedDocumentationBindingProjection(projectInput.generatedDocumentationBindingProjection);
649
1022
  const diagnostics = renderProjectDiagnostics(projectInput.diagnostics ?? []);
650
1023
  return [
651
1024
  "<!doctype html>",
@@ -670,6 +1043,7 @@ function renderProjectIndexHtml(pageTitle, projectInput, options) {
670
1043
  profileSummary,
671
1044
  docSourceMapSummary,
672
1045
  relationGraphSummary,
1046
+ generatedDocumentationBindingProjection,
673
1047
  diagnostics,
674
1048
  "</aside>",
675
1049
  "<main class=\"hia-main hia-project-main\">",
@@ -766,6 +1140,7 @@ function renderProjectEntry(entry, locales, selectedLocale) {
766
1140
  const profile = entry.profile ? renderProjectEntryProfile(entry.profile) : "";
767
1141
  const hierarchy = entry.hierarchy ? renderProjectEntryHierarchy(entry.hierarchy) : "";
768
1142
  const source = entry.source ? renderProjectEntrySource(entry.source) : "";
1143
+ const sourceUsability = entry.sourceUsability ? renderProjectEntrySourceUsability(entry.sourceUsability) : "";
769
1144
  const docSourceMap = entry.docSourceMap ? renderProjectEntryDocSourceMap(entry.docSourceMap) : "";
770
1145
  const diagnostics = renderProjectDiagnostics(entry.diagnostics ?? []);
771
1146
  const searchText = createProjectEntrySearchText(entry);
@@ -780,11 +1155,240 @@ function renderProjectEntry(entry, locales, selectedLocale) {
780
1155
  profile,
781
1156
  hierarchy,
782
1157
  source,
1158
+ sourceUsability,
783
1159
  docSourceMap,
784
1160
  diagnostics,
785
1161
  "</article>"
786
1162
  ].join("");
787
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
+ }
788
1392
  function renderProjectEntryHierarchy(hierarchy) {
789
1393
  const details = [
790
1394
  hierarchy.assembly ? `<dt>Assembly</dt><dd>${escapeHtml(hierarchy.assembly)}</dd>` : "",
@@ -825,7 +1429,7 @@ function renderProjectEntryProfile(profile) {
825
1429
  const version = profile.profileVersion ? `@${profile.profileVersion}` : "";
826
1430
  return `<p class="hia-project-profile">Profile ${escapeHtml(profile.profileId)}${escapeHtml(version)}</p>`;
827
1431
  }
828
- function renderProjectEntrySource(source) {
1432
+ function renderProjectEntrySource(source, includeHeading = true) {
829
1433
  const range = source.range ? `:${source.range.start.line}${source.range.end ? `-${source.range.end.line}` : ""}` : "";
830
1434
  const label = `${source.path}${range}`;
831
1435
  const sourceLabel = source.linkUrl
@@ -839,20 +1443,78 @@ function renderProjectEntrySource(source) {
839
1443
  ].join("");
840
1444
  const preview = source.preview ? renderProjectSourcePreview(source.preview, source.path) : "";
841
1445
  const fetchPreview = source.fetchUrl ? renderProjectSourceFetch(source) : "";
842
- 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
+ };
843
1497
  }
844
1498
  function renderProjectSourceFetch(source) {
845
1499
  const startLine = source.range?.start.line ?? 1;
846
- const endLine = source.range?.end?.line ?? startLine;
1500
+ const endLine = source.range?.end?.line;
1501
+ const fetchTrigger = source.fetchTrigger ?? "on-expand";
1502
+ const maxLines = source.fetchMaxLines ?? 400;
1503
+ const caption = endLine ? `${source.path}:${startLine}-${endLine}` : `${source.path}:${startLine}`;
1504
+ const endAttribute = endLine ? ` data-hia-source-end="${escapeHtml(String(endLine))}"` : "";
1505
+ const manualButton = fetchTrigger === "manual"
1506
+ ? "<button type=\"button\" class=\"hia-source-fetch-button\" data-hia-source-fetch-button>Load source / 加载源码</button>"
1507
+ : "";
847
1508
  return [
848
- "<details class=\"hia-source-preview hia-project-source-preview\">",
849
- `<summary>${escapeHtml(`${source.path}:${startLine}-${endLine}`)}</summary>`,
850
- `<button type="button" class="hia-source-fetch-button" data-hia-source-fetch="${escapeHtml(source.fetchUrl ?? "")}" data-hia-source-start="${escapeHtml(String(startLine))}" data-hia-source-end="${escapeHtml(String(endLine))}">Load source / 加载源码</button>`,
1509
+ `<details class="hia-source-preview hia-project-source-preview" data-hia-source-fetch="${escapeHtml(source.fetchUrl ?? "")}" data-hia-source-fetch-trigger="${escapeHtml(fetchTrigger)}" data-hia-source-start="${escapeHtml(String(startLine))}"${endAttribute} data-hia-source-max-lines="${escapeHtml(String(maxLines))}">`,
1510
+ `<summary>${escapeHtml(caption)}</summary>`,
1511
+ manualButton,
1512
+ "<p class=\"hia-project-loading\" data-hia-source-fetch-status hidden></p>",
851
1513
  `<pre class="hia-source-code"><code data-language="${escapeHtml(source.language ?? "")}"></code></pre>`,
852
1514
  "</details>"
853
1515
  ].join("");
854
1516
  }
855
- function renderProjectEntryDocSourceMap(docSourceMap) {
1517
+ function renderProjectEntryDocSourceMap(docSourceMap, includeHeading = true) {
856
1518
  const sourceRange = docSourceMap.sourceRange ? `:${docSourceMap.sourceRange.start.line}${docSourceMap.sourceRange.end ? `-${docSourceMap.sourceRange.end.line}` : ""}` : "";
857
1519
  const diagnostics = docSourceMap.diagnostics && docSourceMap.diagnostics.length > 0
858
1520
  ? `<dt>Diagnostics</dt><dd>${escapeHtml(docSourceMap.diagnostics.join(", "))}</dd>`
@@ -869,7 +1531,8 @@ function renderProjectEntryDocSourceMap(docSourceMap) {
869
1531
  diagnostics
870
1532
  ].join("");
871
1533
  const actions = renderProjectDocSourceMapOpenRequests(docSourceMap);
872
- 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>`;
873
1536
  }
874
1537
  function renderProjectSourcePreview(preview, fallbackPath) {
875
1538
  if (!preview.content) {
@@ -937,6 +1600,60 @@ function renderProjectDocSourceMaps(docSourceMaps) {
937
1600
  .join("");
938
1601
  return `<section class="hia-project-summary"><h2>Doc Source Maps</h2><ul>${items}</ul></section>`;
939
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
+ }
940
1657
  function renderProjectRelationGraphSummary(relationGraph) {
941
1658
  if (!relationGraph || relationGraph.relationCount === 0) {
942
1659
  return "";
@@ -1005,6 +1722,7 @@ function renderProjectViewScript() {
1005
1722
  " const search = document.querySelector('[data-hia-project-search]');",
1006
1723
  " const empty = document.querySelector('[data-hia-project-empty]');",
1007
1724
  " let activeView = 'all';",
1725
+ ...renderProjectSourceFetchClientLines("document"),
1008
1726
  " function matchesFilter(item, view, query) {",
1009
1727
  " const viewName = item.dataset.hiaProjectEntry || item.dataset.hiaProjectNav || 'other';",
1010
1728
  " const text = (item.dataset.hiaProjectSearchText || '').toLowerCase();",
@@ -1038,6 +1756,7 @@ function renderProjectViewScript() {
1038
1756
  " }, window.location.protocol === 'file:' || window.location.origin === 'null' ? '*' : window.location.origin);",
1039
1757
  " });",
1040
1758
  " }",
1759
+ " bindSourceFetch();",
1041
1760
  " activate('all');",
1042
1761
  "})();",
1043
1762
  "</script>"
@@ -1229,7 +1948,7 @@ function collectProjectNavigationGroups(entries) {
1229
1948
  ...collectProjectNavigationGroupsBy(entries, "source-root", (entry) => getProjectSourceRoot(entry.source?.path))
1230
1949
  ].sort(compareProjectNavigationGroups);
1231
1950
  }
1232
- function collectProjectNavigationTree(entries) {
1951
+ function collectProjectNavigationTree(entries, informationArchitecture) {
1233
1952
  return PROJECT_VIEW_ORDER
1234
1953
  .filter((view) => view !== "all")
1235
1954
  .flatMap((view) => {
@@ -1237,9 +1956,11 @@ function collectProjectNavigationTree(entries) {
1237
1956
  if (viewEntries.length === 0) {
1238
1957
  return [];
1239
1958
  }
1240
- const children = view === "dotnet"
1241
- ? collectDotNetNavigationTree(viewEntries)
1242
- : collectSemanticSourceNavigationTree(viewEntries);
1959
+ const children = informationArchitecture
1960
+ ? collectManifestSemanticNavigationTree(viewEntries, view)
1961
+ : view === "dotnet"
1962
+ ? collectDotNetNavigationTree(viewEntries)
1963
+ : collectSemanticSourceNavigationTree(viewEntries);
1243
1964
  return [{
1244
1965
  id: `view:${view}`,
1245
1966
  kind: "view",
@@ -1250,7 +1971,7 @@ function collectProjectNavigationTree(entries) {
1250
1971
  }];
1251
1972
  });
1252
1973
  }
1253
- function collectDotNetNavigationTree(entries) {
1974
+ function collectDotNetNavigationTree(entries, includeTypeRelations = true) {
1254
1975
  const roots = new Map();
1255
1976
  for (const entry of entries) {
1256
1977
  const parts = getDotNetNavigationParts(entry);
@@ -1276,7 +1997,7 @@ function collectDotNetNavigationTree(entries) {
1276
1997
  if (isDotNetTypeNavigationEntry(entry)) {
1277
1998
  typeNode.entryId = entry.id;
1278
1999
  assignProjectTreeEntryRefs(typeNode, entry);
1279
- if (entry.kind === "dotnet-type") {
2000
+ if (includeTypeRelations && entry.kind === "dotnet-type") {
1280
2001
  addDotNetInheritanceNodes(typeNode, entry);
1281
2002
  }
1282
2003
  continue;
@@ -1289,6 +2010,125 @@ function collectDotNetNavigationTree(entries) {
1289
2010
  }
1290
2011
  return sortProjectTreeNodes([...roots.values()].map(finalizeProjectTreeBuilder));
1291
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
+ }
1292
2132
  function addDotNetInheritanceNodes(typeNode, entry) {
1293
2133
  for (const baseTypeId of entry.hierarchy?.baseTypeIds ?? []) {
1294
2134
  const relationNode = getOrCreateProjectTreeChild(typeNode.childrenById, `${typeNode.id}:base:${slugProjectGroupLabel(baseTypeId)}`, "relation", `Base: ${baseTypeId.replace(/^T:/u, "")}`);
@@ -1377,7 +2217,8 @@ function getOrCreateProjectTreeChild(map, id, kind, label) {
1377
2217
  entryCount: 0,
1378
2218
  views: new Set(),
1379
2219
  children: [],
1380
- childrenById: new Map()
2220
+ childrenById: new Map(),
2221
+ terminalChildren: []
1381
2222
  };
1382
2223
  map.set(id, created);
1383
2224
  return created;
@@ -1399,7 +2240,10 @@ function assignProjectTreeSourcePath(node, sourcePath) {
1399
2240
  }
1400
2241
  function finalizeProjectTreeBuilder(node) {
1401
2242
  const childBuilders = node.childrenById.size > 0 ? [...node.childrenById.values()] : node.children;
1402
- const children = sortProjectTreeNodes(childBuilders.map(finalizeProjectTreeBuilder));
2243
+ const children = sortProjectTreeNodes([
2244
+ ...childBuilders.map(finalizeProjectTreeBuilder),
2245
+ ...node.terminalChildren
2246
+ ]);
1403
2247
  return {
1404
2248
  id: node.id,
1405
2249
  kind: node.kind,
@@ -1425,28 +2269,40 @@ function projectTreeKindOrder(kind) {
1425
2269
  if (kind === "view") {
1426
2270
  return 0;
1427
2271
  }
1428
- if (kind === "surface" || kind === "project") {
2272
+ if (kind === "repository") {
2273
+ return 1;
2274
+ }
2275
+ if (kind === "package") {
1429
2276
  return 2;
1430
2277
  }
1431
- if (kind === "namespace") {
2278
+ if (kind === "layer") {
1432
2279
  return 3;
1433
2280
  }
1434
- if (kind === "type") {
2281
+ if (kind === "contract" || kind === "operation") {
1435
2282
  return 4;
1436
2283
  }
1437
- if (kind === "relation") {
2284
+ if (kind === "surface" || kind === "project") {
1438
2285
  return 5;
1439
2286
  }
1440
2287
  if (kind === "assembly") {
1441
- 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;
1442
2298
  }
1443
2299
  if (kind === "source-root") {
1444
- return 6;
2300
+ return 10;
1445
2301
  }
1446
2302
  if (kind === "source-file") {
1447
- return 7;
2303
+ return 11;
1448
2304
  }
1449
- return 8;
2305
+ return 12;
1450
2306
  }
1451
2307
  function getDotNetNavigationParts(entry) {
1452
2308
  const fallback = getDotNetNonAssemblyNavigationParts(entry);