@hamsterbase/evidra 0.11.0 → 0.12.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.
@@ -0,0 +1,191 @@
1
+ import { z } from "zod";
2
+ // packages/conformance/runner/config.ts
3
+ function defineConfig(config) {
4
+ return config;
5
+ }
6
+ // packages/conformance/runner/rule.ts
7
+ /** 定义一条自描述规约:统一声明元信息、Zod 配置校验与检查实现。 */
8
+ function defineRule(definition) {
9
+ const meta = {
10
+ id: definition.id,
11
+ displayName: definition.displayName,
12
+ exportName: definition.exportName,
13
+ ...definition.importFrom ? { importFrom: definition.importFrom } : {},
14
+ summary: definition.summary,
15
+ optionsSchema: definition.optionsSchema,
16
+ examples: definition.examples,
17
+ ...definition.notes ? { notes: definition.notes } : {}
18
+ };
19
+ const factory = ((rawOptions) => {
20
+ const parsed = definition.optionsSchema.safeParse(rawOptions ?? {});
21
+ if (!parsed.success) throw new Error(`${definition.id} 配置无效:\n${z.prettifyError(parsed.error)}`);
22
+ const options = parsed.data;
23
+ const task = (common) => definition.run(common, options);
24
+ return Object.assign(task, {
25
+ id: definition.id,
26
+ displayName: definition.resolveDisplayName?.(options) ?? definition.displayName,
27
+ doc: meta
28
+ });
29
+ });
30
+ return Object.assign(factory, { meta });
31
+ }
32
+ // packages/conformance/runner/doc.ts
33
+ const DEFAULT_IMPORT_FROM = "@hamsterbase/evidra/conformance-rules";
34
+ const IDENTIFIER_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
35
+ /** 将规约的 Zod Schema 转换为带 tsType 元信息的 JSON Schema。 */
36
+ function ruleOptionsToJsonSchema(schema) {
37
+ return z.toJSONSchema(schema, {
38
+ io: "input",
39
+ unrepresentable: "any",
40
+ override(context) {
41
+ const meta = context.zodSchema.meta?.();
42
+ if (meta && typeof meta.tsType === "string") context.jsonSchema.tsType = meta.tsType;
43
+ }
44
+ });
45
+ }
46
+ /** 根据规约定义与 Zod Schema 自动推导工作台展示的 Markdown 文档。 */
47
+ function renderRuleDoc(doc) {
48
+ const schema = ruleOptionsToJsonSchema(doc.optionsSchema);
49
+ const sections = [
50
+ `# ${doc.exportName}`,
51
+ doc.summary.trim(),
52
+ `规约 ID:${inlineCode(doc.id)}`,
53
+ renderUsageSection(doc, schema),
54
+ renderOptionsSection(schema)
55
+ ];
56
+ const notes = doc.notes?.trim();
57
+ if (notes) sections.push(`## 说明\n\n${notes}`);
58
+ return `${sections.join("\n\n")}\n`;
59
+ }
60
+ function renderUsageSection(doc, schema) {
61
+ const importFrom = doc.importFrom ?? DEFAULT_IMPORT_FROM;
62
+ const hasRequired = (schema.required?.length ?? 0) > 0;
63
+ return `## 用法\n\n${doc.examples.map((example) => {
64
+ const call = formatExampleCall(doc.exportName, example.options, hasRequired);
65
+ const rulesLine = call.includes("\n") ? ` rules: [\n${indentLines(call, 4)},\n ],` : ` rules: [${call}],`;
66
+ const snippet = [
67
+ `import { defineConfig } from '@hamsterbase/evidra/conformance';`,
68
+ `import { ${doc.exportName} } from '${importFrom}';`,
69
+ "",
70
+ "export default defineConfig({",
71
+ rulesLine,
72
+ "});"
73
+ ].join("\n");
74
+ return `${example.title?.trim() ? `### ${example.title.trim()}\n\n` : ""}${codeFence("ts", snippet)}`;
75
+ }).join("\n\n")}`;
76
+ }
77
+ function renderOptionsSection(schema) {
78
+ const lines = renderProperties(schema, 0);
79
+ if (lines.length === 0) return "## 参数\n\n此规约无需配置参数。";
80
+ return `## 参数\n\n${lines.join("\n")}`;
81
+ }
82
+ function renderProperties(schema, depth) {
83
+ const properties = schema.properties ?? {};
84
+ const required = new Set(schema.required ?? []);
85
+ const indent = " ".repeat(depth);
86
+ const lines = [];
87
+ for (const [key, prop] of Object.entries(properties)) {
88
+ const tags = [inlineCode(formatSchemaType(prop))];
89
+ const constraints = formatConstraints(prop);
90
+ if (constraints) tags.push(constraints);
91
+ tags.push(required.has(key) ? "必填" : "可选");
92
+ if (prop.default !== void 0) tags.push(`默认 ${inlineCode(formatTsValue(prop.default))}`);
93
+ const description = prop.description?.trim() ?? "";
94
+ lines.push(`${indent}- ${inlineCode(key)}(${tags.join(",")})${description ? `:${description}` : ""}`);
95
+ if (prop.type === "object" && prop.properties) lines.push(...renderProperties(prop, depth + 1));
96
+ else if (prop.type === "array" && prop.items?.type === "object" && prop.items.properties) lines.push(...renderProperties(prop.items, depth + 1));
97
+ }
98
+ return lines;
99
+ }
100
+ function formatSchemaType(node) {
101
+ if (node.tsType) return node.tsType;
102
+ if (node.const !== void 0) return formatTsValue(node.const);
103
+ if (node.enum?.length) return node.enum.map((item) => formatTsValue(item)).join(" | ");
104
+ if (node.anyOf?.length) return node.anyOf.map(formatSchemaType).join(" | ");
105
+ if (node.oneOf?.length) return node.oneOf.map(formatSchemaType).join(" | ");
106
+ if (Array.isArray(node.type)) return node.type.join(" | ");
107
+ if (node.type === "array") {
108
+ const itemType = node.items ? formatSchemaType(node.items) : "unknown";
109
+ const wrapped = itemType.includes(" | ") ? `(${itemType})[]` : `${itemType}[]`;
110
+ return node.readOnly ? `readonly ${wrapped}` : wrapped;
111
+ }
112
+ if (node.type === "object") {
113
+ if (node.properties) return "object";
114
+ if (node.additionalProperties && typeof node.additionalProperties === "object") {
115
+ const recordType = `Record<string, ${formatSchemaType(node.additionalProperties)}>`;
116
+ return node.readOnly ? `Readonly<${recordType}>` : recordType;
117
+ }
118
+ return "Record<string, unknown>";
119
+ }
120
+ if (typeof node.type === "string") return node.type;
121
+ return "unknown";
122
+ }
123
+ function formatConstraints(node) {
124
+ const parts = [];
125
+ if (node.type === "string") {
126
+ if (node.minLength === 1) parts.push("非空");
127
+ else if (typeof node.minLength === "number" && node.minLength > 1) parts.push(`长度 >= ${node.minLength}`);
128
+ if (typeof node.maxLength === "number") parts.push(`长度 <= ${node.maxLength}`);
129
+ }
130
+ if (node.type === "integer" || node.type === "number") {
131
+ if (typeof node.minimum === "number" && node.minimum !== Number.MIN_SAFE_INTEGER) parts.push(`>= ${node.minimum}`);
132
+ if (typeof node.maximum === "number" && node.maximum !== Number.MAX_SAFE_INTEGER) parts.push(`<= ${node.maximum}`);
133
+ if (typeof node.exclusiveMinimum === "number") parts.push(`> ${node.exclusiveMinimum}`);
134
+ if (typeof node.exclusiveMaximum === "number") parts.push(`< ${node.exclusiveMaximum}`);
135
+ }
136
+ return parts.join(",");
137
+ }
138
+ function formatExampleCall(exportName, options, hasRequired) {
139
+ if (!hasRequired && options !== null && typeof options === "object" && !Array.isArray(options) && Object.keys(options).length === 0) return `${exportName}()`;
140
+ return `${exportName}(${formatTsValue(options, 0)})`;
141
+ }
142
+ function formatTsValue(value, indent = 0) {
143
+ if (value instanceof RegExp) return value.toString();
144
+ if (typeof value === "string") return formatString(value);
145
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
146
+ if (value === null) return "null";
147
+ if (value === void 0) return "undefined";
148
+ if (Array.isArray(value)) {
149
+ if (value.length === 0) return "[]";
150
+ const inlineItems = value.map((item) => formatTsValue(item, indent + 2));
151
+ const singleLine = `[${inlineItems.join(", ")}]`;
152
+ if (singleLine.length <= 60 && !singleLine.includes("\n")) return singleLine;
153
+ const pad = " ".repeat(indent + 2);
154
+ const closePad = " ".repeat(indent);
155
+ return `[\n${inlineItems.map((item) => `${pad}${item},`).join("\n")}\n${closePad}]`;
156
+ }
157
+ if (typeof value === "object") {
158
+ const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== void 0);
159
+ if (entries.length === 0) return "{}";
160
+ const inlinePairs = entries.map(([key, entryValue]) => `${formatObjectKey(key)}: ${formatTsValue(entryValue, indent + 2)}`);
161
+ const singleLine = `{ ${inlinePairs.join(", ")} }`;
162
+ if (singleLine.length <= 60 && !singleLine.includes("\n")) return singleLine;
163
+ const pad = " ".repeat(indent + 2);
164
+ const closePad = " ".repeat(indent);
165
+ return `{\n${inlinePairs.map((pair) => `${pad}${pair},`).join("\n")}\n${closePad}}`;
166
+ }
167
+ return String(value);
168
+ }
169
+ function formatObjectKey(key) {
170
+ return IDENTIFIER_PATTERN.test(key) ? key : formatString(key);
171
+ }
172
+ function formatString(value) {
173
+ return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n").replaceAll("\r", "\\r").replaceAll(" ", "\\t")}'`;
174
+ }
175
+ function indentLines(text, spaces) {
176
+ const pad = " ".repeat(spaces);
177
+ return text.split("\n").map((line) => `${pad}${line}`).join("\n");
178
+ }
179
+ function inlineCode(value) {
180
+ let maxTicks = 0;
181
+ for (const match of value.matchAll(/`+/g)) if (match[0].length > maxTicks) maxTicks = match[0].length;
182
+ const ticks = "`".repeat(maxTicks + 1);
183
+ return value.startsWith("`") || value.endsWith("`") || value.startsWith(" ") && value.endsWith(" ") && value.trim().length > 0 ? `${ticks} ${value} ${ticks}` : `${ticks}${value}${ticks}`;
184
+ }
185
+ function codeFence(language, code) {
186
+ let maxTicks = 0;
187
+ for (const match of code.matchAll(/`+/g)) if (match[0].length > maxTicks) maxTicks = match[0].length;
188
+ const fence = "`".repeat(Math.max(3, maxTicks + 1));
189
+ return `${fence}${language}\n${code}\n${fence}`;
190
+ }
191
+ export { defineConfig as i, ruleOptionsToJsonSchema as n, defineRule as r, renderRuleDoc as t };