@hia-doc/css-doc-adapter 0.0.0-stage → 1.0.0-rc.2

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/API.md ADDED
@@ -0,0 +1,106 @@
1
+ # CSS Doc Adapter API
2
+
3
+ 中文摘要:将精确支持的新旧 CSSDoc JSON 提取件投影为核心文档;同源、已证
4
+ PostCSS rule 的片段逐字符保留,未知范围只保留定位。适配器没有 I/O,不读取源码。
5
+
6
+ ## Public exports
7
+
8
+ | Export | Responsibility |
9
+ | --- | --- |
10
+ | `cssExtractionToHiaDocument(artifact, options?)` | Validates an exact supported extraction and projects its symbols into a fresh HIA core document. It does not migrate or rewrite the input. |
11
+ | `assertCssExtractionArtifact(artifact)` | Validates the supported JSON structure and declared relative locators; returns `undefined` on success, throws a fixed `TypeError` on refusal. |
12
+
13
+ The only package export is `.`. There are no binaries or schema subpaths in this
14
+ package. Schema selectors, validators and migration APIs belong to
15
+ `@hia-doc/cssdoc-spec`.
16
+
17
+ ## Inputs
18
+
19
+ `artifact` is an ordinary JSON `hia-cssdoc-extraction`, with matching extraction
20
+ and artifact profile versions: exact `0.1.0-draft` or `1.0.0`. JSON extension
21
+ fields remain supported by their schema. Unknown versions, malformed structures,
22
+ non-JSON values and unsafe declared source locators are refused.
23
+
24
+ `options` is an ordinary object. Optional `id`, `title`, `defaultLocale` and
25
+ `locales` customize document identity and locale selection. The adapter does not
26
+ validate these overrides as a complete core document: callers are responsible
27
+ for choosing suitable values and using the core validator downstream.
28
+
29
+ ## Returns
30
+
31
+ With valid ordinary options, the conversion returns an ordinary JSON
32
+ `hia-core-document` shape `schemaVersion: "0.2.0"`, a root
33
+ node, a new symbols array, source links and source-contract metadata. Each source
34
+ uses `hia-source@0.2.0`, `mode: "link"`. Design-token source language is `json`;
35
+ CSS and Vue-style source language is `css`.
36
+
37
+ Absent optional parent, summary and reference-range fields are omitted, not
38
+ assigned `undefined`; direct core validation must not depend on serialization
39
+ discarding them first.
40
+
41
+ The result is **not a deep clone**. Symbol i18n, ranges and annotation objects,
42
+ diagnostic arrays, producer/source-map metadata and nested symbol metadata can
43
+ share references with the input. The conversion itself never changes them;
44
+ clone before mutating nested output data.
45
+
46
+ ## Defaults
47
+
48
+ - Document id: `cssdoc:<artifact.source.path>`.
49
+ - Title: source filename, unless explicitly overridden.
50
+ - Default locale: override, then artifact locale, then `en`.
51
+ - Locales: normalized, deduplicated union of default, override, artifact and
52
+ symbol locales; underscores normalize to hyphens and invalid locale strings
53
+ are omitted.
54
+ - A missing symbol range preserves the existing reference fallback at `1:1`,
55
+ with no source fragment. This fallback is not a claim of exact source extent.
56
+
57
+ ## Errors
58
+
59
+ Invalid extraction input throws
60
+ `TypeError("Unsupported or invalid CSSDoc extraction.")`; raw schema errors are
61
+ not copied into the public message. A schema-valid but incomplete, reversed or
62
+ out-of-bounds range yields no fragment; it does not cause a slicing exception or
63
+ clamping. Reference ranges are retained for downstream consumers to assess.
64
+
65
+ ## Effects
66
+
67
+ Conversion and assertion perform no filesystem, network, source resolution,
68
+ execution or publication. A provided source string is indexed once per document;
69
+ fragments are slices of that original text. No source text is fetched from paths
70
+ or schema URLs. Shared output references have the ownership limitation above.
71
+
72
+ ## Compatibility
73
+
74
+ Exact old/current artifacts use the same conversion. No migration is implicit;
75
+ the source contract version remains in document metadata. Package version,
76
+ extraction/profile version and core/source-model versions are independent.
77
+ See [migration notes](MIGRATION.md) for the corrected fragment behavior.
78
+
79
+ ## Source linkage
80
+
81
+ Only the established rule provenance obtains a precise fragment: source kind
82
+ `css`, parser `postcss` in `stylesheet` mode, target type `rule`, symbol path equal
83
+ to artifact source path, available `source.sourcesContent`, and complete,
84
+ in-bounds positive integer line/column coordinates. The rule convention matches
85
+ the CSS doc-source-map writer's `1.1.0`: one-based, **inclusive UTF-16** columns.
86
+ PostCSS counts lines at LF only; CR in CRLF remains in the original text, and a
87
+ standalone CR occupies a column. The slice preserves all content inside the
88
+ range, including CRLF, tabs, astral characters and whitespace; it never includes
89
+ same-line neighbors or the attached documentation comment outside the range.
90
+
91
+ Declarations, at-rules, Vue style locations, synthetic design-token `1:1`
92
+ locations, unknown parser provenance, missing columns, foreign source paths and
93
+ invalid ranges receive **no exact fragment**. Their reference information is
94
+ retained. No coordinate proof is inferred from a tag name, artifact version or
95
+ the availability of source text alone. Multiple annotations on a rule project
96
+ the same exact source fragment into their separate symbol identities.
97
+
98
+ ## Privacy
99
+
100
+ The adapter consumes only explicitly supplied content; normal extraction with
101
+ `none` or `reference` does not supply a body and creates no fragments. A body
102
+ already present in an imported artifact is caller-supplied data, not a new
103
+ authorization check. Callers must authorize and sanitize embedded source,
104
+ summaries, annotations, extensions and diagnostics before publication. Valid
105
+ relative paths are a lexical boundary, not a filesystem or symlink sandbox.
106
+ Fixed validation errors do not make the accepted artifact itself public-safe.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
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.
package/MIGRATION.md ADDED
@@ -0,0 +1,26 @@
1
+ # CSS Doc Adapter compatibility
2
+
3
+ Both `hia-cssdoc-extraction@0.1.0-draft` and `@1.0.0` remain exact supported
4
+ inputs. Conversion does not migrate them; use the spec package's explicit pure
5
+ migration when needed. No contract version is changed by the fragment fix.
6
+
7
+ Source fragments now slice **only the precise rule range** from the original
8
+ text using the established PostCSS inclusive UTF-16 coordinates. The previous
9
+ whole-line `split/join/trim` behavior could include adjacent symbols and change
10
+ CRLF/whitespace. Consumers must not depend on those extra characters.
11
+
12
+ Unknown endpoints, columns or provenance, unprobed declaration/at-rule and Vue
13
+ locations, synthetic token locations, foreign source paths and out-of-bounds or
14
+ reversed ranges retain references but do not produce an alleged exact fragment.
15
+ Design-token references report JSON language. No source is fetched to fill a gap.
16
+
17
+ Absent optional `parentId`, `summary` and reference `range` properties are omitted
18
+ instead of assigned `undefined`, allowing the in-memory result to satisfy the
19
+ core ordinary-JSON boundary before any file serialization.
20
+
21
+ The output remains a shallow projection with shared nested i18n, range, diagnostic
22
+ and metadata objects. Clone before mutating output. For complete ownership,
23
+ defaults, errors, source precision and privacy responsibilities, see [API](API.md).
24
+
25
+ 中文:修复按整行截取导致的串入邻居与换行损失,不升级契约;未知坐标不生成
26
+ 高置信片段。新旧读取、调用者提供的正文和输入不变规则保持,详见包内 API。
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # CSS Doc Adapter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## Supported runtime
4
+
5
+ Current source supports Node.js `^22.23.4 || ^24.22.1`. Release checks use
6
+ Node.js 22.23.4 and 24.22.1 on Windows and Ubuntu; actual package qualification
7
+ and npm availability remain separate. The repository default is Node.js 24.22.1.
8
+
9
+ 中文:当前源码运行范围为上述两条已确认版本线,CI/安装验收与实际npm发布分别核对。
10
+
11
+
12
+ Converts CSSDoc extraction artifacts into HIA core documents.
13
+
14
+ Current writers/readers coordinate `hia-cssdoc-extraction@1.0.0` with exact `0.1.0-draft` JSON compatibility; unsupported or invalid reader inputs fail. See the repository migration guide for structure and source-precision limits.
15
+
16
+ See the packaged [API reference](API.md) and [compatibility notes](MIGRATION.md)
17
+ for input/output ownership, defaults, errors and privacy. Embedded fragments use
18
+ the original text and proven PostCSS rule coordinates, preserving CRLF and
19
+ whitespace while excluding same-line neighbors. Unproven locations remain
20
+ references without invented exact fragments. Design-token references use JSON.
21
+
22
+ 中文:已证规则按原文精确截取;未知坐标只保留定位。包内文档与实际归档同步。
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@hia-doc/css-doc-adapter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-rc.2",
4
+ "description": "Converts CSSDoc extraction artifacts to HIA core documents.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": "./src/index.mjs"
9
+ },
10
+ "dependencies": {
11
+ "@hia-doc/cssdoc-spec": "1.0.0-rc.2"
12
+ },
13
+ "engines": {
14
+ "node": "^22.23.4 || ^24.22.1"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "README.md",
19
+ "API.md",
20
+ "MIGRATION.md",
21
+ "LICENSE"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public",
25
+ "registry": "https://registry.npmjs.org/"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/mandolin/hia-cssdoc.git",
30
+ "directory": "packages/css-doc-adapter"
31
+ },
32
+ "homepage": "https://github.com/mandolin/hia-cssdoc/tree/main/packages/css-doc-adapter",
33
+ "bugs": {
34
+ "url": "https://github.com/mandolin/hia-cssdoc/issues"
35
+ },
36
+ "keywords": [
37
+ "documentation",
38
+ "css",
39
+ "hia"
40
+ ]
41
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * @file CSSDoc JSON 到核心文档的纯投影;仅已证同源规则得到逐字符片段。
3
+ * @lang en Pure CSSDoc JSON to core-document projection; only proven same-source rules receive character-exact fragments.
4
+ */
5
+ import { validateCssDocExtraction } from "@hia-doc/cssdoc-spec";
6
+
7
+ const HIA_CORE_SCHEMA_VERSION = "0.2.0";
8
+ const HIA_SOURCE_MODEL = "hia-source";
9
+ const HIA_SOURCE_MODEL_VERSION = "0.2.0";
10
+
11
+ /**
12
+ * @lang zh-CN 校验精确旧版或当前CSS提取件后构造核心文档,保留符号身份及语言和来源关联。
13
+ * @lang en Constructs a core document after validating an exact legacy or current CSS extraction, retaining symbol identities, locales and source associations.
14
+ * @param {object} artifact <lang><zh-CN>精确已支持旧/新JSON提取件,扩展必须为JSON。</zh-CN><en>Exactly supported old/current JSON extraction with JSON extensions.</en></lang> @param {object} [options] <lang><zh-CN>身份/标题/语言覆写。</zh-CN><en>Identity/title/locale overrides.</en></lang> @returns {object} <lang><zh-CN>新核心文档;i18n与部分metadata仍共享输入嵌套对象;无I/O。</zh-CN><en>Fresh core document; i18n and some metadata share nested input objects; no I/O.</en></lang> @throws {TypeError} <lang><zh-CN>未知版本或不合法结构拒绝。</zh-CN><en>Rejects unknown versions or invalid structure.</en></lang>
15
+ */
16
+ export function cssExtractionToHiaDocument(artifact, options = {}) {
17
+ assertCssExtractionArtifact(artifact);
18
+ // <lang><zh-CN>标题按调用方覆写或来源文件名确定,不读取文件。</zh-CN><en>The caller override or source filename determines the title without file reads.</en></lang>
19
+ const title = options.title ?? titleFromPath(artifact.source.path);
20
+ // <lang><zh-CN>原文只索引一次,避免每个符号重复扫描整份嵌入源码;索引仅在本次调用中存在。</zh-CN><en>Index the original text once instead of rescanning all embedded source for every symbol; the index is call-local.</en></lang>
21
+ const sourceLines = typeof artifact.source.sourcesContent === "string" ? indexSourceLines(artifact.source.sourcesContent) : null;
22
+ // <lang><zh-CN>每个符号新建投影,多个标签可共享同一来源范围但保留各自身份。</zh-CN><en>Create each symbol projection separately; multiple tags may share a source range while keeping their own identities.</en></lang>
23
+ const symbols = artifact.symbols.map((symbol) => mapSymbol(symbol, artifact, sourceLines));
24
+ // <lang><zh-CN>沿用调用方、工件、英语的既有回退顺序。</zh-CN><en>Retain the existing caller, artifact, English fallback order.</en></lang>
25
+ const defaultLocale = options.defaultLocale ?? artifact.defaultLocale ?? "en";
26
+
27
+ return {
28
+ schemaVersion: HIA_CORE_SCHEMA_VERSION,
29
+ id: options.id ?? `cssdoc:${artifact.source.path}`,
30
+ title,
31
+ defaultLocale,
32
+ locales: collectDocumentLocales(options.locales, artifact.locales, symbols, defaultLocale),
33
+ nodes: [
34
+ {
35
+ id: "root",
36
+ kind: "root",
37
+ title,
38
+ symbolIds: symbols.map((symbol) => symbol.id)
39
+ }
40
+ ],
41
+ symbols,
42
+ diagnostics: artifact.diagnostics ?? [],
43
+ metadata: {
44
+ sourceContract: artifact.contract,
45
+ sourceContractVersion: artifact.contractVersion,
46
+ producer: artifact.producer,
47
+ sourceMap: artifact.sourceMap ?? null
48
+ }
49
+ };
50
+ }
51
+
52
+ /**
53
+ * @lang zh-CN 校验CSS提取件的受支持精确身份与JSON结构,失败时抛出固定公开TypeError。
54
+ * @lang en Validates a CSS extraction's supported exact identity and JSON structure, throwing a fixed public TypeError on failure.
55
+ * @param {unknown} artifact <lang><zh-CN>普通JSON提取工件。</zh-CN><en>Ordinary JSON extraction artifact.</en></lang> @returns {void} <lang><zh-CN>精确旧/新结构有效时无值且不改输入。</zh-CN><en>No value for valid exact old/current structure; input unchanged.</en></lang> @throws {TypeError} <lang><zh-CN>固定公开拒绝,不回显schema诊断。</zh-CN><en>Fixed public refusal without raw schema diagnostics.</en></lang>
56
+ */
57
+ export function assertCssExtractionArtifact(artifact) {
58
+ if (validateCssDocExtraction(artifact).length) throw new TypeError("Unsupported or invalid CSSDoc extraction.");
59
+ }
60
+
61
+ /**
62
+ * @param {object} symbol <lang><zh-CN>已验证符号,不修改输入。</zh-CN><en>Validated symbol, left unchanged.</en></lang>
63
+ * @param {object} artifact <lang><zh-CN>提供来源正文及既有解析器证据的工件。</zh-CN><en>Artifact providing source text and established parser evidence.</en></lang>
64
+ * @param {Array<{start:number,end:number}>|null} sourceLines <lang><zh-CN>PostCSS原文UTF-16行索引,end不含LF。</zh-CN><en>PostCSS original UTF-16 line index whose ends exclude LF.</en></lang>
65
+ * @returns {object} <lang><zh-CN>新符号;定位范围透传,未知精度不发片段,部分嵌套metadata/i18n共享。</zh-CN><en>New symbol retaining reference ranges; unknown precision emits no fragment; some nested metadata/i18n is shared.</en></lang>
66
+ */
67
+ function mapSymbol(symbol, artifact, sourceLines) {
68
+ // <lang><zh-CN>定位可引用其它来源,但片段只能来自工件所带同路径正文。</zh-CN><en>References may address another source, but fragments require the artifact's own same-path text.</en></lang>
69
+ const sourcePath = symbol.source?.path ?? artifact.source.path;
70
+ // <lang><zh-CN>缺范围保持既有定位回退,不合成片段坐标。</zh-CN><en>Missing ranges keep the existing reference fallback without synthesizing fragment coordinates.</en></lang>
71
+ const range = symbol.source?.range ?? null;
72
+ // <lang><zh-CN>与1.1.0 map的已证rule分支一致;不外推Vue、声明、at-rule或token占位的终点/列单位。</zh-CN><en>Match the proven rule branch of the 1.1.0 map without extrapolating endpoint/column semantics to Vue, declarations, at-rules or token placeholders.</en></lang>
73
+ const provenRule = artifact.source.kind === "css"
74
+ && artifact.metadata?.parser?.name === "postcss"
75
+ && artifact.metadata.parser.mode === "stylesheet"
76
+ && symbol.metadata?.target?.type === "rule";
77
+ // <lang><zh-CN>坐标完整且在原文内时按包含式UTF-16切片;不修剪、不夹取、不回退整行。</zh-CN><en>Slice complete in-bounds coordinates as inclusive UTF-16, without trimming, clamping or whole-line fallback.</en></lang>
78
+ const fragmentContent = provenRule && range && sourceLines && sourcePath === artifact.source.path
79
+ ? extractRangeContent(artifact.source.sourcesContent, sourceLines, range)
80
+ : null;
81
+ // <lang><zh-CN>设计令牌的实际来源是JSON,其合成范围仍只用于定位。</zh-CN><en>Design tokens originate in JSON; their synthetic ranges remain reference-only.</en></lang>
82
+ const sourceLanguage = artifact.source.kind === "design-tokens" ? "json" : "css";
83
+ // <lang><zh-CN>缺省摘要在JSON中应省略;不能把undefined留给序列化静默擦除。</zh-CN><en>Absent summaries must be omitted in JSON rather than left as undefined for serialization to erase silently.</en></lang>
84
+ const summary = symbol.i18n?.fields?.description?.defaultText ?? symbol.summary;
85
+ // <lang><zh-CN>核心来源模型维持link模式;只有上面已证的正文能进入高置信片段。</zh-CN><en>The core source model stays in link mode; only text proven above may enter high-confidence fragments.</en></lang>
86
+ const mapped = {
87
+ id: symbol.id,
88
+ name: symbol.name,
89
+ kind: symbol.kind,
90
+ ...(symbol.parentId === undefined ? {} : { parentId: symbol.parentId }),
91
+ ...(summary === undefined ? {} : { summary }),
92
+ source: {
93
+ model: HIA_SOURCE_MODEL,
94
+ modelVersion: HIA_SOURCE_MODEL_VERSION,
95
+ mode: "link",
96
+ definedIn: {
97
+ kind: "defined-in",
98
+ relativePath: sourcePath,
99
+ language: sourceLanguage,
100
+ position: range?.start ?? { line: 1, column: 1 },
101
+ ...(range ? { range } : {})
102
+ },
103
+ fragments: range && fragmentContent
104
+ ? [
105
+ {
106
+ kind: "source-fragment",
107
+ id: `${symbol.id}:source`,
108
+ relativePath: sourcePath,
109
+ language: sourceLanguage,
110
+ range,
111
+ content: fragmentContent,
112
+ rangeSource: "parser",
113
+ confidence: "high",
114
+ origin: {
115
+ contract: artifact.contract,
116
+ annotation: symbol.annotation ?? null
117
+ }
118
+ }
119
+ ]
120
+ : []
121
+ },
122
+ diagnostics: symbol.diagnostics ?? [],
123
+ metadata: {
124
+ cssdoc: {
125
+ annotation: symbol.annotation ?? null,
126
+ ...symbol.metadata
127
+ }
128
+ }
129
+ };
130
+ if (symbol.i18n) {
131
+ mapped.i18n = symbol.i18n;
132
+ }
133
+ return mapped;
134
+ }
135
+
136
+ function collectDocumentLocales(optionLocales, artifactLocales, symbols, defaultLocale) {
137
+ const locales = [
138
+ defaultLocale,
139
+ ...(Array.isArray(optionLocales) ? optionLocales : []),
140
+ ...(Array.isArray(artifactLocales) ? artifactLocales : [])
141
+ ];
142
+ for (const symbol of symbols) {
143
+ locales.push(...(Array.isArray(symbol.i18n?.locales) ? symbol.i18n.locales : []));
144
+ }
145
+ return [...new Set(locales.map((locale) => normalizeLocale(locale)).filter(Boolean))];
146
+ }
147
+
148
+ function normalizeLocale(value) {
149
+ const locale = String(value ?? "").trim().replace(/_/g, "-");
150
+ return /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/.test(locale) ? locale : "";
151
+ }
152
+
153
+ function titleFromPath(sourcePath) {
154
+ return sourcePath.split("/").at(-1) || "CSSDoc Document";
155
+ }
156
+
157
+ /**
158
+ * @param {string} source <lang><zh-CN>已获提供的原始源码。</zh-CN><en>Provided original source text.</en></lang>
159
+ * @returns {Array<{start:number,end:number}>} <lang><zh-CN>零基UTF-16行边界,按PostCSS仅以LF分行;保留CR/空行,时间/空间线性,无I/O。</zh-CN><en>Zero-based UTF-16 bounds using PostCSS LF-only line splitting, retaining CR/empty lines; linear time/space without I/O.</en></lang>
160
+ */
161
+ function indexSourceLines(source) {
162
+ // <lang><zh-CN>索引只存边界,不复制或规范化源码正文。</zh-CN><en>Store boundaries only, without copying or normalizing source text.</en></lang>
163
+ const lines = [];
164
+ // <lang><zh-CN>PostCSS input.fromOffset仅按LF递增行号;独立CR仍占同一行的UTF-16列。</zh-CN><en>PostCSS input.fromOffset increments lines only at LF; standalone CR occupies a UTF-16 column on the same line.</en></lang>
165
+ let start = 0;
166
+ // <lang><zh-CN>match.index为原始UTF-16偏移,不能用拆行再join重建文本。</zh-CN><en>match.index is an original UTF-16 offset; never reconstruct text by splitting and joining lines.</en></lang>
167
+ for (const match of source.matchAll(/\n/g)) {
168
+ lines.push({ start, end: match.index });
169
+ start = match.index + match[0].length;
170
+ }
171
+ lines.push({ start, end: source.length });
172
+ return lines;
173
+ }
174
+
175
+ /**
176
+ * @param {string} source <lang><zh-CN>未改写原文。</zh-CN><en>Unmodified source.</en></lang>
177
+ * @param {Array<{start:number,end:number}>} lines <lang><zh-CN>同一正文的一次性行索引。</zh-CN><en>Once-built line index for that same text.</en></lang>
178
+ * @param {object} range <lang><zh-CN>来自已证PostCSS rule的一基包含式UTF-16范围。</zh-CN><en>One-based inclusive UTF-16 range from a proven PostCSS rule.</en></lang>
179
+ * @returns {string|null} <lang><zh-CN>精确原文子串;不完整、反向或越界时null,不抛错或夹取。</zh-CN><en>Exact original substring; null for incomplete, reversed or out-of-bounds ranges, without throwing or clamping.</en></lang>
180
+ */
181
+ function extractRangeContent(source, lines, range) {
182
+ // <lang><zh-CN>schema允许省略end/column,因此精确片段另核四个安全正整数。</zh-CN><en>The schema permits omitted end/column, so exact fragments separately require four safe positive integers.</en></lang>
183
+ if (![range.start?.line, range.start?.column, range.end?.line, range.end?.column].every((value) => Number.isSafeInteger(value) && value > 0)) return null;
184
+ // <lang><zh-CN>行号越界不借JavaScript的slice夹取行为生成看似有效的文本。</zh-CN><en>Do not let JavaScript slice clamping turn out-of-bounds lines into plausible text.</en></lang>
185
+ const startLine = lines[range.start.line - 1];
186
+ const endLine = lines[range.end.line - 1];
187
+ if (!startLine || !endLine || range.start.column > startLine.end - startLine.start || range.end.column > endLine.end - endLine.start) return null;
188
+ // <lang><zh-CN>包含终点加一转为slice的排除式偏移;数值不跨入换行或相邻规则。</zh-CN><en>Convert the inclusive end to a slice-exclusive offset without entering newlines or neighboring rules.</en></lang>
189
+ const start = startLine.start + range.start.column - 1;
190
+ const end = endLine.start + range.end.column;
191
+ return end > start ? source.slice(start, end) : null;
192
+ }