@hia-doc/cssdoc-runner 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 +108 -0
- package/LICENSE +21 -0
- package/MIGRATION.md +81 -0
- package/README.md +165 -2
- package/package.json +50 -4
- package/src/cli.mjs +91 -0
- package/src/command-content.mjs +218 -0
- package/src/command-documentation/command.schema.json +1466 -0
- package/src/command-documentation/description.json +1860 -0
- package/src/command-documentation/document.hia.json +2699 -0
- package/src/command-documentation/document.schema.json +817 -0
- package/src/command-documentation/generation.json +12 -0
- package/src/command-documentation/help.mjs +16 -0
- package/src/command-documentation/observations.json +62 -0
- package/src/config-compatibility.mjs +99 -0
- package/src/index.mjs +405 -0
- package/src/metadata.mjs +27 -0
- package/src/schema-legacy.mjs +57 -0
- package/src/schema.mjs +86 -0
- package/src/schemas/cssdoc-config-0.1.0-draft.schema.json +116 -0
- package/src/schemas/cssdoc-config-1.0.0.schema.json +115 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"coreContractVersion": "1.0.0",
|
|
3
|
+
"commandContractVersion": "0.1.0-draft",
|
|
4
|
+
"outputs": {
|
|
5
|
+
"description.json": "db86a5dab64faea9576f4728656a0237c4488c6656a306a0fc07bde68b5fadcc",
|
|
6
|
+
"observations.json": "13896166286bb577a70122ca3a81dee7d34688e3b2d253b23310bdcc69b8a3ae",
|
|
7
|
+
"document.hia.json": "be24faf1890cba15e05e12467c66e72e532fefc39ad8ef823070c9063d6cdd1b",
|
|
8
|
+
"command.schema.json": "c291f19d9bdbbd61db167edb9d268af83e7f36ec320263b13e211c798db70c32",
|
|
9
|
+
"document.schema.json": "404d90c3bd2b2b90e4723767c75c3a3bf8e713786a81c9583f7c93f5f4938895",
|
|
10
|
+
"help.mjs": "07e86d500ab31a5ebed3b6e8f2044611af4e5862f8ad1e97f5efed102d4a0e15"
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file
|
|
3
|
+
* @lang zh-CN 由共享命令内容生成的静态帮助,通过commands:build重新生成。
|
|
4
|
+
* @lang en Static help generated from shared command content, regenerated with commands:build.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* @lang zh-CN 80列纯文本命令帮助。
|
|
8
|
+
* @lang en 80-column plain-text command help.
|
|
9
|
+
*/
|
|
10
|
+
export const CSSDOC_HELP_80 = "HIA-Documentation-Sys · cssdoc\n提取CSS与设计令牌文档 / Extract CSS and design-token documentation\n\n用法 / Usage\n cssdoc --config cssdoc.config.json\n cssdoc [options] <input...>\n\n参数 / Options\n -c, --config <path>\n 从JSON配置构造请求。 / Build a request from JSON configuration.\n -k, --kind <kind>\n 直接输入的类型,省略时从输入推断。\n Direct-input kind, inferred from input when omitted.\n -o, --out-dir <path>\n 配置模式非空值覆盖输出;直接模式缺省dist/cssdoc,空字符串为工作区根。\n Nonempty values override configured output; direct mode defaults to\n dist/cssdoc, with an empty string selecting the workspace root.\n --workspace-root <path>\n 直接模式的工作区根,省略时使用调用目录。\n Workspace root for direct mode, defaulting to cwd.\n --sources-content-policy <none|reference|embed>\n 直接模式缺省none;配置模式省略或空值时保留原值,非空值覆盖。\n Direct mode defaults to none; config mode retains its policy for omission or\n empty strings and uses nonempty overrides.\n --no-doc-source-map\n 提供时关闭地图;省略时直接模式生成地图,配置模式保留原值。\n Supplying the flag disables maps; omission enables direct-mode maps and\n retains the configured value.\n -h, --help\n 输出帮助并退出0。 / Print help and exit 0.\n -v, --version\n 输出运行器版本并退出0。 / Print runner version and exit 0.\n\n位置输入 / Positional inputs\n <input...>\n 直接模式至少一个相对工作区的输入;配置模式忽略。\n Direct mode requires at least one workspace-relative input; config mode\n ignores positional inputs.\n\n配置与副作用 / Configuration and effects\n 配置模式中,CLI可覆盖out-dir、sources-content-policy及no-doc-source-map。\n In config mode CLI can override out-dir, sources-content-policy and\n no-doc-source-map.\n kind及workspace-root用于直接模式;配置模式忽略它们和位置输入。\n kind and workspace-root apply to direct mode; config mode ignores them and\n positional inputs.\n 配置文件相对调用目录,配置工作区相对配置目录;输出相对所选工作区。\n Config paths use cwd, configured workspaces use the config directory, and\n output uses the selected workspace.\n 运行会创建目录并写工件,失败时可能已写部分文件。embed策略会写入获准公开的源码\n 正文。\n Runs create directories and artifacts; failures may leave partial output. The\n embed policy includes source bodies authorized for publication.\n Node严格解析先于帮助;未知、缺值或类型错误返回1。重复带值选项取最后值,--之后\n 作为位置输入。\n Node strict parsing precedes help; unknown, missing or invalid option values\n exit 1. Repeated value options use the last value, and tokens after -- are\n positional inputs.\n\n退出码 / Exit codes\n 0 成功、帮助或版本 / Success, help or version\n 1 参数、配置或构建失败 / Argument, configuration or build failure\n\n示例 / Example\n cssdoc --config cssdoc.config.json\n\n离线完整说明 / Complete offline reference\n @hia-doc/cssdoc-runner/README.md\n";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @lang zh-CN 120列纯文本命令帮助。
|
|
14
|
+
* @lang en 120-column plain-text command help.
|
|
15
|
+
*/
|
|
16
|
+
export const CSSDOC_HELP_120 = "HIA-Documentation-Sys · cssdoc\n提取CSS与设计令牌文档 / Extract CSS and design-token documentation\n\n用法 / Usage\n cssdoc --config cssdoc.config.json\n cssdoc [options] <input...>\n\n参数 / Options\n -c, --config <path>\n 从JSON配置构造请求。 / Build a request from JSON configuration.\n -k, --kind <kind>\n 直接输入的类型,省略时从输入推断。\n Direct-input kind, inferred from input when omitted.\n -o, --out-dir <path>\n 配置模式非空值覆盖输出;直接模式缺省dist/cssdoc,空字符串为工作区根。\n Nonempty values override configured output; direct mode defaults to dist/cssdoc, with an empty string selecting the\n workspace root.\n --workspace-root <path>\n 直接模式的工作区根,省略时使用调用目录。\n Workspace root for direct mode, defaulting to cwd.\n --sources-content-policy <none|reference|embed>\n 直接模式缺省none;配置模式省略或空值时保留原值,非空值覆盖。\n Direct mode defaults to none; config mode retains its policy for omission or empty strings and uses nonempty\n overrides.\n --no-doc-source-map\n 提供时关闭地图;省略时直接模式生成地图,配置模式保留原值。\n Supplying the flag disables maps; omission enables direct-mode maps and retains the configured value.\n -h, --help\n 输出帮助并退出0。 / Print help and exit 0.\n -v, --version\n 输出运行器版本并退出0。 / Print runner version and exit 0.\n\n位置输入 / Positional inputs\n <input...>\n 直接模式至少一个相对工作区的输入;配置模式忽略。\n Direct mode requires at least one workspace-relative input; config mode ignores positional inputs.\n\n配置与副作用 / Configuration and effects\n 配置模式中,CLI可覆盖out-dir、sources-content-policy及no-doc-source-map。\n In config mode CLI can override out-dir, sources-content-policy and no-doc-source-map.\n kind及workspace-root用于直接模式;配置模式忽略它们和位置输入。\n kind and workspace-root apply to direct mode; config mode ignores them and positional inputs.\n 配置文件相对调用目录,配置工作区相对配置目录;输出相对所选工作区。\n Config paths use cwd, configured workspaces use the config directory, and output uses the selected workspace.\n 运行会创建目录并写工件,失败时可能已写部分文件。embed策略会写入获准公开的源码正文。\n Runs create directories and artifacts; failures may leave partial output. The embed policy includes source bodies\n authorized for publication.\n Node严格解析先于帮助;未知、缺值或类型错误返回1。重复带值选项取最后值,--之后作为位置输入。\n Node strict parsing precedes help; unknown, missing or invalid option values exit 1. Repeated value options use the\n last value, and tokens after -- are positional inputs.\n\n退出码 / Exit codes\n 0 成功、帮助或版本 / Success, help or version\n 1 参数、配置或构建失败 / Argument, configuration or build failure\n\n示例 / Example\n cssdoc --config cssdoc.config.json\n\n离线完整说明 / Complete offline reference\n @hia-doc/cssdoc-runner/README.md\n";
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"commandId": "cssdoc",
|
|
4
|
+
"sourceDigests": {
|
|
5
|
+
"src/cli.mjs": "b8dc623556d60300123586ff0d404f5ad171f06f69d6fc848d2cc91c6c16777b",
|
|
6
|
+
"src/command-content.mjs": "97fc8e337e486edf00433c505195704f3d47ebb48cf146b78559d2c123751205",
|
|
7
|
+
"src/metadata.mjs": "27aea061883a3105fe28271f6fd2a1e4b554a73cbfd114fdf19e081ed5447e62",
|
|
8
|
+
"src/index.mjs": "e7b16c94a22b3b6a7335ce3e60a6471d7a79c614ee573c6873d8aba27e529b25",
|
|
9
|
+
"src/schema.mjs": "65a9c7f1765206e569d0da91624884b0cebabce64cb91d0ffc7f8aaf6f304894",
|
|
10
|
+
"src/config-compatibility.mjs": "48e84ecf7316979854c3ae78fcc38caa7a7dbc78d31f3311856614b7f4369bfc",
|
|
11
|
+
"src/schemas/cssdoc-config-0.1.0-draft.schema.json": "7467524764faad0ab3f8a1a9248e022d097198d9584fe179ba9bae9f247a5fe0",
|
|
12
|
+
"src/schemas/cssdoc-config-1.0.0.schema.json": "fef1ee7048982d62f69e7cb805eed6f429e66af552a6d87b7070de44e3d739dc",
|
|
13
|
+
"README.md": "ef98236f15a557579ddaeedf78603e8cb4f3c9495d93d1f8aef2a677ca8fc4a2",
|
|
14
|
+
"package.json": "152921714e2541ffa5922ef7573c72170ff23585e47f1e86dfc5a19bee8d698e"
|
|
15
|
+
},
|
|
16
|
+
"options": [
|
|
17
|
+
{
|
|
18
|
+
"name": "config",
|
|
19
|
+
"valueType": "string",
|
|
20
|
+
"short": "c"
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"name": "help",
|
|
24
|
+
"valueType": "boolean",
|
|
25
|
+
"short": "h"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"name": "kind",
|
|
29
|
+
"valueType": "string",
|
|
30
|
+
"short": "k"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"name": "no-doc-source-map",
|
|
34
|
+
"valueType": "boolean"
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"name": "out-dir",
|
|
38
|
+
"valueType": "string",
|
|
39
|
+
"short": "o"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"name": "sources-content-policy",
|
|
43
|
+
"valueType": "string"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"name": "version",
|
|
47
|
+
"valueType": "boolean",
|
|
48
|
+
"short": "v"
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
"name": "workspace-root",
|
|
52
|
+
"valueType": "string"
|
|
53
|
+
}
|
|
54
|
+
],
|
|
55
|
+
"positionals": [
|
|
56
|
+
{
|
|
57
|
+
"name": "positionals",
|
|
58
|
+
"valueType": "string"
|
|
59
|
+
}
|
|
60
|
+
]
|
|
61
|
+
}
|
|
62
|
+
]
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file Exact config schemas, compatible reading and explicit migration.
|
|
3
|
+
* @lang zh-CN 纯内存读取/迁移,不读配置路径或 schema URL;旧 schema 原字节不改。
|
|
4
|
+
* @lang en Pure in-memory reading/migration without reading config paths or schema URLs; historical schema bytes stay unchanged.
|
|
5
|
+
*/
|
|
6
|
+
import Ajv2020 from "ajv/dist/2020.js";
|
|
7
|
+
import { CSSDOC_CONFIG_JSON_SCHEMA, CSSDOC_CONFIG_SCHEMA_ID, CSSDOC_LEGACY_CONFIG_JSON_SCHEMA, CSSDOC_LEGACY_CONFIG_SCHEMA_ID } from "./schema.mjs";
|
|
8
|
+
|
|
9
|
+
/** @lang zh-CN 不回显 caller 字段或 Ajv 错误原文。 @lang en Excludes caller fields and raw Ajv errors. */
|
|
10
|
+
const failure = "CSSDoc config must match an exact supported identity and declared JSON structure.";
|
|
11
|
+
/** @lang zh-CN 固定本地 schema 的懒编译缓存,不使用 loadSchema 或网络。 @lang en Lazy compilation cache of a fixed local schema with no loadSchema or network. */
|
|
12
|
+
let currentValidator;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @lang zh-CN 按精确配置版本或Schema身份返回对应CSS文档配置Schema对象,未知身份返回undefined。
|
|
16
|
+
* @lang en Returns the CSS documentation config schema object selected by an exact version or schema identity, or undefined for an unknown identity.
|
|
17
|
+
* @param {string} identity <lang><zh-CN>精确版本或 schema ID。</zh-CN><en>Exact version or schema ID.</en></lang>
|
|
18
|
+
* @returns {object|undefined} <lang><zh-CN>原 schema;未知身份不猜默认。</zh-CN><en>Original schema; unknown identities have no guessed default.</en></lang>
|
|
19
|
+
*/
|
|
20
|
+
export function getCssDocConfigSchema(identity) {
|
|
21
|
+
if (identity === "1.0.0" || identity === CSSDOC_CONFIG_SCHEMA_ID) return CSSDOC_CONFIG_JSON_SCHEMA;
|
|
22
|
+
if (identity === "0.1.0-draft" || identity === CSSDOC_LEGACY_CONFIG_SCHEMA_ID) return CSSDOC_LEGACY_CONFIG_JSON_SCHEMA;
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {unknown} value <lang><zh-CN>精确旧/新配置 JSON。</zh-CN><en>Exact legacy/current config JSON.</en></lang>
|
|
28
|
+
* @returns {void} <lang><zh-CN>有效时无值,不修改输入;旧 loader 默认按已确认兼容规则保留。</zh-CN><en>Returns no value when valid without mutation; legacy loader defaults follow confirmed compatibility rules.</en></lang>
|
|
29
|
+
* @throws {TypeError} <lang><zh-CN>身份或目标兼容结构不合法时固定拒绝。</zh-CN><en>Fixed refusal for invalid identity or compatible structure.</en></lang>
|
|
30
|
+
* @lang zh-CN 内部 loader helper,不从包根额外暴露 API。
|
|
31
|
+
* @lang en Internal loader helper, not an additional package-root API.
|
|
32
|
+
*/
|
|
33
|
+
export function validateCssDocConfigForReading(value) {
|
|
34
|
+
try {
|
|
35
|
+
// <lang><zh-CN>克隆后才临时协调验证视图;不重标 caller 对象或宣称旧 schema 接受默认缺省。</zh-CN><en>Only coordinate a cloned validation view, never relabeling caller data or claiming the old schema permits omitted defaults.</en></lang>
|
|
36
|
+
// <lang><zh-CN>独立JSON副本是验证/迁移视图,调用方所有权和扩展数据保持。</zh-CN><en>The independent JSON copy is a validation/migration view preserving caller ownership and extension data.</en></lang>
|
|
37
|
+
const json = cloneJson(value);
|
|
38
|
+
// <lang><zh-CN>仅选择已知精确身份,无版本范围猜测。</zh-CN><en>Select only known exact identities without version-range guesses.</en></lang>
|
|
39
|
+
const schema = getCssDocConfigSchema(json?.schemaVersion);
|
|
40
|
+
if (!schema || (json.$schema !== undefined && json.$schema !== schema.$id)) throw new TypeError(failure);
|
|
41
|
+
json.schemaVersion = "1.0.0";
|
|
42
|
+
if (json.$schema !== undefined) json.$schema = CSSDOC_CONFIG_SCHEMA_ID;
|
|
43
|
+
if (!currentValidator) {
|
|
44
|
+
const ajv = new Ajv2020({ strict: false, allErrors: true });
|
|
45
|
+
currentValidator = ajv.compile(CSSDOC_CONFIG_JSON_SCHEMA);
|
|
46
|
+
}
|
|
47
|
+
if (!currentValidator(json)) throw new TypeError(failure);
|
|
48
|
+
} catch { throw new TypeError(failure); }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @lang zh-CN 校验旧版普通JSON配置并在独立副本中协调当前版本与已有Schema引用,保留省略字段。
|
|
53
|
+
* @lang en Validates an ordinary-JSON legacy config and coordinates the current version and any existing schema reference in a detached copy while preserving omitted fields.
|
|
54
|
+
* @param {unknown} value <lang><zh-CN>精确旧配置的普通 JSON,允许已有 loader 的省略默认。</zh-CN><en>Ordinary JSON of an exact legacy config, allowing omissions supported by the existing loader.</en></lang>
|
|
55
|
+
* @returns {object} <lang><zh-CN>只协调 schemaVersion/已有 $schema 的新副本,保留省略字段与全部内容。</zh-CN><en>Fresh copy coordinating only schemaVersion/existing $schema while preserving omissions and all content.</en></lang>
|
|
56
|
+
* @throws {TypeError} <lang><zh-CN>未知/当前版本、非 JSON 或目标验证失败时固定拒绝。</zh-CN><en>Fixed refusal for unknown/current versions, non-JSON or failed target validation.</en></lang>
|
|
57
|
+
*/
|
|
58
|
+
export function migrateCssDocConfig(value) {
|
|
59
|
+
try {
|
|
60
|
+
// <lang><zh-CN>独立JSON副本是验证/迁移视图,调用方所有权和扩展数据保持。</zh-CN><en>The independent JSON copy is a validation/migration view preserving caller ownership and extension data.</en></lang>
|
|
61
|
+
const json = cloneJson(value);
|
|
62
|
+
if (json.schemaVersion !== "0.1.0-draft") throw new TypeError(failure);
|
|
63
|
+
validateCssDocConfigForReading(json);
|
|
64
|
+
json.schemaVersion = "1.0.0";
|
|
65
|
+
if (json.$schema !== undefined) json.$schema = CSSDOC_CONFIG_SCHEMA_ID;
|
|
66
|
+
validateCssDocConfigForReading(json);
|
|
67
|
+
return json;
|
|
68
|
+
} catch { throw new TypeError(failure); }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {unknown} value <lang><zh-CN>普通 JSON 值。</zh-CN><en>Ordinary JSON value.</en></lang>
|
|
73
|
+
* @param {Set<object>} [active] <lang><zh-CN>当前递归栈,不跨调用共享。</zh-CN><en>Current recursion stack, never shared across calls.</en></lang>
|
|
74
|
+
* @returns {unknown} <lang><zh-CN>不包含 getter、原型行为或共享可变容器的副本。</zh-CN><en>Copy without getters, prototype behavior or shared mutable containers.</en></lang>
|
|
75
|
+
* @throws {TypeError} <lang><zh-CN>拒绝所有非 JSON 值/稀疏数组/隐藏属性。</zh-CN><en>Rejects non-JSON values, sparse arrays and hidden properties.</en></lang>
|
|
76
|
+
*/
|
|
77
|
+
function cloneJson(value, active = new Set()) {
|
|
78
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
79
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
80
|
+
if (!value || typeof value !== "object" || active.has(value)) throw new TypeError(failure);
|
|
81
|
+
// <lang><zh-CN>记录容器形状,随后按描述符复制;递归栈用于拒绝不可无损复制的循环。</zh-CN><en>Track container shape for descriptor copying; the recursion stack rejects cycles that cannot be copied losslessly.</en></lang>
|
|
82
|
+
const array = Array.isArray(value);
|
|
83
|
+
if (!array && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) throw new TypeError(failure);
|
|
84
|
+
active.add(value);
|
|
85
|
+
try {
|
|
86
|
+
// <lang><zh-CN>描述符先检查,绝不通过普通属性读取触发用户访问器。</zh-CN><en>Inspect descriptors first, never triggering user accessors through ordinary property reads.</en></lang>
|
|
87
|
+
// <lang><zh-CN>新容器不共享输入可变状态;逐字段描述符避免getter执行。</zh-CN><en>The fresh container shares no mutable input state; descriptors prevent getter execution.</en></lang>
|
|
88
|
+
const result = array ? [] : {};
|
|
89
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
90
|
+
if (array && key === "length") continue;
|
|
91
|
+
// <lang><zh-CN>只接收可枚举数据字段,隐藏属性/访问器/非JSON键不能静默丢弃。</zh-CN><en>Accept enumerable data fields only; hidden properties, accessors and non-JSON keys cannot be silently discarded.</en></lang>
|
|
92
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
93
|
+
if (typeof key !== "string" || !descriptor.enumerable || !("value" in descriptor) || (array && !/^(0|[1-9][0-9]*)$/.test(key))) throw new TypeError(failure);
|
|
94
|
+
Object.defineProperty(result, key, { value: cloneJson(descriptor.value, active), enumerable: true, configurable: true, writable: true });
|
|
95
|
+
}
|
|
96
|
+
if (array && (result.length !== value.length || Object.keys(result).length !== value.length)) throw new TypeError(failure);
|
|
97
|
+
return result;
|
|
98
|
+
} finally { active.delete(value); }
|
|
99
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { readFile, mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
import { cssExtractionToHiaDocument } from "@hia-doc/css-doc-adapter";
|
|
5
|
+
import { extractCssDoc } from "@hia-doc/css-doc-extractor";
|
|
6
|
+
import {
|
|
7
|
+
CSS_DOC_SOURCE_MAP_CONTRACT_VERSION,
|
|
8
|
+
createCssDocumentationSourceMap
|
|
9
|
+
} from "@hia-doc/css-doc-source-map";
|
|
10
|
+
import {
|
|
11
|
+
CSSDOC_EXTRACTION_CONTRACT,
|
|
12
|
+
CSSDOC_EXTRACTION_CONTRACT_VERSION
|
|
13
|
+
} from "@hia-doc/cssdoc-spec";
|
|
14
|
+
import { designTokensToCssExtraction } from "@hia-doc/design-token-bridge";
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
CSSDOC_CONFIG_JSON_SCHEMA,
|
|
18
|
+
CSSDOC_CONFIG_SCHEMA_ID,
|
|
19
|
+
CSSDOC_CONFIG_SCHEMA_VERSION,
|
|
20
|
+
CSSDOC_LEGACY_CONFIG_JSON_SCHEMA,
|
|
21
|
+
CSSDOC_LEGACY_CONFIG_SCHEMA_ID,
|
|
22
|
+
CSSDOC_LEGACY_CONFIG_SCHEMA_VERSION
|
|
23
|
+
} from "./schema.mjs";
|
|
24
|
+
import { validateCssDocConfigForReading } from "./config-compatibility.mjs";
|
|
25
|
+
export { getCssDocConfigSchema, migrateCssDocConfig } from "./config-compatibility.mjs";
|
|
26
|
+
/** @lang zh-CN 复用包内纯数据定义的同一冻结对象。 @lang en Reuses the same frozen objects from owner-local plain-data definitions. */
|
|
27
|
+
import {CSSDOC_RUNNER_VERSION, CSSDOC_INPUT_KINDS, CSSDOC_OUTPUT_KINDS} from './metadata.mjs';
|
|
28
|
+
export {CSSDOC_RUNNER_VERSION, CSSDOC_INPUT_KINDS, CSSDOC_OUTPUT_KINDS} from './metadata.mjs';
|
|
29
|
+
|
|
30
|
+
const RESULT_CONTRACT = "documentation-producer-result";
|
|
31
|
+
/** @lang zh-CN 沿用已确认主SDK写者身份,与CSSDoc自有契约和包版本独立。 @lang en Uses the approved main SDK writer identity independently of CSSDoc contracts and package versions. */
|
|
32
|
+
const RESULT_CONTRACT_VERSION = "1.0.0";
|
|
33
|
+
const PRODUCER_ID = "cssdoc";
|
|
34
|
+
const SAFE_ID_PATTERN = /^[a-z0-9][a-z0-9._-]*$/;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @lang zh-CN 顺序处理显式CSS或设计令牌输入并写出提取件、核心文档及可选映射,以累积诊断区分success、partial与failed。
|
|
38
|
+
* @lang en Processes explicit CSS or design-token inputs sequentially, writes extractions, core documents and optional maps, and uses accumulated diagnostics to distinguish success, partial and failed results.
|
|
39
|
+
* @param {object} request <lang><zh-CN>绝对运行根与非空安全相对输入;三种kind/选项见包README。</zh-CN><en>Absolute runtime roots and nonempty safe relative inputs; see package README for the three kinds/options.</en></lang>
|
|
40
|
+
* @param {object} [context] <lang><zh-CN>signal在每个输入前检查;reportProgress同步回调,异常传播。</zh-CN><en>signal is checked before each input; reportProgress is synchronous and its exceptions propagate.</en></lang>
|
|
41
|
+
* @returns {Promise<object>} <lang><zh-CN>已确认主SDK1.0.0结果,success/partial/failed;不返回运行绝对路径。</zh-CN><en>Approved SDK1.0.0 result with success/partial/failed; no runtime absolute paths.</en></lang>
|
|
42
|
+
* @throws {TypeError|Error} <lang><zh-CN>输入结构、目录写入或回调失败;逐文件处理失败转诊断,非原子落盘。</zh-CN><en>Invalid request, directory writes or callbacks fail; per-file failures become diagnostics and writes are not atomic.</en></lang>
|
|
43
|
+
*/
|
|
44
|
+
export async function runCssDoc(request, context = {}) {
|
|
45
|
+
// <lang><zh-CN>执行前一次校验并复制请求,只将绝对根用于I/O。</zh-CN><en>Validate and copy the request once before execution, using absolute roots for I/O only.</en></lang>
|
|
46
|
+
const normalized = normalizeRequest(request);
|
|
47
|
+
await mkdir(normalized.outputDirectory, { recursive: true });
|
|
48
|
+
|
|
49
|
+
// <lang><zh-CN>三项可变状态仅属于本次调用:成功产物、公开诊断和已完成输入数。</zh-CN><en>Three mutable accumulators belong to this call: artifacts, public diagnostics and completed input count.</en></lang>
|
|
50
|
+
const artifacts = [];
|
|
51
|
+
const diagnostics = [];
|
|
52
|
+
let completed = 0;
|
|
53
|
+
|
|
54
|
+
for (const [index, input] of normalized.inputs.entries()) {
|
|
55
|
+
// <lang><zh-CN>中止只在输入边界观察,已落盘文件保留并产生明确失败诊断。</zh-CN><en>Observe cancellation at input boundaries; existing files remain and an explicit error diagnostic is emitted.</en></lang>
|
|
56
|
+
if (context.signal?.aborted) {
|
|
57
|
+
diagnostics.push(createDiagnostic(
|
|
58
|
+
"CSSDOC_RUNNER_ABORTED",
|
|
59
|
+
"CSSDoc runner was aborted before all inputs completed.",
|
|
60
|
+
"error"
|
|
61
|
+
));
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
context.reportProgress?.({
|
|
66
|
+
phase: "extract",
|
|
67
|
+
current: index,
|
|
68
|
+
total: normalized.inputs.length,
|
|
69
|
+
message: input.path
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
// <lang><zh-CN>只有成功返回才并入产物;逐输入失败转诊断后继续其它输入。</zh-CN><en>Merge artifacts only after a successful return; per-input failures become diagnostics and remaining inputs continue.</en></lang>
|
|
74
|
+
const generated = await processInput(input, normalized, index);
|
|
75
|
+
artifacts.push(...generated.artifacts);
|
|
76
|
+
diagnostics.push(...generated.diagnostics);
|
|
77
|
+
completed += 1;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
diagnostics.push(createDiagnostic(
|
|
80
|
+
"CSSDOC_RUNNER_INPUT_FAILED",
|
|
81
|
+
`Unable to process CSSDoc input ${input.path} (${errorCode(error)}).`,
|
|
82
|
+
"error",
|
|
83
|
+
input.path
|
|
84
|
+
));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// <lang><zh-CN>有错误时按已存在产物区分partial/failed,不把未完成当success。</zh-CN><en>When errors exist, distinguish partial/failed using available artifacts, never presenting unfinished work as success.</en></lang>
|
|
89
|
+
const hasErrors = diagnostics.some((diagnostic) => diagnostic.severity === "error");
|
|
90
|
+
const result = {
|
|
91
|
+
contract: RESULT_CONTRACT,
|
|
92
|
+
contractVersion: RESULT_CONTRACT_VERSION,
|
|
93
|
+
producer: {
|
|
94
|
+
id: PRODUCER_ID,
|
|
95
|
+
version: CSSDOC_RUNNER_VERSION
|
|
96
|
+
},
|
|
97
|
+
status: hasErrors ? (artifacts.length > 0 ? "partial" : "failed") : "success",
|
|
98
|
+
artifacts,
|
|
99
|
+
diagnostics
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
if (normalized.options.writeResultManifest) {
|
|
103
|
+
await writeJson(path.join(normalized.outputDirectory, "cssdoc.producer-result.json"), result);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
context.reportProgress?.({
|
|
107
|
+
phase: "complete",
|
|
108
|
+
current: completed,
|
|
109
|
+
total: normalized.inputs.length
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* @lang zh-CN 读取并验证精确新旧版本JSON配置,按配置目录与工作根解析运行目录,返回规范化请求。
|
|
117
|
+
* @lang en Reads and validates exact current or legacy JSON configs, resolves runtime directories against the config directory and workspace root, and returns a normalized request.
|
|
118
|
+
* @param {string} configPath <lang><zh-CN>配置定位器;相对cwd。</zh-CN><en>Config locator relative to cwd.</en></lang>
|
|
119
|
+
* @param {Object} [options] <lang><zh-CN>配置加载选项。</zh-CN><en>Config loading options.</en></lang>
|
|
120
|
+
* @param {string} [options.cwd] <lang><zh-CN>默认process.cwd,仅内存绝对路径。</zh-CN><en>Defaults to process.cwd; absolute paths remain in memory.</en></lang>
|
|
121
|
+
* @returns {Promise<object>} <lang><zh-CN>精确旧0.1.0-draft/新1.0.0配置加载;历史目录/后缀默认保持,不写文件。</zh-CN><en>Exact legacy0.1.0-draft/current1.0.0 config load preserving historical directory/suffix defaults without writes.</en></lang>
|
|
122
|
+
* @throws {TypeError} <lang><zh-CN>读/解析/字段失败,固定公开错误;旧schema的required原样保留,纯迁移另有显式入口。</zh-CN><en>Read/parse/field failures use fixed public errors; legacy required remains unchanged and pure migration has an explicit entry.</en></lang>
|
|
123
|
+
*/
|
|
124
|
+
export async function loadCssDocConfig(configPath, options = {}) {
|
|
125
|
+
// <lang><zh-CN>绝对配置位置只用于读取,不进入结果或公开异常。</zh-CN><en>The absolute config location is used for reads only, never public results or errors.</en></lang>
|
|
126
|
+
const absoluteConfigPath = path.resolve(options.cwd ?? process.cwd(), configPath);
|
|
127
|
+
// <lang><zh-CN>文件和JSON是外部边界,公开异常不携带本机路径或配置正文。</zh-CN><en>File and JSON input are external boundaries; public errors carry neither local paths nor config bodies.</en></lang>
|
|
128
|
+
let config;
|
|
129
|
+
try {
|
|
130
|
+
config = JSON.parse(await readFile(absoluteConfigPath, "utf8"));
|
|
131
|
+
} catch {
|
|
132
|
+
throw new TypeError("Unable to read or parse CSSDoc config JSON.");
|
|
133
|
+
}
|
|
134
|
+
validateCssDocConfigForReading(config);
|
|
135
|
+
|
|
136
|
+
// <lang><zh-CN>历史配置位置关系:工作根相对配置,输出相对工作根;绝对解析仅保存在内存。</zh-CN><en>Historical bases: workspace relative to config, output relative to workspace; absolute resolutions stay in memory.</en></lang>
|
|
137
|
+
const configDirectory = path.dirname(absoluteConfigPath);
|
|
138
|
+
const workspaceDirectory = normalizeConfigDirectory(config.workspaceRoot ?? ".", "workspaceRoot");
|
|
139
|
+
const outputDirectory = normalizeConfigDirectory(config.outputDirectory ?? "dist/cssdoc", "outputDirectory");
|
|
140
|
+
const workspaceRoot = path.resolve(configDirectory, workspaceDirectory);
|
|
141
|
+
|
|
142
|
+
return normalizeRequest({
|
|
143
|
+
workspaceRoot,
|
|
144
|
+
outputDirectory: path.resolve(workspaceRoot, outputDirectory),
|
|
145
|
+
inputs: config.inputs,
|
|
146
|
+
options: config.options,
|
|
147
|
+
profileIds: config.profileIds
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* @lang zh-CN 仅按文件名后缀推断设计令牌、PostCSS或普通CSS输入种类,默认css。
|
|
153
|
+
* @lang en Infers design-token, PostCSS or ordinary CSS input kinds from filename suffixes alone, defaulting to css.
|
|
154
|
+
* @param {string} inputPath <lang><zh-CN>输入名称。</zh-CN><en>Input name.</en></lang> @returns {string} <lang><zh-CN>.json为design-token,.pcss/.postcss.css为postcss-css,否则css;无I/O。</zh-CN><en>.json gives design-token, .pcss/.postcss.css gives postcss-css, otherwise css; no I/O.</en></lang>
|
|
155
|
+
*/
|
|
156
|
+
export function inferCssDocInputKind(inputPath) {
|
|
157
|
+
// <lang><zh-CN>名称规范化只为后缀匹配,不执行文件读取或发现。</zh-CN><en>Name normalization serves suffix matching only, without reads or discovery.</en></lang>
|
|
158
|
+
const normalized = String(inputPath).replaceAll("\\", "/").toLowerCase();
|
|
159
|
+
if (normalized.endsWith(".json")) {
|
|
160
|
+
return "design-token";
|
|
161
|
+
}
|
|
162
|
+
if (normalized.endsWith(".pcss") || normalized.endsWith(".postcss.css")) {
|
|
163
|
+
return "postcss-css";
|
|
164
|
+
}
|
|
165
|
+
return "css";
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async function processInput(input, request, index) {
|
|
169
|
+
const sourceFile = path.resolve(request.workspaceRoot, input.path);
|
|
170
|
+
const source = await readFile(sourceFile, "utf8");
|
|
171
|
+
const extraction = input.kind === "design-token"
|
|
172
|
+
? designTokensToCssExtraction(JSON.parse(source), { path: input.path })
|
|
173
|
+
: extractCssDoc(source, {
|
|
174
|
+
path: input.path,
|
|
175
|
+
sourcesContentPolicy: request.options.sourcesContentPolicy
|
|
176
|
+
});
|
|
177
|
+
const document = cssExtractionToHiaDocument(extraction, {
|
|
178
|
+
id: `cssdoc:${input.path}`,
|
|
179
|
+
title: path.posix.basename(input.path)
|
|
180
|
+
});
|
|
181
|
+
const basePath = outputBasePath(input, index);
|
|
182
|
+
const extractionPath = `${basePath}.cssdoc.json`;
|
|
183
|
+
const hiaDocumentPath = `${basePath}.hia.json`;
|
|
184
|
+
const docSourceMapPath = `${basePath}.docmap.json`;
|
|
185
|
+
|
|
186
|
+
await writeJson(path.join(request.outputDirectory, extractionPath), extraction);
|
|
187
|
+
await writeJson(path.join(request.outputDirectory, hiaDocumentPath), document);
|
|
188
|
+
|
|
189
|
+
const artifactIdBase = `input-${index + 1}`;
|
|
190
|
+
const artifacts = [
|
|
191
|
+
{
|
|
192
|
+
id: `${artifactIdBase}-extraction`,
|
|
193
|
+
kind: "cssdoc-extraction",
|
|
194
|
+
path: extractionPath,
|
|
195
|
+
contract: CSSDOC_EXTRACTION_CONTRACT,
|
|
196
|
+
contractVersion: CSSDOC_EXTRACTION_CONTRACT_VERSION,
|
|
197
|
+
language: "json",
|
|
198
|
+
mediaType: "application/json",
|
|
199
|
+
profileIds: request.profileIds
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
id: `${artifactIdBase}-hia-document`,
|
|
203
|
+
kind: "hia-document",
|
|
204
|
+
path: hiaDocumentPath,
|
|
205
|
+
language: "json",
|
|
206
|
+
mediaType: "application/json",
|
|
207
|
+
profileIds: request.profileIds
|
|
208
|
+
}
|
|
209
|
+
];
|
|
210
|
+
|
|
211
|
+
if (request.options.emitDocSourceMap) {
|
|
212
|
+
const docSourceMap = createCssDocumentationSourceMap({
|
|
213
|
+
extraction,
|
|
214
|
+
extractionPath,
|
|
215
|
+
hiaDocumentPath,
|
|
216
|
+
sourcesContentPolicy: request.options.sourcesContentPolicy
|
|
217
|
+
});
|
|
218
|
+
await writeJson(path.join(request.outputDirectory, docSourceMapPath), docSourceMap);
|
|
219
|
+
artifacts.push({
|
|
220
|
+
id: `${artifactIdBase}-doc-source-map`,
|
|
221
|
+
kind: "doc-source-map",
|
|
222
|
+
path: docSourceMapPath,
|
|
223
|
+
contract: "doc-source-map",
|
|
224
|
+
contractVersion: CSS_DOC_SOURCE_MAP_CONTRACT_VERSION,
|
|
225
|
+
language: "json",
|
|
226
|
+
mediaType: "application/json",
|
|
227
|
+
profileIds: request.profileIds
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return {
|
|
232
|
+
artifacts,
|
|
233
|
+
diagnostics: (extraction.diagnostics ?? []).map((diagnostic) => normalizeDiagnostic(diagnostic, input.path))
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @param {unknown} value <lang><zh-CN>API或loader输入,是执行前真实信任边界。</zh-CN><en>API/loader input at the real execution trust boundary.</en></lang> @returns {object} <lang><zh-CN>复制输入/profile数组并规范化,未改原值;只缺省字段启用历史默认。</zh-CN><en>Copies input/profile arrays and normalizes without mutation; historical defaults apply only to absent fields.</en></lang> @throws {TypeError} <lang><zh-CN>已声明类型/唯一性/路径错误,不打印原值。</zh-CN><en>Declared type/uniqueness/path failure without raw values.</en></lang> */
|
|
238
|
+
function normalizeRequest(value) {
|
|
239
|
+
assertRecord(value, "CSSDoc runner request must be an object.");
|
|
240
|
+
assertAbsoluteDirectory(value.workspaceRoot, "workspaceRoot");
|
|
241
|
+
assertAbsoluteDirectory(value.outputDirectory, "outputDirectory");
|
|
242
|
+
if (!Array.isArray(value.inputs) || value.inputs.length === 0) {
|
|
243
|
+
throw new TypeError("inputs must be a non-empty array.");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// <lang><zh-CN>每条输入建新记录,语言/路径和kind在此一次校验。</zh-CN><en>Create a fresh record per input, checking language/path/kind once here.</en></lang>
|
|
247
|
+
const inputs = value.inputs.map((input, index) => {
|
|
248
|
+
assertRecord(input, `inputs[${index}] must be an object.`);
|
|
249
|
+
assertKnownKeys(input, ["kind", "path", "language"], `inputs[${index}]`);
|
|
250
|
+
// <lang><zh-CN>已验证的相对定位器决定现有后缀推断,禁止回显错误kind。</zh-CN><en>The checked relative locator drives existing suffix inference without echoing invalid kinds.</en></lang>
|
|
251
|
+
const inputPath = normalizeSafeRelativePath(input.path, `inputs[${index}].path`);
|
|
252
|
+
const kind = input.kind === undefined ? inferCssDocInputKind(inputPath) : input.kind;
|
|
253
|
+
if (!CSSDOC_INPUT_KINDS.includes(kind)) {
|
|
254
|
+
throw new TypeError("Unsupported CSSDoc input kind.");
|
|
255
|
+
}
|
|
256
|
+
// <lang><zh-CN>非空语言是既有声明,不能静默丢弃错误类型。</zh-CN><en>A nonempty language is an existing declaration; mistyped values cannot be silently dropped.</en></lang>
|
|
257
|
+
if (input.language !== undefined && (typeof input.language !== "string" || input.language.length === 0)) {
|
|
258
|
+
throw new TypeError("Input language must be a non-empty string.");
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
kind,
|
|
262
|
+
path: inputPath,
|
|
263
|
+
...(typeof input.language === "string" ? { language: input.language } : {})
|
|
264
|
+
};
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// <lang><zh-CN>显式null不能冒充缺省选项。</zh-CN><en>Explicit null cannot stand in for absent options.</en></lang>
|
|
268
|
+
const runnerOptions = value.options === undefined ? {} : value.options;
|
|
269
|
+
assertRecord(runnerOptions, "options must be an object.");
|
|
270
|
+
assertKnownKeys(runnerOptions, ["emitDocSourceMap", "sourcesContentPolicy", "writeResultManifest"], "options");
|
|
271
|
+
// <lang><zh-CN>仅缺省才启用默认值;显式null与其它非布尔值违反既有schema。</zh-CN><en>Defaults apply only when absent; explicit null and other nonbooleans violate the existing schema.</en></lang>
|
|
272
|
+
for (const key of ["emitDocSourceMap", "writeResultManifest"]) {
|
|
273
|
+
if (runnerOptions[key] !== undefined && typeof runnerOptions[key] !== "boolean") {
|
|
274
|
+
throw new TypeError("Runner flags must be booleans.");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
const sourcesContentPolicy = runnerOptions.sourcesContentPolicy === undefined ? "none" : runnerOptions.sourcesContentPolicy;
|
|
278
|
+
if (!["none", "reference", "embed"].includes(sourcesContentPolicy)) {
|
|
279
|
+
throw new TypeError("Unsupported sourcesContentPolicy.");
|
|
280
|
+
}
|
|
281
|
+
// <lang><zh-CN>非空唯一profile列表随后复制,避免共享调用方可变数组。</zh-CN><en>The nonempty unique profile list is copied to avoid sharing the caller mutable array.</en></lang>
|
|
282
|
+
const profileIds = value.profileIds === undefined ? ["cssdoc"] : value.profileIds;
|
|
283
|
+
if (!Array.isArray(profileIds) || profileIds.length === 0 || profileIds.some((id) => typeof id !== "string" || !SAFE_ID_PATTERN.test(id)) || new Set(profileIds).size !== profileIds.length) {
|
|
284
|
+
throw new TypeError("profileIds must be a non-empty array of lower-case identifiers.");
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
workspaceRoot: path.resolve(value.workspaceRoot),
|
|
289
|
+
outputDirectory: path.resolve(value.outputDirectory),
|
|
290
|
+
inputs,
|
|
291
|
+
profileIds: [...profileIds],
|
|
292
|
+
options: {
|
|
293
|
+
emitDocSourceMap: runnerOptions.emitDocSourceMap !== false,
|
|
294
|
+
sourcesContentPolicy,
|
|
295
|
+
writeResultManifest: runnerOptions.writeResultManifest !== false
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function outputBasePath(input, index) {
|
|
301
|
+
const parsed = path.posix.parse(input.path);
|
|
302
|
+
const directory = parsed.dir ? `${parsed.dir}/` : "";
|
|
303
|
+
return normalizeSafeRelativePath(
|
|
304
|
+
`artifacts/${directory}${parsed.name}.${slug(input.kind)}-${index + 1}`,
|
|
305
|
+
"artifact base path"
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function normalizeDiagnostic(diagnostic, fallbackPath) {
|
|
310
|
+
const severity = diagnostic?.severity === "error" || diagnostic?.severity === "warning" || diagnostic?.severity === "info"
|
|
311
|
+
? diagnostic.severity
|
|
312
|
+
: "info";
|
|
313
|
+
const diagnosticPath = typeof diagnostic?.path === "string" && isSafeRelativePath(diagnostic.path)
|
|
314
|
+
? diagnostic.path.replaceAll("\\", "/")
|
|
315
|
+
: fallbackPath;
|
|
316
|
+
return {
|
|
317
|
+
code: typeof diagnostic?.code === "string" ? diagnostic.code : "CSSDOC_RUNNER_DIAGNOSTIC",
|
|
318
|
+
message: typeof diagnostic?.message === "string" ? diagnostic.message : "CSSDoc runner diagnostic.",
|
|
319
|
+
severity,
|
|
320
|
+
path: diagnosticPath,
|
|
321
|
+
...(isJsonObject(diagnostic?.data) ? { data: diagnostic.data } : {})
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function createDiagnostic(code, message, severity, diagnosticPath) {
|
|
326
|
+
return {
|
|
327
|
+
code,
|
|
328
|
+
message,
|
|
329
|
+
severity,
|
|
330
|
+
...(diagnosticPath ? { path: diagnosticPath } : {})
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function writeJson(filePath, value) {
|
|
335
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
336
|
+
await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function normalizeSafeRelativePath(value, label) {
|
|
340
|
+
if (typeof value !== "string" || !isSafeRelativePath(value)) {
|
|
341
|
+
throw new TypeError(`${label} must be a safe relative path.`);
|
|
342
|
+
}
|
|
343
|
+
return value.replaceAll("\\", "/");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function isSafeRelativePath(value) {
|
|
347
|
+
const normalized = String(value).replaceAll("\\", "/");
|
|
348
|
+
return Boolean(normalized)
|
|
349
|
+
&& !path.posix.isAbsolute(normalized)
|
|
350
|
+
&& !path.win32.isAbsolute(value)
|
|
351
|
+
&& !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(normalized)
|
|
352
|
+
&& !normalized.split("/").includes("..");
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function normalizeConfigDirectory(value, label) {
|
|
356
|
+
if (typeof value !== "string" || path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)) {
|
|
357
|
+
throw new TypeError(`${label} must be relative to the config/project directory.`);
|
|
358
|
+
}
|
|
359
|
+
const normalized = value.replaceAll("\\", "/");
|
|
360
|
+
if (!normalized || normalized.split("/").includes("..")) {
|
|
361
|
+
throw new TypeError(`${label} must not escape its base directory.`);
|
|
362
|
+
}
|
|
363
|
+
return normalized;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function assertAbsoluteDirectory(value, label) {
|
|
367
|
+
if (typeof value !== "string" || (!path.posix.isAbsolute(value) && !path.win32.isAbsolute(value))) {
|
|
368
|
+
throw new TypeError(`${label} must be an absolute runtime path.`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** @param {object} value <lang><zh-CN>已确认对象。</zh-CN><en>Checked object.</en></lang> @param {string[]} allowed <lang><zh-CN>允许字段。</zh-CN><en>Allowed keys.</en></lang> @param {string} label <lang><zh-CN>内部固定位置标签。</zh-CN><en>Internal location label.</en></lang> @returns {void} <lang><zh-CN>检查自有字段,无I/O。</zh-CN><en>Checks own keys without I/O.</en></lang> @throws {TypeError} <lang><zh-CN>未知键固定拒绝,键名可能私有所以不回显。</zh-CN><en>Fixed refusal of unknown potentially private keys without echo.</en></lang> */
|
|
373
|
+
function assertKnownKeys(value, allowed, label) {
|
|
374
|
+
for (const key of Object.keys(value)) {
|
|
375
|
+
if (!allowed.includes(key)) {
|
|
376
|
+
throw new TypeError(`${label} contains unsupported fields.`);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function assertRecord(value, message) {
|
|
382
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
383
|
+
throw new TypeError(message);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function isJsonObject(value) {
|
|
388
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
try {
|
|
392
|
+
JSON.stringify(value);
|
|
393
|
+
return true;
|
|
394
|
+
} catch {
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function errorCode(error) {
|
|
400
|
+
return typeof error?.code === "string" ? error.code : error?.name ?? "Error";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function slug(value) {
|
|
404
|
+
return String(value).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-|-$/g, "") || "input";
|
|
405
|
+
}
|
package/src/metadata.mjs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** @file @lang zh-CN 运行器纯元数据,含版本及冻结输入/输出种类。 @lang en Pure runner metadata containing its version and frozen input/output kinds. */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @lang zh-CN 显式输入kind只读列表,不发现文件。
|
|
5
|
+
* @lang en Read-only explicit input-kind list without file discovery.
|
|
6
|
+
*/
|
|
7
|
+
export const CSSDOC_INPUT_KINDS = Object.freeze([
|
|
8
|
+
"css",
|
|
9
|
+
"postcss-css",
|
|
10
|
+
"design-token"
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @lang zh-CN 可能输出的工件kind,实际map受选项控制。
|
|
15
|
+
* @lang en Possible output artifact kinds; actual map output is option-controlled.
|
|
16
|
+
*/
|
|
17
|
+
export const CSSDOC_OUTPUT_KINDS = Object.freeze([
|
|
18
|
+
"cssdoc-extraction",
|
|
19
|
+
"hia-document",
|
|
20
|
+
"doc-source-map"
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @lang zh-CN 当前包/producer版本,与工件契约身份分层。
|
|
25
|
+
* @lang en Current package/producer version, separate from artifact contract identities.
|
|
26
|
+
*/
|
|
27
|
+
export const CSSDOC_RUNNER_VERSION = "1.0.0";
|