@boringparts/lioni 0.0.0-stage → 0.4.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.
@@ -0,0 +1,331 @@
1
+ import { z } from "zod";
2
+ import { isMap, isPair, isScalar, isSeq, parseDocument } from "yaml";
3
+ // ../../packages/terminology/dist/data.js
4
+ const jsonScalarSchema = z.compile(z.union([
5
+ z.string(),
6
+ z.number().refine((value) => !Object.is(value, -0), "JSON 数值不能为负零。"),
7
+ z.boolean(),
8
+ z.null()
9
+ ]));
10
+ const jsonValueSchema = z.lazy(() => z.union([
11
+ jsonScalarSchema,
12
+ z.array(jsonValueSchema),
13
+ z.custom((value) => value !== null && typeof value === "object" && !Array.isArray(value) && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)).transform(Object.entries).pipe(z.array(z.tuple([z.string(), jsonValueSchema]))).transform((entries) => Object.fromEntries(entries))
14
+ ]));
15
+ const nonemptyTextSchema = z.string().refine((value) => value.trim() !== "", "文本不得为空或仅有空白。");
16
+ const termUsageSchema = z.enum([
17
+ "preferred",
18
+ "allowed",
19
+ "forbidden"
20
+ ]);
21
+ const termTypeSchema = z.enum([
22
+ "fullForm",
23
+ "abbreviation",
24
+ "acronym",
25
+ "shortForm",
26
+ "variant",
27
+ "phrase"
28
+ ]);
29
+ const metadataShape = {
30
+ note: z.string().exactOptional(),
31
+ metadata: jsonValueSchema.exactOptional(),
32
+ sourceRefs: z.array(jsonValueSchema).exactOptional()
33
+ };
34
+ const expressionSchema = z.object({
35
+ ...metadataShape,
36
+ id: nonemptyTextSchema,
37
+ text: nonemptyTextSchema,
38
+ usage: termUsageSchema,
39
+ termType: termTypeSchema.exactOptional(),
40
+ variants: z.never().exactOptional()
41
+ });
42
+ const languageSchema = z.object({
43
+ ...metadataShape,
44
+ language: nonemptyTextSchema,
45
+ definition: z.object({
46
+ ...metadataShape,
47
+ text: z.string()
48
+ }).exactOptional(),
49
+ expressions: z.array(expressionSchema).min(1)
50
+ });
51
+ const conceptSchema = z.object({
52
+ ...metadataShape,
53
+ id: nonemptyTextSchema,
54
+ languages: z.array(languageSchema).min(1),
55
+ subjectFields: z.array(z.string()).exactOptional()
56
+ });
57
+ const termbaseContract = z.compile(z.object({
58
+ ...metadataShape,
59
+ concepts: z.array(conceptSchema)
60
+ }).superRefine((data, context) => {
61
+ const conceptIds = /* @__PURE__ */ new Set();
62
+ for (const [ci, concept] of data.concepts.entries()) {
63
+ if (conceptIds.has(concept.id)) context.addIssue({
64
+ code: "custom",
65
+ message: "概念身份重复。",
66
+ path: [
67
+ "concepts",
68
+ ci,
69
+ "id"
70
+ ]
71
+ });
72
+ conceptIds.add(concept.id);
73
+ const languages = /* @__PURE__ */ new Set();
74
+ const expressions = /* @__PURE__ */ new Set();
75
+ for (const [li, language] of concept.languages.entries()) {
76
+ const path = [
77
+ "concepts",
78
+ ci,
79
+ "languages",
80
+ li
81
+ ];
82
+ if (languages.has(language.language)) context.addIssue({
83
+ code: "custom",
84
+ message: "概念内语言段重复。",
85
+ path: [...path, "language"]
86
+ });
87
+ languages.add(language.language);
88
+ for (const [ei, expression] of language.expressions.entries()) {
89
+ if (expressions.has(expression.id)) context.addIssue({
90
+ code: "custom",
91
+ message: "概念内表达身份重复。",
92
+ path: [
93
+ ...path,
94
+ "expressions",
95
+ ei,
96
+ "id"
97
+ ]
98
+ });
99
+ expressions.add(expression.id);
100
+ }
101
+ }
102
+ }
103
+ }));
104
+ var TermContractError = class extends TypeError {
105
+ stage;
106
+ issues;
107
+ constructor(stage, issues) {
108
+ super(issues.map((issue) => issue.message).join(";"));
109
+ this.name = "TermContractError";
110
+ this.stage = stage;
111
+ this.issues = Object.freeze([...issues]);
112
+ }
113
+ };
114
+ function contractIssue(code, message, path = []) {
115
+ return {
116
+ code,
117
+ message,
118
+ path
119
+ };
120
+ }
121
+ /** 输入异常只公开字段位置与原因,调用方无需识别具体验证库。 */
122
+ function contractIssues(error) {
123
+ return error.issues.map((issue) => ({
124
+ code: "invalid-input",
125
+ message: issue.message,
126
+ path: issue.path.map((part) => typeof part === "symbol" ? String(part) : part)
127
+ }));
128
+ }
129
+ /** 先复制再验证,保留特殊键;Zod 的对象输出不作为领域快照。 */
130
+ function copyJson(value, stage) {
131
+ const active = /* @__PURE__ */ new Set();
132
+ function copy(current, path) {
133
+ if (current === null || typeof current !== "object") {
134
+ if (jsonScalarSchema.validate(current)) return current;
135
+ const error = jsonScalarSchema.safeParse(current).error;
136
+ throw new TermContractError(stage, contractIssues(error).map((issue) => ({
137
+ ...issue,
138
+ path: [...path, ...issue.path]
139
+ })));
140
+ }
141
+ const prototype = Object.getPrototypeOf(current);
142
+ if (active.has(current) || prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null) throw new TermContractError(stage, [contractIssue("invalid-json", "资料必须可无损保存为 JSON。", path)]);
143
+ active.add(current);
144
+ try {
145
+ const result = Array.isArray(current) ? Array.from(current, (item, index) => copy(item, [...path, index])) : Object.fromEntries(Object.entries(current).map(([key, item]) => [key, copy(item, [...path, key])]));
146
+ return Object.freeze(result);
147
+ } finally {
148
+ active.delete(current);
149
+ }
150
+ }
151
+ return copy(value, []);
152
+ }
153
+ /** 创建独立、不可改写的资料快照;使用地位冲突在有效选择之后检查。 */
154
+ function createTermbase(value) {
155
+ const snapshot = copyJson(value, "create");
156
+ if (!termbaseContract.validate(snapshot)) throw new TermContractError("create", contractIssues(termbaseContract.safeParse(snapshot).error));
157
+ const data = snapshot;
158
+ const expressions = Object.freeze(data.concepts.flatMap((concept) => concept.languages.flatMap((languageData) => languageData.expressions.map((expression) => Object.freeze({
159
+ conceptId: concept.id,
160
+ expressionId: expression.id,
161
+ language: languageData.language,
162
+ concept,
163
+ languageData,
164
+ expression
165
+ })))));
166
+ const concepts = new Map(data.concepts.map((concept) => [concept.id, concept]));
167
+ const byConcept = /* @__PURE__ */ new Map();
168
+ for (const entry of expressions) {
169
+ let entries = byConcept.get(entry.conceptId);
170
+ if (!entries) {
171
+ entries = /* @__PURE__ */ new Map();
172
+ byConcept.set(entry.conceptId, entries);
173
+ }
174
+ entries.set(entry.expressionId, entry);
175
+ }
176
+ return Object.freeze({
177
+ data,
178
+ concepts: data.concepts,
179
+ expressions,
180
+ getConcept: (id) => concepts.get(id),
181
+ getExpression: (conceptId, expressionId) => byConcept.get(conceptId)?.get(expressionId)
182
+ });
183
+ }
184
+ function selectTerms(termbase, selection = {}) {
185
+ const concepts = termbase.concepts.filter((concept) => selection.concept?.(concept) ?? true).map((concept) => ({
186
+ ...concept,
187
+ languages: concept.languages.map((language) => ({
188
+ ...language,
189
+ expressions: language.expressions.filter((expression) => selection.expression?.(termbase.getExpression(concept.id, expression.id)) ?? true)
190
+ })).filter((language) => language.expressions.length > 0)
191
+ })).filter((concept) => concept.languages.length > 0);
192
+ const selected = createTermbase({
193
+ ...termbase.data,
194
+ concepts
195
+ });
196
+ assertUsageConflicts(selected.expressions.map((entry) => ({
197
+ entry,
198
+ key: entry.expression.text
199
+ })), "select");
200
+ return selected;
201
+ }
202
+ function assertUsageConflicts(entries, stage) {
203
+ const seen = /* @__PURE__ */ new Map();
204
+ const issues = [];
205
+ for (const { entry, key } of entries) {
206
+ const identity = JSON.stringify([
207
+ entry.conceptId,
208
+ entry.language,
209
+ key
210
+ ]);
211
+ const previous = seen.get(identity);
212
+ if (previous && previous.expression.usage === "forbidden" !== (entry.expression.usage === "forbidden")) issues.push({
213
+ code: "usage-conflict",
214
+ message: "同一概念的有效表达同时允许和禁用。",
215
+ path: [
216
+ "concepts",
217
+ entry.conceptId,
218
+ "expressions",
219
+ entry.expressionId
220
+ ],
221
+ conceptId: entry.conceptId,
222
+ expressionId: entry.expressionId
223
+ });
224
+ else seen.set(identity, entry);
225
+ }
226
+ if (issues.length) throw new TermContractError(stage, issues);
227
+ }
228
+ // ../../packages/terminology/dist/yaml.js
229
+ var TermbaseYamlError = class extends TypeError {
230
+ stage;
231
+ issues;
232
+ constructor(stage, issues, options) {
233
+ super(issues.map(({ message }) => message).join(";"), options);
234
+ this.name = "TermbaseYamlError";
235
+ this.stage = stage;
236
+ this.issues = Object.freeze([...issues]);
237
+ }
238
+ };
239
+ /** 在内存中解析概念与语言 YAML,并返回经过领域校验的术语库。 */
240
+ function parseTermbaseYaml(files) {
241
+ const parsed = {
242
+ concepts: parseMapping(files.concepts, "concepts.yaml"),
243
+ languages: Object.fromEntries(Object.entries(files.languages).map(([language, contents]) => [language, parseMapping(contents, `${language}.yaml`, true)]))
244
+ };
245
+ const unknownConcepts = Object.entries(parsed.languages).flatMap(([language, declarations]) => Object.keys(declarations).filter((id) => !Object.hasOwn(parsed.concepts, id)).map((id) => ({
246
+ code: "unknown-concept",
247
+ file: `${language}.yaml`,
248
+ message: `${language}.yaml 引用了未在 concepts.yaml 登记的概念:${id}。`
249
+ })));
250
+ const declaredLanguages = Object.entries(parsed.languages).flatMap(([language, declarations]) => Object.entries(declarations).filter(([, declaration]) => Object.hasOwn(declaration, "language")).map(([id]) => ({
251
+ code: "language-in-file",
252
+ file: `${language}.yaml`,
253
+ message: `${language}.yaml 中的概念 ${id} 不得重复声明语言;语言由文件名确定。`
254
+ })));
255
+ const assemblyIssues = [...unknownConcepts, ...declaredLanguages];
256
+ if (assemblyIssues.length) throw new TermbaseYamlError("validation", assemblyIssues);
257
+ return createTermbase({ concepts: Object.entries(parsed.concepts).map(([id, metadata]) => {
258
+ const languages = Object.entries(parsed.languages).flatMap(([language, declarations]) => {
259
+ if (!Object.hasOwn(declarations, id)) return [];
260
+ return [{
261
+ ...declarations[id],
262
+ language
263
+ }];
264
+ });
265
+ return {
266
+ ...metadata,
267
+ id,
268
+ languages
269
+ };
270
+ }) });
271
+ }
272
+ const mappingSchema = z.record(z.string(), z.unknown());
273
+ const documentSchema = z.object({ concepts: mappingSchema });
274
+ const declarationsSchema = z.array(z.tuple([z.string(), mappingSchema]));
275
+ function parseMapping(contents, file, emptyAllowed = false) {
276
+ const document = parseDocument(contents, {
277
+ uniqueKeys: true,
278
+ version: "1.2",
279
+ schema: "core"
280
+ });
281
+ if (document.errors.length > 0) throw new TermbaseYamlError("parse", document.errors.map((error) => ({
282
+ code: error.code,
283
+ file,
284
+ message: `${file}:${error.message}`
285
+ })));
286
+ if (emptyAllowed && document.contents === null) return {};
287
+ rejectNonStringMappingKeys(document.contents, file);
288
+ const value = document.toJS({ maxAliasCount: 100 });
289
+ if (emptyAllowed && mappingSchema.safeParse(value).success && Object.keys(value).length === 0) return {};
290
+ const result = documentSchema.safeParse(value);
291
+ if (!result.success) throw new TermbaseYamlError("parse", result.error.issues.map((issue) => ({
292
+ code: "invalid-document",
293
+ file,
294
+ message: `${file} ${issue.path.join(".")}:${issue.message}`
295
+ })));
296
+ const concepts = value.concepts;
297
+ const entries = Object.entries(concepts);
298
+ const declarations = declarationsSchema.safeParse(entries);
299
+ if (!declarations.success) throw new TermbaseYamlError("parse", declarations.error.issues.map((issue) => ({
300
+ code: "invalid-declaration",
301
+ file,
302
+ message: `${file} concepts.${entries[Number(issue.path[0])]?.[0] ?? String(issue.path[0])}:${issue.message}`
303
+ })));
304
+ return concepts;
305
+ }
306
+ function rejectNonStringMappingKeys(node, file) {
307
+ if (isMap(node)) {
308
+ for (const pair of node.items) {
309
+ rejectMappingKey(pair.key, file);
310
+ rejectNonStringMappingKeys(pair.value, file);
311
+ }
312
+ return;
313
+ }
314
+ if (isSeq(node)) {
315
+ for (const item of node.items) rejectNonStringMappingKeys(item, file);
316
+ return;
317
+ }
318
+ if (isPair(node)) {
319
+ rejectMappingKey(node.key, file);
320
+ rejectNonStringMappingKeys(node.value, file);
321
+ }
322
+ }
323
+ function rejectMappingKey(key, file) {
324
+ if (isScalar(key) && typeof key.value === "string") return;
325
+ throw new TermbaseYamlError("parse", [{
326
+ code: "non-string-key",
327
+ file,
328
+ message: `${file} 中的映射键必须是文本。`
329
+ }]);
330
+ }
331
+ export { contractIssue as a, createTermbase as c, selectTerms as d, assertUsageConflicts as i, jsonValueSchema as l, parseTermbaseYaml as n, contractIssues as o, TermContractError as r, copyJson as s, TermbaseYamlError as t, nonemptyTextSchema as u };