@hia-doc/htmdoc-spec 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ +MIT License
2
+
3
+ Copyright (c) 2026 HIA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # @hia-doc/htmdoc-spec
2
+
3
+ Defines draft annotation, tag registry, rule, diagnostic and compatibility semantics for HTML documentation.
4
+
5
+ ```sh
6
+ npm install @hia-doc/htmdoc-spec
7
+ ```
8
+
9
+ ```js
10
+ import {
11
+ HTMDOC_EXTRACTION_CONTRACT,
12
+ HTMDOC_EXTRACTION_JSON_SCHEMA
13
+ } from "@hia-doc/htmdoc-spec";
14
+ ```
15
+
16
+ The current tag registry includes standard-level, unprefixed tags for components, elements, templates, attributes, slots, events, style hooks, accessibility notes, examples, descriptions and language metadata.
17
+
18
+ The package also exports the draft extraction artifact schema constants:
19
+
20
+ - `HTMDOC_EXTRACTION_SCHEMA_ID`
21
+ - `HTMDOC_EXTRACTION_JSON_SCHEMA`
22
+
23
+ It also exports the owner-local `evaluateHtmDocOutputConformance()` evaluator and its
24
+ `HTMDOC_OUTPUT_CONFORMANCE_*` constants. The evaluator compares already-generated extraction, HIA document,
25
+ ordinary doc-source-map and producer-result JSON records. It performs no file, source, network or target-project
26
+ access, and is not a cross-package runtime capability schema. The default `none` source-content policy remains
27
+ content-free; an `embed` artifact requires explicit evaluator confirmation.
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@hia-doc/htmdoc-spec",
3
+ "version": "0.1.0",
4
+ "description": "HTML documentation annotation, tag registry and rule drafts.",
5
+ "license": "MIT",
6
+ "keywords": ["documentation", "html", "htmdoc", "schema"],
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mandolin/hia-htmdoc.git",
10
+ "directory": "packages/htmdoc-spec"
11
+ },
12
+ "bugs": { "url": "https://github.com/mandolin/hia-htmdoc/issues" },
13
+ "homepage": "https://github.com/mandolin/hia-htmdoc/tree/main/packages/htmdoc-spec#readme",
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./src/index.mjs"
17
+ },
18
+ "files": ["src", "README.md", "LICENSE"],
19
+ "engines": { "node": ">=20.19.0" },
20
+ "publishConfig": { "access": "public" }
21
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,182 @@
1
+ export const HTMDOC_EXTRACTION_CONTRACT = "hia-htmdoc-extraction";
2
+ export const HTMDOC_EXTRACTION_CONTRACT_VERSION = "0.1.0-draft";
3
+ export const HTMDOC_EXTRACTION_SCHEMA_ID = "https://hia-doc.local/schema/hia-htmdoc-extraction-0.1.0-draft.json";
4
+ export const HTMDOC_PROFILE_VERSION = "0.1.0-draft";
5
+
6
+ /**
7
+ * Owner-local output conformance evaluator for already-generated HTMDoc artifacts.
8
+ *
9
+ * 中文:针对已生成 HTMDoc artifact 的 owner-local output conformance evaluator。
10
+ * English: Owner-local output conformance evaluator for already-generated HTMDoc artifacts.
11
+ * @lang zh-CN 该 evaluator 不读取 source、不写入 artifact,也不成为跨仓 runtime capability schema。
12
+ */
13
+ export {
14
+ evaluateHtmDocOutputConformance,
15
+ HTMDOC_OUTPUT_CONFORMANCE_CODES,
16
+ HTMDOC_OUTPUT_CONFORMANCE_CONTRACT,
17
+ HTMDOC_OUTPUT_CONFORMANCE_VERSION
18
+ } from "./output-conformance.mjs";
19
+
20
+ export const HTMDOC_SYMBOL_KINDS = Object.freeze({
21
+ component: "html-component",
22
+ element: "html-element",
23
+ template: "html-template",
24
+ attribute: "html-attribute",
25
+ slot: "html-slot",
26
+ event: "html-event",
27
+ styleHook: "html-style-hook",
28
+ a11yNote: "html-a11y-note",
29
+ example: "html-example"
30
+ });
31
+
32
+ export const HTMDOC_TAGS = Object.freeze([
33
+ "component",
34
+ "element",
35
+ "template",
36
+ "attr",
37
+ "slot",
38
+ "event",
39
+ "stylehook",
40
+ "a11y",
41
+ "description",
42
+ "example",
43
+ "lang"
44
+ ]);
45
+
46
+ export const HTMDOC_EXTRACTION_JSON_SCHEMA = Object.freeze({
47
+ $schema: "https://json-schema.org/draft/2020-12/schema",
48
+ $id: HTMDOC_EXTRACTION_SCHEMA_ID,
49
+ type: "object",
50
+ required: ["contract", "contractVersion", "producer", "profile", "source", "symbols", "annotations", "diagnostics", "sourceMap"],
51
+ additionalProperties: true,
52
+ properties: {
53
+ contract: { const: HTMDOC_EXTRACTION_CONTRACT },
54
+ contractVersion: { const: HTMDOC_EXTRACTION_CONTRACT_VERSION },
55
+ producer: { $ref: "#/$defs/producer" },
56
+ profile: { $ref: "#/$defs/profile" },
57
+ source: { $ref: "#/$defs/source" },
58
+ symbols: {
59
+ type: "array",
60
+ items: { $ref: "#/$defs/symbol" }
61
+ },
62
+ annotations: {
63
+ type: "array",
64
+ items: { type: "object" }
65
+ },
66
+ diagnostics: {
67
+ type: "array",
68
+ items: { $ref: "#/$defs/diagnostic" }
69
+ },
70
+ sourceMap: { type: "object" },
71
+ metadata: { type: "object" }
72
+ },
73
+ $defs: {
74
+ nonEmptyString: { type: "string", minLength: 1 },
75
+ producer: {
76
+ type: "object",
77
+ required: ["name", "version"],
78
+ additionalProperties: true,
79
+ properties: {
80
+ name: { $ref: "#/$defs/nonEmptyString" },
81
+ version: { $ref: "#/$defs/nonEmptyString" }
82
+ }
83
+ },
84
+ profile: {
85
+ type: "object",
86
+ required: ["name", "version"],
87
+ additionalProperties: true,
88
+ properties: {
89
+ name: { $ref: "#/$defs/nonEmptyString" },
90
+ version: { $ref: "#/$defs/nonEmptyString" }
91
+ }
92
+ },
93
+ source: {
94
+ type: "object",
95
+ required: ["kind", "path"],
96
+ additionalProperties: true,
97
+ properties: {
98
+ kind: { $ref: "#/$defs/nonEmptyString" },
99
+ path: { $ref: "#/$defs/nonEmptyString" },
100
+ sourcesContent: { type: "string" }
101
+ }
102
+ },
103
+ sourcePosition: {
104
+ type: "object",
105
+ required: ["line"],
106
+ additionalProperties: true,
107
+ properties: {
108
+ line: { type: "integer", minimum: 1 },
109
+ column: { type: "integer", minimum: 1 }
110
+ }
111
+ },
112
+ sourceRange: {
113
+ anyOf: [
114
+ { type: "null" },
115
+ {
116
+ type: "object",
117
+ required: ["start"],
118
+ additionalProperties: true,
119
+ properties: {
120
+ start: { $ref: "#/$defs/sourcePosition" },
121
+ end: { $ref: "#/$defs/sourcePosition" }
122
+ }
123
+ }
124
+ ]
125
+ },
126
+ symbol: {
127
+ type: "object",
128
+ required: ["id", "kind", "name", "source"],
129
+ additionalProperties: true,
130
+ properties: {
131
+ id: { $ref: "#/$defs/nonEmptyString" },
132
+ kind: { enum: Object.values(HTMDOC_SYMBOL_KINDS) },
133
+ name: { $ref: "#/$defs/nonEmptyString" },
134
+ parentId: { $ref: "#/$defs/nonEmptyString" },
135
+ summary: { type: "string" },
136
+ source: {
137
+ type: "object",
138
+ required: ["path"],
139
+ additionalProperties: true,
140
+ properties: {
141
+ path: { $ref: "#/$defs/nonEmptyString" },
142
+ range: { $ref: "#/$defs/sourceRange" }
143
+ }
144
+ },
145
+ annotation: { type: "object" },
146
+ metadata: { type: "object" }
147
+ }
148
+ },
149
+ diagnostic: {
150
+ type: "object",
151
+ required: ["code", "message", "severity"],
152
+ additionalProperties: true,
153
+ properties: {
154
+ code: { $ref: "#/$defs/nonEmptyString" },
155
+ message: { $ref: "#/$defs/nonEmptyString" },
156
+ severity: { enum: ["info", "warning", "error"] },
157
+ path: { $ref: "#/$defs/nonEmptyString" },
158
+ data: { type: "object" }
159
+ }
160
+ }
161
+ }
162
+ });
163
+
164
+ const TAG_TO_KIND = Object.freeze({
165
+ component: HTMDOC_SYMBOL_KINDS.component,
166
+ element: HTMDOC_SYMBOL_KINDS.element,
167
+ template: HTMDOC_SYMBOL_KINDS.template,
168
+ attr: HTMDOC_SYMBOL_KINDS.attribute,
169
+ slot: HTMDOC_SYMBOL_KINDS.slot,
170
+ event: HTMDOC_SYMBOL_KINDS.event,
171
+ stylehook: HTMDOC_SYMBOL_KINDS.styleHook,
172
+ a11y: HTMDOC_SYMBOL_KINDS.a11yNote,
173
+ example: HTMDOC_SYMBOL_KINDS.example
174
+ });
175
+
176
+ export function getHtmlDocSymbolKind(tag) {
177
+ return TAG_TO_KIND[tag] ?? null;
178
+ }
179
+
180
+ export function isHtmlDocTag(tag) {
181
+ return HTMDOC_TAGS.includes(tag);
182
+ }
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Owner-local contract identity for HTMDoc output conformance summaries.
3
+ *
4
+ * 中文:HTMDoc 输出 conformance summary 的 owner-local contract identity。
5
+ * English: Owner-local contract identity for HTMDoc output conformance summaries.
6
+ */
7
+ export const HTMDOC_OUTPUT_CONFORMANCE_CONTRACT = "htmdoc-output-conformance";
8
+
9
+ /**
10
+ * Frozen draft version for the owner-local HTMDoc output conformance result.
11
+ *
12
+ * 中文:HTMDoc owner-local 输出 conformance result 的冻结 draft version。
13
+ * English: Frozen draft version for the owner-local HTMDoc output conformance result.
14
+ */
15
+ export const HTMDOC_OUTPUT_CONFORMANCE_VERSION = "0.1.0-draft";
16
+
17
+ /**
18
+ * Public-safe violation codes emitted by the HTMDoc output conformance evaluator.
19
+ *
20
+ * 中文:HTMDoc 输出 conformance evaluator 发出的 public-safe violation codes。
21
+ * English: Public-safe violation codes emitted by the HTMDoc output conformance evaluator.
22
+ * @lang zh-CN code 只描述 artifact boundary;绝不回显 source text、absolute path、private sidecar locator 或 caller supplied value。
23
+ */
24
+ export const HTMDOC_OUTPUT_CONFORMANCE_CODES = Object.freeze([
25
+ "HTMDOC_OUTPUT_CONFORMANCE_INPUT_INVALID",
26
+ "HTMDOC_OUTPUT_CONFORMANCE_EXTRACTION_INVALID",
27
+ "HTMDOC_OUTPUT_CONFORMANCE_DOCUMENT_INVALID",
28
+ "HTMDOC_OUTPUT_CONFORMANCE_RELATION_INVALID",
29
+ "HTMDOC_OUTPUT_CONFORMANCE_PROVENANCE_INVALID",
30
+ "HTMDOC_OUTPUT_CONFORMANCE_SOURCE_POLICY_INVALID",
31
+ "HTMDOC_OUTPUT_CONFORMANCE_EMBED_UNAUTHORIZED",
32
+ "HTMDOC_OUTPUT_CONFORMANCE_SIDECAR_BOUNDARY_INVALID",
33
+ "HTMDOC_OUTPUT_CONFORMANCE_PRODUCER_RESULT_INVALID"
34
+ ]);
35
+
36
+ /**
37
+ * Evaluate whether already-materialized HTMDoc artifacts preserve the owner-local P1 output boundary.
38
+ *
39
+ * 中文:评估已经 materialized 的 HTMDoc artifact 是否保持 owner-local P1 output boundary。
40
+ * English: Evaluate whether already-materialized HTMDoc artifacts preserve the owner-local P1 output boundary.
41
+ *
42
+ * @param {unknown} artifacts <lang><zh-CN>extraction、HIA document、ordinary doc-source-map 与 producer result 的固定 bundle。</zh-CN><en>Fixed bundle containing extraction, HIA document, ordinary doc-source-map, and producer result.</en></lang>
43
+ * @param {{allowEmbeddedSource?: boolean}} [options] <lang><zh-CN>只允许 caller 显式确认 `embed`;缺省保持 `none`/`reference` 不嵌入。</zh-CN><en>Only permits `embed` after explicit caller confirmation; the default keeps `none`/`reference` unembedded.</en></lang>
44
+ * @returns {{contract:string,contractVersion:string,conformant:boolean,violations:Array<{code:string,message:string}>}} <lang><zh-CN>不含 artifact 内容的确定性 summary。</zh-CN><en>Deterministic summary containing no artifact content.</en></lang>
45
+ * @lang zh-CN 函数只比较 caller 已提供的 JSON records;不接收文件路径、workspace root、source text、network 或 sidecar path,也不会产生写入。
46
+ */
47
+ export function evaluateHtmDocOutputConformance(artifacts, options = {}) {
48
+ // <lang><zh-CN>violation 仅累积固定 code/message,避免诊断把不可信 artifact 字段回显到 public output。</zh-CN><en>Violations accumulate only fixed code/message pairs so diagnostics never echo untrusted artifact fields into public output.</en></lang>
49
+ const violations = [];
50
+ // <lang><zh-CN>bundle 是唯一允许的根形状;array/primitive 无法安全承载四类关联 artifact。</zh-CN><en>The bundle is the only allowed root shape; an array or primitive cannot safely carry the four related artifact classes.</en></lang>
51
+ const bundle = isRecord(artifacts) ? artifacts : undefined;
52
+ if (!bundle) {
53
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_INPUT_INVALID", "HTMDoc output conformance requires an artifact bundle object.");
54
+ return createSummary(violations);
55
+ }
56
+
57
+ // <lang><zh-CN>只从固定字段提取 artifact;evaluator 不接受自由命名的 artifact、路径或 I/O callback。</zh-CN><en>Extract artifacts only from fixed fields; the evaluator accepts no freely named artifact, path, or I/O callback.</en></lang>
58
+ const extraction = isRecord(bundle.extraction) ? bundle.extraction : undefined;
59
+ const document = isRecord(bundle.document) ? bundle.document : undefined;
60
+ const docSourceMap = isRecord(bundle.docSourceMap) ? bundle.docSourceMap : undefined;
61
+ const producerResult = isRecord(bundle.producerResult) ? bundle.producerResult : undefined;
62
+ // <lang><zh-CN>embed 许可只由 boolean true 开启;truthy 值或 artifact 内声明均不能绕过默认保护。</zh-CN><en>Embed permission is enabled only by boolean true; truthy values or artifact declarations cannot bypass the default protection.</en></lang>
63
+ const allowEmbeddedSource = options?.allowEmbeddedSource === true;
64
+
65
+ // <lang><zh-CN>root check 先确立后续 relation/privacy 检查的最小可信 shape。</zh-CN><en>Root checks establish the minimum trusted shape needed by later relation and privacy checks.</en></lang>
66
+ const extractionValid = validateExtraction(extraction, violations);
67
+ const documentValid = validateDocument(document, extraction, violations);
68
+ const mapValid = validateDocSourceMap(docSourceMap, extraction, allowEmbeddedSource, violations);
69
+ // <lang><zh-CN>只有各 artifact 根有效时才计算跨 artifact continuity,避免 malformed input 触发隐式 property access。</zh-CN><en>Compute cross-artifact continuity only after each root is valid, avoiding implicit property access on malformed input.</en></lang>
70
+ if (extractionValid && documentValid && mapValid) {
71
+ validateArtifactRelations(extraction, document, docSourceMap, violations);
72
+ }
73
+ // <lang><zh-CN>producer result 最后验证,因为它将三份 artifact 的 delivery metadata 汇聚为外部可消费边界。</zh-CN><en>Validate the producer result last because it aggregates delivery metadata for all three artifacts into the externally consumable boundary.</en></lang>
74
+ validateProducerResult(producerResult, docSourceMap, violations);
75
+
76
+ return createSummary(violations);
77
+ }
78
+
79
+ /**
80
+ * Create the stable, content-free conformance result shape.
81
+ *
82
+ * 中文:创建稳定且不含内容的 conformance result shape。
83
+ * English: Create the stable, content-free conformance result shape.
84
+ *
85
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>已过滤为固定值的 violation。</zh-CN><en>Violations already filtered to fixed values.</en></lang>
86
+ * @returns {{contract:string,contractVersion:string,conformant:boolean,violations:Array<{code:string,message:string}>}} <lang><zh-CN>不可变语义的 summary record。</zh-CN><en>Summary record with immutable semantics.</en></lang>
87
+ */
88
+ function createSummary(violations) {
89
+ // <lang><zh-CN>contract/version 与 boolean 结论永远同时返回,使 caller 无需从 exception text 推断 evaluator 版本。</zh-CN><en>Always return contract/version with the boolean conclusion so callers never infer evaluator version from exception text.</en></lang>
90
+ return {
91
+ contract: HTMDOC_OUTPUT_CONFORMANCE_CONTRACT,
92
+ contractVersion: HTMDOC_OUTPUT_CONFORMANCE_VERSION,
93
+ conformant: violations.length === 0,
94
+ violations
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Validate the extraction root and its source-content policy without reading source content.
100
+ *
101
+ * 中文:验证 extraction root 和 source-content policy;不读取 source content。
102
+ * English: Validate the extraction root and source-content policy without reading source content.
103
+ *
104
+ * @param {Record<string, unknown>|undefined} extraction <lang><zh-CN>候选 HTMDoc extraction。</zh-CN><en>Candidate HTMDoc extraction.</en></lang>
105
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
106
+ * @returns {boolean} <lang><zh-CN>root 是否足以安全进入 relation check。</zh-CN><en>Whether the root is safe enough for relation checks.</en></lang>
107
+ */
108
+ function validateExtraction(extraction, violations) {
109
+ // <lang><zh-CN>contract/version/symbols/source 是所有 downstream projection 的最小连续性锚点。</zh-CN><en>Contract/version/symbols/source are the minimum continuity anchors for every downstream projection.</en></lang>
110
+ if (!extraction || extraction.contract !== "hia-htmdoc-extraction" || extraction.contractVersion !== "0.1.0-draft" || !Array.isArray(extraction.symbols) || !isRecord(extraction.source)) {
111
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_EXTRACTION_INVALID", "HTMDoc extraction must expose the supported contract, version, source, and symbols.");
112
+ return false;
113
+ }
114
+ // <lang><zh-CN>source path 只允许 relative logical identity,既不 canonicalize 也不访问 filesystem。</zh-CN><en>The source path permits only a relative logical identity; it is neither canonicalized nor sent to the filesystem.</en></lang>
115
+ const sourcePath = extraction.source.path;
116
+ const sourceMap = isRecord(extraction.sourceMap) ? extraction.sourceMap : undefined;
117
+ const policy = sourceMap?.sourcesContentPolicy;
118
+ if (!isSafeRelativePath(sourcePath) || !isSupportedSourcePolicy(policy)) {
119
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_SOURCE_POLICY_INVALID", "HTMDoc extraction must use a safe relative source identity and supported source-content policy.");
120
+ return false;
121
+ }
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * Validate the projected HIA document against the extraction's stable symbol identities.
127
+ *
128
+ * 中文:按 extraction 的 stable symbol identity 验证 projected HIA document。
129
+ * English: Validate the projected HIA document against the extraction's stable symbol identities.
130
+ *
131
+ * @param {Record<string, unknown>|undefined} document <lang><zh-CN>候选 HIA document。</zh-CN><en>Candidate HIA document.</en></lang>
132
+ * @param {Record<string, unknown>|undefined} extraction <lang><zh-CN>已检查的 extraction root。</zh-CN><en>Previously checked extraction root.</en></lang>
133
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
134
+ * @returns {boolean} <lang><zh-CN>document root 是否足以安全进入 relation check。</zh-CN><en>Whether the document root is safe enough for relation checks.</en></lang>
135
+ */
136
+ function validateDocument(document, extraction, violations) {
137
+ // <lang><zh-CN>document 使用现有 HIA 0.2 形状;本检查不把 owner-local evaluator 误作新的 document schema。</zh-CN><en>The document uses the existing HIA 0.2 shape; this check does not mistake the owner-local evaluator for a new document schema.</en></lang>
138
+ if (!document || document.schemaVersion !== "0.2.0" || !Array.isArray(document.symbols) || !extraction) {
139
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_DOCUMENT_INVALID", "HTMDoc HIA document must retain the supported core shape and symbol array.");
140
+ return false;
141
+ }
142
+ return true;
143
+ }
144
+
145
+ /**
146
+ * Validate ordinary doc-source-map linkage, policy propagation, and the no-sidecar-by-default boundary.
147
+ *
148
+ * 中文:验证 ordinary doc-source-map linkage、policy propagation 与默认无 sidecar 边界。
149
+ * English: Validate ordinary doc-source-map linkage, policy propagation, and the no-sidecar-by-default boundary.
150
+ *
151
+ * @param {Record<string, unknown>|undefined} docSourceMap <lang><zh-CN>候选 ordinary doc-source-map。</zh-CN><en>Candidate ordinary doc-source-map.</en></lang>
152
+ * @param {Record<string, unknown>|undefined} extraction <lang><zh-CN>已检查的 extraction root。</zh-CN><en>Previously checked extraction root.</en></lang>
153
+ * @param {boolean} allowEmbeddedSource <lang><zh-CN>caller 是否明确确认 embed。</zh-CN><en>Whether the caller explicitly confirmed embed.</en></lang>
154
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
155
+ * @returns {boolean} <lang><zh-CN>map root 是否足以安全进入 relation check。</zh-CN><en>Whether the map root is safe enough for relation checks.</en></lang>
156
+ */
157
+ function validateDocSourceMap(docSourceMap, extraction, allowEmbeddedSource, violations) {
158
+ // <lang><zh-CN>普通 map 必须保留 explicit sources/artifacts/chains/entries;它仍不是完整 capability model。</zh-CN><en>An ordinary map must retain explicit sources/artifacts/chains/entries; it is still not a full capability model.</en></lang>
159
+ if (!docSourceMap || docSourceMap.contract !== "doc-source-map" || docSourceMap.contractVersion !== "0.1.0-draft" || !Array.isArray(docSourceMap.sources) || !Array.isArray(docSourceMap.artifacts) || !Array.isArray(docSourceMap.chains) || !Array.isArray(docSourceMap.entries) || !extraction) {
160
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_PROVENANCE_INVALID", "HTMDoc doc-source-map must retain the supported ordinary-map identity and relation arrays.");
161
+ return false;
162
+ }
163
+ // <lang><zh-CN>HTMDoc P1 尚未生产 metadata sidecar;任何未审核 sidecar field 都必须拒绝,防止私有 locator 或 body 偷渡。</zh-CN><en>HTMDoc P1 does not produce metadata sidecars; reject any unreviewed sidecar field to prevent private locators or bodies from bypassing review.</en></lang>
164
+ const sidecarKeys = Object.keys(docSourceMap).filter((key) => key.toLocaleLowerCase("en-US").includes("sidecar"));
165
+ if (sidecarKeys.length > 0 || Object.hasOwn(docSourceMap, "capabilities") || Object.hasOwn(docSourceMap, "capability") || Object.hasOwn(docSourceMap, "outputCapabilities")) {
166
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_SIDECAR_BOUNDARY_INVALID", "HTMDoc ordinary doc-source-map must not embed a sidecar or capability model before an explicitly reviewed owner feature exists.");
167
+ }
168
+ // <lang><zh-CN>source/map privacy 值必须一起传播;单独存在 policy 不能证明 paths/body 已被拒绝。</zh-CN><en>Source/map privacy values must propagate together; policy alone does not prove paths or bodies were denied.</en></lang>
169
+ const source = isRecord(docSourceMap.sources[0]) ? docSourceMap.sources[0] : undefined;
170
+ const privacy = isRecord(docSourceMap.privacy) ? docSourceMap.privacy : undefined;
171
+ const extractionPolicy = extraction.sourceMap?.sourcesContentPolicy;
172
+ if (docSourceMap.sources.length !== 1 || !source || source.path !== extraction.source.path || source.sourcesContentPolicy !== extractionPolicy ||
173
+ !privacy || privacy.sourcesContentPolicy !== extractionPolicy || privacy.allowAbsolutePaths !== false || privacy.allowUncPaths !== false || privacy.allowPathTraversal !== false) {
174
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_SOURCE_POLICY_INVALID", "HTMDoc doc-source-map must preserve one safe source identity and all source-policy privacy denials.");
175
+ return false;
176
+ }
177
+ // <lang><zh-CN>`none` 的 extraction source 不能携带 content;`embed` 既要存在 content 又要获得本次 caller 的显式确认。</zh-CN><en>A `none` extraction source cannot carry content; `embed` requires both content and explicit confirmation from this caller.</en></lang>
178
+ const sourceContainsContent = Object.hasOwn(extraction.source, "sourcesContent") && typeof extraction.source.sourcesContent === "string";
179
+ if (extractionPolicy === "none" && sourceContainsContent) {
180
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_SOURCE_POLICY_INVALID", "HTMDoc sourcesContentPolicy none must not serialize extraction source content.");
181
+ }
182
+ if (extractionPolicy === "embed" && !sourceContainsContent) {
183
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_SOURCE_POLICY_INVALID", "HTMDoc sourcesContentPolicy embed requires explicitly provided extraction source content.");
184
+ }
185
+ if (extractionPolicy === "embed" && !allowEmbeddedSource) {
186
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_EMBED_UNAUTHORIZED", "HTMDoc embedded source content requires explicit evaluator confirmation.");
187
+ }
188
+ return true;
189
+ }
190
+
191
+ /**
192
+ * Validate symbol, entry, artifact, and chain continuity without relying on array ordering outside the map contract.
193
+ *
194
+ * 中文:验证 symbol、entry、artifact、chain continuity;除 map contract 外不依赖 array ordering。
195
+ * English: Validate symbol, entry, artifact, and chain continuity without relying on array ordering outside the map contract.
196
+ *
197
+ * @param {Record<string, unknown>} extraction <lang><zh-CN>已验证的 extraction。</zh-CN><en>Validated extraction.</en></lang>
198
+ * @param {Record<string, unknown>} document <lang><zh-CN>已验证的 HIA document。</zh-CN><en>Validated HIA document.</en></lang>
199
+ * @param {Record<string, unknown>} docSourceMap <lang><zh-CN>已验证的 doc-source-map。</zh-CN><en>Validated doc-source-map.</en></lang>
200
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
201
+ * @returns {void} <lang><zh-CN>只向 accumulator 追加固定 violation。</zh-CN><en>Only appends fixed violations to the accumulator.</en></lang>
202
+ */
203
+ function validateArtifactRelations(extraction, document, docSourceMap, violations) {
204
+ // <lang><zh-CN>symbol id set 是 extraction 到 document/map 的稳定连接;重复/空 id 一律不可作为 public entry identity。</zh-CN><en>The symbol-id set is the stable extraction-to-document/map link; duplicate or empty ids can never serve as public entry identities.</en></lang>
205
+ const extractionSymbols = extraction.symbols.filter(isRecord);
206
+ const symbolIds = extractionSymbols.map((symbol) => symbol.id).filter(isNonEmptyString);
207
+ const uniqueSymbolIds = new Set(symbolIds);
208
+ if (extractionSymbols.length !== extraction.symbols.length || symbolIds.length !== extractionSymbols.length || uniqueSymbolIds.size !== symbolIds.length) {
209
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_RELATION_INVALID", "HTMDoc extraction symbols must expose unique non-empty stable identities.");
210
+ return;
211
+ }
212
+ // <lang><zh-CN>document symbol index 按 id 查找,不受 renderer/consumer 重排影响。</zh-CN><en>Index document symbols by id so renderer or consumer reordering has no effect.</en></lang>
213
+ const documentSymbols = Array.isArray(document.symbols) ? document.symbols.filter(isRecord) : [];
214
+ const documentById = new Map(documentSymbols.map((symbol) => [symbol.id, symbol]));
215
+ for (const symbolId of symbolIds) {
216
+ // <lang><zh-CN>每个 extraction symbol 必须投影为同 id 且指向同一 safe relative source 的 HIA symbol。</zh-CN><en>Each extraction symbol must project to a same-id HIA symbol pointing at the same safe relative source.</en></lang>
217
+ const documentSymbol = documentById.get(symbolId);
218
+ const definedIn = isRecord(documentSymbol?.source) && isRecord(documentSymbol.source.definedIn) ? documentSymbol.source.definedIn : undefined;
219
+ if (!documentSymbol || definedIn?.relativePath !== extraction.source.path) {
220
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_RELATION_INVALID", "HTMDoc HIA document must preserve each stable symbol identity and public-safe source relation.");
221
+ break;
222
+ }
223
+ }
224
+ // <lang><zh-CN>ordinary map 的 entries 与 two-stage chain 是 provenance continuity,不是 source body 或 renderer tree。</zh-CN><en>The ordinary map's entries and two-stage chain establish provenance continuity, not a source body or renderer tree.</en></lang>
225
+ const entrySymbolIds = docSourceMap.entries.filter(isRecord).map((entry) => entry.symbolId).filter(isNonEmptyString);
226
+ const entrySymbolIdSet = new Set(entrySymbolIds);
227
+ const hasExpectedArtifacts = docSourceMap.artifacts.filter(isRecord).some((artifact) => artifact.id === "artifact:htmdoc:extraction") &&
228
+ docSourceMap.artifacts.filter(isRecord).some((artifact) => artifact.id === "artifact:hia:document");
229
+ const chain = docSourceMap.chains.filter(isRecord)[0];
230
+ if (entrySymbolIds.length !== symbolIds.length || entrySymbolIdSet.size !== symbolIds.length || symbolIds.some((symbolId) => !entrySymbolIdSet.has(symbolId)) || !hasExpectedArtifacts || !chain || !Array.isArray(chain.stages) || chain.stages.length !== 2) {
231
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_PROVENANCE_INVALID", "HTMDoc doc-source-map must retain one entry per stable symbol and the extraction-to-HIA two-stage provenance chain.");
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Validate that the producer result delivers each supplied artifact through public-safe relative paths.
237
+ *
238
+ * 中文:验证 producer result 通过 public-safe relative paths delivery 每个 supplied artifact。
239
+ * English: Validate that the producer result delivers each supplied artifact through public-safe relative paths.
240
+ *
241
+ * @param {Record<string, unknown>|undefined} producerResult <lang><zh-CN>候选 documentation-producer-result。</zh-CN><en>Candidate documentation-producer-result.</en></lang>
242
+ * @param {Record<string, unknown>|undefined} docSourceMap <lang><zh-CN>候选 doc-source-map。</zh-CN><en>Candidate doc-source-map.</en></lang>
243
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
244
+ * @returns {void} <lang><zh-CN>只向 accumulator 追加固定 violation。</zh-CN><en>Only appends fixed violations to the accumulator.</en></lang>
245
+ */
246
+ function validateProducerResult(producerResult, docSourceMap, violations) {
247
+ // <lang><zh-CN>result metadata 是 target consumer 看到的 delivery boundary;它不能以 failed/partial 状态假装 conformance 成功。</zh-CN><en>Result metadata is the delivery boundary seen by target consumers; a failed or partial state cannot masquerade as conformance success.</en></lang>
248
+ const artifacts = Array.isArray(producerResult?.artifacts) ? producerResult.artifacts.filter(isRecord) : [];
249
+ const producer = isRecord(producerResult?.producer) ? producerResult.producer : undefined;
250
+ if (!producerResult || producerResult.contract !== "documentation-producer-result" || producerResult.contractVersion !== "0.1.0-draft" || producer?.id !== "htmdoc" || producerResult.status !== "success" || artifacts.length === 0 || !docSourceMap) {
251
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_PRODUCER_RESULT_INVALID", "HTMDoc producer result must expose the successful supported contract and delivery metadata.");
252
+ return;
253
+ }
254
+ // <lang><zh-CN>artifact path 仅验证 logical relative form;不 resolve、不访问 disk,也不会把 path 写入 violation。</zh-CN><en>Validate artifact paths only as logical relative forms; do not resolve, access disk, or copy paths into violations.</en></lang>
255
+ const pathsAreSafe = artifacts.every((artifact) => isSafeRelativePath(artifact.path));
256
+ const hasRequiredKinds = ["htmdoc-extraction", "hia-document", "doc-source-map"].every((kind) => artifacts.some((artifact) => artifact.kind === kind));
257
+ const mapArtifact = artifacts.find((artifact) => artifact.kind === "doc-source-map");
258
+ const mapPathMatches = mapArtifact && docSourceMap.artifacts.filter(isRecord).every((artifact) => isSafeRelativePath(artifact.path));
259
+ if (!pathsAreSafe || !hasRequiredKinds || !mapPathMatches) {
260
+ addViolation(violations, "HTMDOC_OUTPUT_CONFORMANCE_PRODUCER_RESULT_INVALID", "HTMDoc producer result must deliver the extraction, HIA document, and ordinary doc-source-map through safe relative artifacts.");
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Append one fixed violation only once, preserving deterministic diagnostics without sensitive input interpolation.
266
+ *
267
+ * 中文:仅追加一次固定 violation,保持确定性诊断且不插入敏感 input。
268
+ * English: Append one fixed violation only once, preserving deterministic diagnostics without sensitive input interpolation.
269
+ *
270
+ * @param {Array<{code:string,message:string}>} violations <lang><zh-CN>固定 violation accumulator。</zh-CN><en>Fixed violation accumulator.</en></lang>
271
+ * @param {string} code <lang><zh-CN>已冻结 public-safe code。</zh-CN><en>Frozen public-safe code.</en></lang>
272
+ * @param {string} message <lang><zh-CN>不含 caller value 的固定 English message。</zh-CN><en>Fixed English message containing no caller value.</en></lang>
273
+ * @returns {void} <lang><zh-CN>无返回;原地保持 accumulator 的首次出现顺序。</zh-CN><en>No return; preserves first-occurrence order in the accumulator.</en></lang>
274
+ */
275
+ function addViolation(violations, code, message) {
276
+ // <lang><zh-CN>重复 code 不增加噪声;一条 code 足以说明该 invariant 已被破坏。</zh-CN><en>A duplicate code adds no signal; one code is sufficient to show that its invariant was violated.</en></lang>
277
+ if (!violations.some((violation) => violation.code === code)) {
278
+ violations.push({ code, message });
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Determine whether a candidate is an object record suitable for fixed-field inspection.
284
+ *
285
+ * 中文:确定 candidate 是否为可作固定字段检查的 object record。
286
+ * English: Determine whether a candidate is an object record suitable for fixed-field inspection.
287
+ *
288
+ * @param {unknown} value <lang><zh-CN>未受信任值。</zh-CN><en>Untrusted value.</en></lang>
289
+ * @returns {value is Record<string, unknown>} <lang><zh-CN>record type guard。</zh-CN><en>Record type guard.</en></lang>
290
+ */
291
+ function isRecord(value) {
292
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
293
+ }
294
+
295
+ /**
296
+ * Determine whether a candidate is a non-empty string identity.
297
+ *
298
+ * 中文:确定 candidate 是否为 non-empty string identity。
299
+ * English: Determine whether a candidate is a non-empty string identity.
300
+ *
301
+ * @param {unknown} value <lang><zh-CN>未受信任 identity candidate。</zh-CN><en>Untrusted identity candidate.</en></lang>
302
+ * @returns {value is string} <lang><zh-CN>是否可用作 stable identity。</zh-CN><en>Whether it can serve as a stable identity.</en></lang>
303
+ */
304
+ function isNonEmptyString(value) {
305
+ return typeof value === "string" && value.trim().length > 0;
306
+ }
307
+
308
+ /**
309
+ * Check the logical path form without resolving it against the process working directory.
310
+ *
311
+ * 中文:检查 logical path form,不相对 process working directory 做 resolve。
312
+ * English: Check the logical path form without resolving it against the process working directory.
313
+ *
314
+ * @param {unknown} value <lang><zh-CN>候选 artifact/source path。</zh-CN><en>Candidate artifact/source path.</en></lang>
315
+ * @returns {boolean} <lang><zh-CN>是否为 safe relative logical path。</zh-CN><en>Whether it is a safe relative logical path.</en></lang>
316
+ */
317
+ function isSafeRelativePath(value) {
318
+ // <lang><zh-CN>拒绝 drive、scheme、absolute、UNC 和 parent traversal,保持 artifact identity 不泄漏 host locator。</zh-CN><en>Reject drive, scheme, absolute, UNC, and parent traversal forms so artifact identity does not leak a host locator.</en></lang>
319
+ const normalized = typeof value === "string" ? value.replaceAll("\\", "/") : "";
320
+ return Boolean(normalized) && !normalized.startsWith("/") && !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(normalized) && !normalized.split("/").includes("..");
321
+ }
322
+
323
+ /**
324
+ * Restrict policy values to the already documented HTMDoc source-content choices.
325
+ *
326
+ * 中文:将 policy 限制为已文档化的 HTMDoc source-content choices。
327
+ * English: Restrict policy values to the already documented HTMDoc source-content choices.
328
+ *
329
+ * @param {unknown} value <lang><zh-CN>候选 source-content policy。</zh-CN><en>Candidate source-content policy.</en></lang>
330
+ * @returns {boolean} <lang><zh-CN>是否为受支持 policy。</zh-CN><en>Whether it is a supported policy.</en></lang>
331
+ */
332
+ function isSupportedSourcePolicy(value) {
333
+ return value === "none" || value === "reference" || value === "embed";
334
+ }