mm_schame 0.0.0-stage → 1.0.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,63 @@
1
+ 'use strict';
2
+
3
+ const { Schame } = require('../lib/index.js');
4
+
5
+ // 一个典型的 OpenAI tool 定义
6
+ const TOOL = {
7
+ type: 'function',
8
+ function: {
9
+ name: 'get_weather',
10
+ description: '获取指定城市的天气',
11
+ parameters: {
12
+ type: 'object',
13
+ properties: {
14
+ city: { type: 'string', description: '城市名', minLength: 1 },
15
+ unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
16
+ date: { type: 'string', format: 'date' }
17
+ },
18
+ required: ['city'],
19
+ additionalProperties: false
20
+ }
21
+ }
22
+ };
23
+
24
+ // 1. 校验 tool 定义本身
25
+ console.log('tool 定义校验:', Schame.validateTool(TOOL));
26
+
27
+ // 2. 校验模型返回的 tool_calls 参数(JSON 字符串)
28
+ const schame = new Schame();
29
+ console.log('合法参数:', schame.validateArgs(TOOL.function.parameters, '{"city": "北京", "unit": "celsius"}'));
30
+ console.log('缺必需属性:', schame.validateArgs(TOOL.function.parameters, '{"unit": "celsius"}'));
31
+ console.log('非法 JSON:', schame.validateArgs(TOOL.function.parameters, '{oops'));
32
+
33
+ // 3. 通用 schema:$ref / 组合器 / 条件分支
34
+ const SCHEMA = {
35
+ $defs: {
36
+ address: {
37
+ type: 'object',
38
+ properties: { city: { type: 'string' }, zip: { type: 'string', pattern: '^\\d{6}$' } },
39
+ required: ['city']
40
+ }
41
+ },
42
+ type: 'object',
43
+ properties: {
44
+ name: { type: 'string', minLength: 1 },
45
+ age: { type: 'integer', minimum: 0, maximum: 150 },
46
+ tags: { type: 'array', items: { type: 'string' }, uniqueItems: true },
47
+ score: { anyOf: [{ type: 'number' }, { const: null }] },
48
+ address: { $ref: '#/$defs/address' },
49
+ contact: { if: { properties: { type: { const: 'email' } } }, then: { required: ['email'] } }
50
+ },
51
+ required: ['name'],
52
+ additionalProperties: false
53
+ };
54
+
55
+ const result = new Schame().validate(SCHEMA, {
56
+ name: '',
57
+ age: -1,
58
+ tags: ['a', 'a'],
59
+ score: 'x',
60
+ address: { zip: '123' },
61
+ contact: { type: 'email' }
62
+ });
63
+ console.log('综合校验:', JSON.stringify(result, null, 2));
package/lib/format.js ADDED
@@ -0,0 +1,119 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * IPv6 地址判断
5
+ * @param {string} value 待校验字符串
6
+ * @returns {boolean} 合法返回 true
7
+ */
8
+ function ipv6Check(value) {
9
+ const hexCheck = (item) => /^[0-9a-fA-F]{1,4}$/.test(item);
10
+ const parts = value.split('::');
11
+ if (parts.length > 2) return false;
12
+ const head = parts[0] ? parts[0].split(':') : [];
13
+ if (parts.length === 1) return head.length === 8 && head.every(hexCheck);
14
+ const tail = parts[1] ? parts[1].split(':') : [];
15
+ return head.length + tail.length <= 7 && head.every(hexCheck) && tail.every(hexCheck);
16
+ }
17
+
18
+ /**
19
+ * format 关键字校验函数表,键为格式名,值为 (value) => boolean
20
+ */
21
+ const FORMATS = {
22
+ /**
23
+ * 日期时间
24
+ * @param {string} value 待校验字符串
25
+ * @returns {boolean} 合法返回 true
26
+ */
27
+ // format 名由 JSON Schema 规范固定,不参与命名检测
28
+ /* eslint-disable-next-line naming-convention/function-name */
29
+ 'date-time': (value) =>
30
+ new RegExp('^\\d{4}-\\d{2}-\\d{2}[Tt ]\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?' +
31
+ '([Zz]|[+-]\\d{2}:?\\d{2})?$').test(value) && !Number.isNaN(Date.parse(value)),
32
+ /**
33
+ * 日期
34
+ * @param {string} value 待校验字符串
35
+ * @returns {boolean} 合法返回 true
36
+ */
37
+ date: (value) =>
38
+ new RegExp('^\\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$').test(value) &&
39
+ !Number.isNaN(Date.parse(value)),
40
+ /**
41
+ * 时间
42
+ * @param {string} value 待校验字符串
43
+ * @returns {boolean} 合法返回 true
44
+ */
45
+ time: (value) =>
46
+ new RegExp('^([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(\\.\\d+)?' +
47
+ '([Zz]|[+-]\\d{2}:?\\d{2})?$').test(value),
48
+ /**
49
+ * ISO8601 时长
50
+ * @param {string} value 待校验字符串
51
+ * @returns {boolean} 合法返回 true
52
+ */
53
+ duration: (value) =>
54
+ new RegExp('^P(?!$)(\\d+Y)?(\\d+M)?(\\d+W)?(\\d+D)?' +
55
+ '(T(?!$)(\\d+H)?(\\d+M)?(\\d+(\\.\\d+)?S)?)?$').test(value),
56
+ /**
57
+ * 邮箱
58
+ * @param {string} value 待校验字符串
59
+ * @returns {boolean} 合法返回 true
60
+ */
61
+ email: (value) => /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value),
62
+ /**
63
+ * 主机名
64
+ * @param {string} value 待校验字符串
65
+ * @returns {boolean} 合法返回 true
66
+ */
67
+ hostname: (value) =>
68
+ new RegExp('^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?' +
69
+ '(\\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$').test(value),
70
+ /**
71
+ * URI
72
+ * @param {string} value 待校验字符串
73
+ * @returns {boolean} 合法返回 true
74
+ */
75
+ uri: (value) => new RegExp('^[a-zA-Z][a-zA-Z0-9+.-]*:\\S*$').test(value),
76
+ /**
77
+ * UUID
78
+ * @param {string} value 待校验字符串
79
+ * @returns {boolean} 合法返回 true
80
+ */
81
+ uuid: (value) =>
82
+ new RegExp('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-' +
83
+ '[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$').test(value),
84
+ /**
85
+ * IPv4 地址
86
+ * @param {string} value 待校验字符串
87
+ * @returns {boolean} 合法返回 true
88
+ */
89
+ ipv4: (value) =>
90
+ new RegExp('^((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}' +
91
+ '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$').test(value),
92
+ /**
93
+ * IPv6 地址
94
+ * @param {string} value 待校验字符串
95
+ * @returns {boolean} 合法返回 true
96
+ */
97
+ ipv6: (value) => ipv6Check(value),
98
+ /**
99
+ * 合法正则表达式
100
+ * @param {string} value 待校验字符串
101
+ * @returns {boolean} 合法返回 true
102
+ */
103
+ regex: (value) => {
104
+ try {
105
+ return new RegExp(value) instanceof RegExp;
106
+ } catch (e) {
107
+ return false;
108
+ }
109
+ },
110
+ /**
111
+ * JSON Pointer
112
+ * @param {string} value 待校验字符串
113
+ * @returns {boolean} 合法返回 true
114
+ */
115
+ /* eslint-disable-next-line naming-convention/function-name */
116
+ 'json-pointer': (value) => value === '' || /^(\/([^~/]|~[01])*)*$/.test(value)
117
+ };
118
+
119
+ module.exports = { FORMATS };
package/lib/index.js ADDED
@@ -0,0 +1,5 @@
1
+ const Schame = require('./schame.js');
2
+
3
+ module.exports = {
4
+ Schame
5
+ };
package/lib/keyword.js ADDED
@@ -0,0 +1,270 @@
1
+ 'use strict';
2
+
3
+ const { FORMATS } = require('./format.js');
4
+
5
+ /**
6
+ * 判断是否为 JSON 对象
7
+ * @param {*} data 待判断值
8
+ * @returns {boolean} 是对象返回 true
9
+ */
10
+ function isObject(data) {
11
+ return typeof data === 'object' && data !== null && !Array.isArray(data);
12
+ }
13
+
14
+ /**
15
+ * 拼接 JSON Pointer 路径片段
16
+ * @param {string} path 当前路径
17
+ * @param {string|number} key 属性名或下标
18
+ * @returns {string} 新路径
19
+ */
20
+ function joinPath(path, key) {
21
+ return `${path}/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`;
22
+ }
23
+
24
+ /**
25
+ * 返回值的 JSON 类型名
26
+ * @param {*} data 待判断值
27
+ * @returns {string} 类型名
28
+ */
29
+ function jsonType(data) {
30
+ if (data === null) return 'null';
31
+ if (Array.isArray(data)) return 'array';
32
+ return typeof data;
33
+ }
34
+
35
+ /**
36
+ * 深度比较两个 JSON 值
37
+ * @param {*} a 值一
38
+ * @param {*} b 值二
39
+ * @returns {boolean} 相等返回 true
40
+ */
41
+ function equalJson(a, b) {
42
+ if (a === b) return true;
43
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
44
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
45
+ const keys_a = Object.keys(a);
46
+ const keys_b = Object.keys(b);
47
+ if (keys_a.length !== keys_b.length) return false;
48
+ return keys_a.every((key) => keys_b.includes(key) && equalJson(a[key], b[key]));
49
+ }
50
+
51
+ /** type 关键字类型判断表,键为类型名 */
52
+ const TYPE_CHECKS = {
53
+ null: (data) => data === null,
54
+ boolean: (data) => typeof data === 'boolean',
55
+ number: (data) => typeof data === 'number' && Number.isFinite(data),
56
+ integer: (data) => Number.isInteger(data),
57
+ string: (data) => typeof data === 'string',
58
+ object: (data) => isObject(data),
59
+ array: (data) => Array.isArray(data)
60
+ };
61
+
62
+ /**
63
+ * 关键字校验函数表
64
+ * 签名: (data, value, ctx, path) => void
65
+ * ctx: { schema, walk, subValid, subErrors, error }
66
+ * subErrors(schema, data, path) 返回子校验的错误列表,error(path, keyword, message) 记录错误
67
+ */
68
+ const KEYWORDS = {
69
+ type: (data, value, ctx, path) => {
70
+ const type_list = Array.isArray(value) ? value : [value];
71
+ const matched = type_list.some((item) => TYPE_CHECKS[item] && TYPE_CHECKS[item](data));
72
+ if (!matched) ctx.error(path, 'type', `期望类型 ${type_list.join(' | ')},实际为 ${jsonType(data)}`);
73
+ },
74
+ // 枚举
75
+ enum: (data, value, ctx, path) => {
76
+ if (Array.isArray(value) && !value.some((item) => equalJson(item, data))) {
77
+ ctx.error(path, 'enum', `值不在枚举 ${JSON.stringify(value)} 中`);
78
+ }
79
+ },
80
+ // 常量
81
+ const: (data, value, ctx, path) => {
82
+ if (!equalJson(value, data)) ctx.error(path, 'const', `值必须等于 ${JSON.stringify(value)}`);
83
+ },
84
+ // 满足全部子 schema
85
+ allOf: (data, value, ctx, path) => {
86
+ if (Array.isArray(value)) value.forEach((sub) => ctx.walk(sub, data, path));
87
+ },
88
+ // 满足至少一个子 schema
89
+ anyOf: (data, value, ctx, path) => {
90
+ if (!Array.isArray(value)) return;
91
+ const details = value.map((sub) => ctx.subErrors(sub, data, path));
92
+ if (details.some((errors) => errors.length === 0)) return;
93
+ const tips = details.map((errors, index) => `分支${index} ${errors[0].message}`);
94
+ ctx.error(path, 'anyOf', `值不满足 anyOf 中的任何分支:${tips.join(';')}`);
95
+ },
96
+ // 恰好满足一个子 schema
97
+ oneOf: (data, value, ctx, path) => {
98
+ const count = Array.isArray(value) ? value.filter((sub) => ctx.subValid(sub, data)).length : 0;
99
+ if (count !== 1) ctx.error(path, 'oneOf', `值须恰好满足 oneOf 一个分支,实际满足 ${count} 个`);
100
+ },
101
+ // 不得满足子 schema
102
+ not: (data, value, ctx, path) => {
103
+ if (ctx.subValid(value, data)) ctx.error(path, 'not', '值不得满足 not 中的 schema');
104
+ },
105
+ // 属性约束
106
+ properties: (data, value, ctx, path) => {
107
+ if (!isObject(data) || !isObject(value)) return;
108
+ for (const key of Object.keys(value)) {
109
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
110
+ ctx.walk(value[key], data[key], joinPath(path, key));
111
+ }
112
+ }
113
+ },
114
+ // 必需属性
115
+ required: (data, value, ctx, path) => {
116
+ if (!isObject(data) || !Array.isArray(value)) return;
117
+ value.forEach((key) => {
118
+ if (!Object.prototype.hasOwnProperty.call(data, key)) {
119
+ ctx.error(path, 'required', `缺少必需属性 '${key}'`);
120
+ }
121
+ });
122
+ },
123
+ // 额外属性约束
124
+ additionalProperties: (data, value, ctx, path) => {
125
+ if (!isObject(data)) return;
126
+ const props = isObject(ctx.schema.properties) ? ctx.schema.properties : {};
127
+ const patterns = isObject(ctx.schema.patternProperties)
128
+ ? Object.keys(ctx.schema.patternProperties)
129
+ : [];
130
+ for (const key of Object.keys(data)) {
131
+ if (props[key] === undefined && !patterns.some((item) => new RegExp(item).test(key))) {
132
+ if (value === false) ctx.error(joinPath(path, key), 'additionalProperties', `存在未定义的属性 '${key}'`);
133
+ else ctx.walk(value, data[key], joinPath(path, key));
134
+ }
135
+ }
136
+ },
137
+ // 按属性名模式约束
138
+ patternProperties: (data, value, ctx, path) => {
139
+ if (!isObject(data) || !isObject(value)) return;
140
+ for (const pattern of Object.keys(value)) {
141
+ const reg_exp = new RegExp(pattern);
142
+ for (const key of Object.keys(data)) {
143
+ if (reg_exp.test(key)) ctx.walk(value[pattern], data[key], joinPath(path, key));
144
+ }
145
+ }
146
+ },
147
+ // 属性名本身校验
148
+ propertyNames: (data, value, ctx, path) => {
149
+ if (!isObject(data)) return;
150
+ Object.keys(data).forEach((key) => ctx.walk(value, key, joinPath(path, key)));
151
+ },
152
+ minProperties: (data, value, ctx, path) => {
153
+ if (isObject(data) && Object.keys(data).length < value) {
154
+ ctx.error(path, 'minProperties', `属性个数不得少于 ${value}`);
155
+ }
156
+ },
157
+ maxProperties: (data, value, ctx, path) => {
158
+ if (isObject(data) && Object.keys(data).length > value) {
159
+ ctx.error(path, 'maxProperties', `属性个数不得多于 ${value}`);
160
+ }
161
+ },
162
+ // 属性依赖(必需)
163
+ dependentRequired: (data, value, ctx, path) => {
164
+ if (!isObject(data) || !isObject(value)) return;
165
+ for (const key of Object.keys(value)) {
166
+ if (!Object.prototype.hasOwnProperty.call(data, key)) continue;
167
+ value[key].forEach((dep) => {
168
+ if (!Object.prototype.hasOwnProperty.call(data, dep)) {
169
+ ctx.error(path, 'dependentRequired', `存在属性 '${key}' 时必须同时存在 '${dep}'`);
170
+ }
171
+ });
172
+ }
173
+ },
174
+ // 属性依赖(schema)
175
+ dependentSchemas: (data, value, ctx, path) => {
176
+ if (!isObject(data) || !isObject(value)) return;
177
+ for (const key of Object.keys(value)) {
178
+ if (Object.prototype.hasOwnProperty.call(data, key)) ctx.walk(value[key], data, path);
179
+ }
180
+ },
181
+ // 数组元素约束(兼容 draft-07 元组写法)
182
+ items: (data, value, ctx, path) => {
183
+ if (!Array.isArray(data)) return;
184
+ if (Array.isArray(value)) {
185
+ value.forEach((sub, index) => {
186
+ if (index < data.length) ctx.walk(sub, data[index], joinPath(path, index));
187
+ });
188
+ return;
189
+ }
190
+ const start = Array.isArray(ctx.schema.prefixItems) ? ctx.schema.prefixItems.length : 0;
191
+ for (let index = start; index < data.length; index += 1) {
192
+ ctx.walk(value, data[index], joinPath(path, index));
193
+ }
194
+ },
195
+ // 前缀元素约束(关键字名由 JSON Schema 规范固定,不参与命名检测)
196
+ /* eslint-disable-next-line naming-convention/function-name */
197
+ prefixItems: (data, value, ctx, path) => {
198
+ if (!Array.isArray(data) || !Array.isArray(value)) return;
199
+ value.forEach((sub, index) => {
200
+ if (index < data.length) ctx.walk(sub, data[index], joinPath(path, index));
201
+ });
202
+ },
203
+ // 包含匹配元素(minContains 并入此判断)
204
+ contains: (data, value, ctx, path) => {
205
+ if (!Array.isArray(data)) return;
206
+ const min = typeof ctx.schema.minContains === 'number' ? ctx.schema.minContains : 1;
207
+ const count = data.filter((item) => ctx.subValid(value, item)).length;
208
+ if (count < min) ctx.error(path, 'contains', `至少需包含 ${min} 个匹配元素,实际 ${count} 个`);
209
+ },
210
+ maxContains: (data, value, ctx, path) => {
211
+ if (!Array.isArray(data) || ctx.schema.contains === undefined) return;
212
+ const count = data.filter((item) => ctx.subValid(ctx.schema.contains, item)).length;
213
+ if (count > value) ctx.error(path, 'maxContains', `匹配 contains 的元素不得多于 ${value} 个`);
214
+ },
215
+ /* eslint-disable-next-line naming-convention/function-name */
216
+ minItems: (data, value, ctx, path) => {
217
+ if (Array.isArray(data) && data.length < value) ctx.error(path, 'minItems', `数组长度不得小于 ${value}`);
218
+ },
219
+ /* eslint-disable-next-line naming-convention/function-name */
220
+ maxItems: (data, value, ctx, path) => {
221
+ if (Array.isArray(data) && data.length > value) ctx.error(path, 'maxItems', `数组长度不得大于 ${value}`);
222
+ },
223
+ // 元素唯一
224
+ /* eslint-disable-next-line naming-convention/function-name */
225
+ uniqueItems: (data, value, ctx, path) => {
226
+ if (!Array.isArray(data) || !value) return;
227
+ for (let i = 0; i < data.length; i += 1) {
228
+ for (let j = i + 1; j < data.length; j += 1) {
229
+ if (equalJson(data[i], data[j])) {
230
+ ctx.error(path, 'uniqueItems', `第 ${j} 项与第 ${i} 项重复`);
231
+ return;
232
+ }
233
+ }
234
+ }
235
+ },
236
+ minLength: (data, value, ctx, path) => {
237
+ if (typeof data === 'string' && data.length < value) ctx.error(path, 'minLength', `字符串长度不得小于 ${value}`);
238
+ },
239
+ maxLength: (data, value, ctx, path) => {
240
+ if (typeof data === 'string' && data.length > value) ctx.error(path, 'maxLength', `字符串长度不得大于 ${value}`);
241
+ },
242
+ pattern: (data, value, ctx, path) => {
243
+ if (typeof data === 'string' && !new RegExp(value).test(data)) {
244
+ ctx.error(path, 'pattern', `字符串不匹配模式 ${value}`);
245
+ }
246
+ },
247
+ format: (data, value, ctx, path) => {
248
+ const check = FORMATS[value];
249
+ if (typeof data === 'string' && check && !check(data)) ctx.error(path, 'format', `字符串不符合 format '${value}'`);
250
+ },
251
+ minimum: (data, value, ctx, path) => {
252
+ if (typeof data === 'number' && data < value) ctx.error(path, 'minimum', `数值不得小于 ${value}`);
253
+ },
254
+ maximum: (data, value, ctx, path) => {
255
+ if (typeof data === 'number' && data > value) ctx.error(path, 'maximum', `数值不得大于 ${value}`);
256
+ },
257
+ exclusiveMinimum: (data, value, ctx, path) => {
258
+ if (typeof data === 'number' && data <= value) ctx.error(path, 'exclusiveMinimum', `数值必须大于 ${value}`);
259
+ },
260
+ exclusiveMaximum: (data, value, ctx, path) => {
261
+ if (typeof data === 'number' && data >= value) ctx.error(path, 'exclusiveMaximum', `数值必须小于 ${value}`);
262
+ },
263
+ multipleOf: (data, value, ctx, path) => {
264
+ if (typeof data !== 'number' || !value) return;
265
+ const quotient = data / value;
266
+ if (Math.abs(quotient - Math.round(quotient)) > 1e-9) ctx.error(path, 'multipleOf', `数值必须是 ${value} 的整数倍`);
267
+ }
268
+ };
269
+
270
+ module.exports = { KEYWORDS };
package/lib/schame.js ADDED
@@ -0,0 +1,206 @@
1
+ 'use strict';
2
+
3
+ const { KEYWORDS } = require('./keyword.js');
4
+
5
+ /** OpenAI tool name 合法格式 */
6
+ const TOOL_NAME_REG_EXP = /^[a-zA-Z0-9_-]{1,64}$/;
7
+
8
+ /** OpenAI tool.function 各字段合法性判断表(name 必填,其余可选) */
9
+ const TOOL_CHECKS = {
10
+ name: (value) => typeof value === 'string' && TOOL_NAME_REG_EXP.test(value),
11
+ description: (value) => typeof value === 'string',
12
+ parameters: (value) => isPlainObject(value) && value.type === 'object',
13
+ strict: (value) => typeof value === 'boolean'
14
+ };
15
+
16
+ /**
17
+ * 判断是否为非数组普通对象
18
+ * @param {*} value 待判断值
19
+ * @returns {boolean} 是对象返回 true
20
+ */
21
+ function isPlainObject(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ /**
26
+ * JSON Schema 校验类(draft 2020-12 常用关键字),兼容 OpenAI tool 参数校验
27
+ */
28
+ class Schame {
29
+ static config = {};
30
+
31
+ /**
32
+ * 构造函数
33
+ * @param {object} config - 配置
34
+ * @param {object} parent - 上级
35
+ */
36
+ constructor(config, parent) {
37
+ void parent;
38
+ this.config = { ...Schame.config };
39
+ this.setConfig(config);
40
+ }
41
+
42
+ /**
43
+ * 合并实例配置
44
+ * @param {object} config 配置对象
45
+ */
46
+ setConfig(config) {
47
+ this.config = { ...this.config, ...config };
48
+ }
49
+
50
+ /**
51
+ * 校验数据
52
+ * @param {object|boolean} schema JSON Schema
53
+ * @param {*} data 待校验数据
54
+ * @returns {{valid: boolean, errors: Array<{path: string, keyword: string, message: string}>}} 校验结果
55
+ */
56
+ validate(schema, data) {
57
+ const errors = [];
58
+ const ctx = {
59
+ root: schema,
60
+ errors,
61
+ stack: new Map(),
62
+ walk: (sub_schema, item, path) => this.#walk(sub_schema, item, path, ctx),
63
+ subErrors: (sub_schema, item, path = '') => {
64
+ const saved = ctx.errors;
65
+ ctx.errors = [];
66
+ this.#walk(sub_schema, item, path, ctx);
67
+ const sub_errors = ctx.errors;
68
+ ctx.errors = saved;
69
+ return sub_errors;
70
+ },
71
+ subValid: (sub_schema, item) => ctx.subErrors(sub_schema, item).length === 0,
72
+ error: (path, keyword, message) => ctx.errors.push({ path, keyword, message })
73
+ };
74
+ this.#walk(schema, data, '', ctx);
75
+ return { valid: errors.length === 0, errors };
76
+ }
77
+
78
+ /**
79
+ * 布尔式校验
80
+ * @param {object|boolean} schema JSON Schema
81
+ * @param {*} data 待校验数据
82
+ * @returns {boolean} 通过返回 true
83
+ */
84
+ isValid(schema, data) {
85
+ return this.validate(schema, data).valid;
86
+ }
87
+
88
+ /**
89
+ * 校验 OpenAI tool 调用参数(tool_calls.function.arguments,JSON 字符串或对象)
90
+ * @param {object|boolean} schema JSON Schema
91
+ * @param {string|*} args 调用参数
92
+ * @returns {{valid: boolean, errors: Array}} 校验结果
93
+ */
94
+ validateArgs(schema, args) {
95
+ if (typeof args !== 'string') return this.validate(schema, args);
96
+ try {
97
+ return this.validate(schema, JSON.parse(args));
98
+ } catch (e) {
99
+ return { valid: false, errors: [{ path: '', keyword: 'json', message: '参数不是合法的 JSON 字符串' }] };
100
+ }
101
+ }
102
+
103
+ /**
104
+ * 校验 OpenAI tool 定义结构
105
+ * @param {object} tool tool 定义对象
106
+ * @returns {{valid: boolean, errors: Array}} 校验结果
107
+ */
108
+ static validateTool(tool) {
109
+ const errors = [];
110
+ const fn = tool && tool.function;
111
+ if (!isPlainObject(fn) || tool.type !== 'function') {
112
+ errors.push({ path: '', keyword: 'tool', message: 'tool 必须是 { type: "function", function: { ... } } 结构' });
113
+ return { valid: false, errors };
114
+ }
115
+ for (const key of Object.keys(TOOL_CHECKS)) {
116
+ const invalid = fn[key] === undefined ? key === 'name' : !TOOL_CHECKS[key](fn[key]);
117
+ if (invalid) errors.push({ path: `/function/${key}`, keyword: 'tool', message: `function.${key} 不符合规范` });
118
+ }
119
+ return { valid: errors.length === 0, errors };
120
+ }
121
+
122
+ /**
123
+ * 递归校验单个 schema 节点
124
+ * @param {object|boolean} schema 子 schema
125
+ * @param {*} data 当前数据
126
+ * @param {string} path 当前 JSON Pointer 路径
127
+ * @param {object} ctx 校验上下文
128
+ */
129
+ #walk(schema, data, path, ctx) {
130
+ if (schema === false) {
131
+ ctx.error(path, 'schema', '该位置不允许任何值');
132
+ return;
133
+ }
134
+ if (!schema || typeof schema !== 'object') return;
135
+ if (typeof schema.$ref === 'string') {
136
+ this.#walkRef(schema.$ref, data, path, ctx);
137
+ return;
138
+ }
139
+ this.#walkBranch(schema, data, path, ctx);
140
+ const node_ctx = { ...ctx, schema };
141
+ for (const keyword of Object.keys(schema)) {
142
+ if (KEYWORDS[keyword]) KEYWORDS[keyword](data, schema[keyword], node_ctx, path);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * 处理 if/then/else 分支
148
+ * @param {object} schema 子 schema
149
+ * @param {*} data 当前数据
150
+ * @param {string} path 当前路径
151
+ * @param {object} ctx 校验上下文
152
+ */
153
+ #walkBranch(schema, data, path, ctx) {
154
+ if (schema.if === undefined) return;
155
+ const branch = ctx.subValid(schema.if, data) ? schema.then : schema.else;
156
+ if (branch !== undefined) this.#walk(branch, data, path, ctx);
157
+ }
158
+
159
+ /**
160
+ * 解析并校验 $ref 引用(仅支持内部 JSON Pointer)
161
+ * 按 schema + 数据对象成对防循环:同一 schema 对同一数据对象只在祖先链上出现一次,
162
+ * 保证递归引用每层数据都被校验,又能挡住 JS 对象自引用造成的死循环
163
+ * @param {string} ref 引用字符串
164
+ * @param {*} data 当前数据
165
+ * @param {string} path 当前路径
166
+ * @param {object} ctx 校验上下文
167
+ */
168
+ #walkRef(ref, data, path, ctx) {
169
+ const target = this.#resolve(ref, ctx.root);
170
+ if (!target) return;
171
+ // 原始值无法再嵌套,不存在循环风险,不需要登记
172
+ if (!isPlainObject(data) && !Array.isArray(data)) {
173
+ this.#walk(target, data, path, ctx);
174
+ return;
175
+ }
176
+ let seen = ctx.stack.get(target);
177
+ if (!seen) {
178
+ seen = new Set();
179
+ ctx.stack.set(target, seen);
180
+ }
181
+ if (seen.has(data)) return;
182
+ seen.add(data);
183
+ this.#walk(target, data, path, ctx);
184
+ seen.delete(data);
185
+ }
186
+
187
+ /**
188
+ * 解析内部 JSON Pointer(如 #/$defs/Foo)
189
+ * @param {string} ref 引用字符串
190
+ * @param {object} root 根 schema
191
+ * @returns {object|undefined} 目标子 schema
192
+ */
193
+ #resolve(ref, root) {
194
+ if (!ref.startsWith('#')) return undefined;
195
+ let node = root;
196
+ if (ref.length > 1) {
197
+ for (const segment of ref.slice(2).split('/')) {
198
+ const key = segment.replace(/~1/g, '/').replace(/~0/g, '~');
199
+ node = node && node[key];
200
+ }
201
+ }
202
+ return node;
203
+ }
204
+ }
205
+
206
+ module.exports = Schame;
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "mm_schame",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "这是一个完整的 JSON Schema(draft 2020-12 常用关键字)校验模块,可用于验证 OpenAI tool 参数。",
5
+ "keywords": [
6
+ "mm_mod",
7
+ "mm_infra",
8
+ "mm_common",
9
+ "超级美眉",
10
+ "参数验证",
11
+ "数据校验",
12
+ "json schema",
13
+ "schema",
14
+ "validator",
15
+ "openai",
16
+ "tool",
17
+ "nodejs",
18
+ "commonjs"
19
+ ],
20
+ "layer": "util",
21
+ "group": "no_io",
22
+ "author": "邱文武",
23
+ "license": "ISC",
24
+ "type": "commonjs",
25
+ "engines": {
26
+ "node": ">=16"
27
+ },
28
+ "main": "lib/index.js",
29
+ "files": [
30
+ "lib",
31
+ "example",
32
+ "tool"
33
+ ],
34
+ "directories": {
35
+ "example": "example",
36
+ "lib": "lib"
37
+ },
38
+ "homepage": "https://gitee.com/qiuwenwu91/mm_schame#readme",
39
+ "bugs": {
40
+ "url": "https://gitee.com/qiuwenwu91/mm_schame/issues"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://gitee.com/qiuwenwu91/mm_schame.git"
45
+ },
46
+ "scripts": {
47
+ "test": "jest --coverage",
48
+ "demo": "node example/index.js",
49
+ "prepublishOnly": "npm test",
50
+ "lint": "eslint .",
51
+ "lint:fix": "eslint . --fix --rule \"naming-convention/class-name:off\" --rule \"naming-convention/function-name:off\" --rule \"naming-convention/variable-name:off\" --rule \"naming-convention/constant-name:off\" --rule \"naming-convention/param-name:off\" --rule \"prefer-arrow-callback:off\""
52
+ },
53
+ "devDependencies": {
54
+ "jest": "^30.5.2",
55
+ "eslint": "^10.15.0",
56
+ "mm_eslint": "^2.15.0",
57
+ "eslint-plugin-jsdoc": "^65.5.7"
58
+ }
59
+ }
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * schame - JSON Schema 校验
5
+ * 按 JSON Schema(draft 2020-12 常用关键字)校验数据,可用于验证 OpenAI tool 参数。触发关键词:schema校验、参数结构验证、tool参数校验。适用场景:接口入参校验、模型工具调用参数校验。
6
+ * 入口:main(params, ctx, options),供 LLM / workflow 调用
7
+ */
8
+ const { Schame } = require('../../lib/index.js');
9
+
10
+ /**
11
+ * 执行工具
12
+ * @param {object} params 输入参数
13
+ * @param {object} ctx 上下文对象
14
+ * @param {object} options 运行选项
15
+ * @returns {*} 工具执行的纯粹结果(失败时抛出 Error,由 mm_toolkit 统一封装)
16
+ */
17
+ function main(params, ctx, options) {
18
+ void ctx;
19
+ void options;
20
+ return new Schame().validate(params.schema, params.data);
21
+ }
22
+
23
+ module.exports = { main };
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "schame",
3
+ "title": "JSON Schema 校验",
4
+ "description": "按 JSON Schema(draft 2020-12 常用关键字)校验数据,可用于验证 OpenAI tool 参数。触发关键词:schema校验、参数结构验证、tool参数校验。适用场景:接口入参校验、模型工具调用参数校验。",
5
+ "category": "参数校验",
6
+ "group": "validation",
7
+ "type": "function",
8
+ "main": "./index.js",
9
+ "params": {
10
+ "type": "object",
11
+ "properties": {
12
+ "schema": {
13
+ "type": "object",
14
+ "description": "JSON Schema 定义"
15
+ },
16
+ "data": {
17
+ "description": "待校验的数据"
18
+ }
19
+ },
20
+ "required": [
21
+ "schema",
22
+ "data"
23
+ ]
24
+ },
25
+ "returns": {
26
+ "description": "校验结果 { valid, errors };失败时抛出 Error,由 mm_toolkit 统一封装"
27
+ },
28
+ "handler": "manager"
29
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.