schema-dsl 2.0.0 → 2.0.1
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/CHANGELOG.md +130 -113
- package/LICENSE +21 -21
- package/README.md +628 -628
- package/dist/{DslBuilder-DkLaOo9Q.d.ts → DslBuilder-BIgQOAXp.d.ts} +2 -0
- package/dist/{DslBuilder-DQDN0ZxZ.d.cts → DslBuilder-CjHTucNQ.d.cts} +2 -0
- package/dist/{Validator-hFWKGxir.d.ts → Validator-CllRdrY0.d.ts} +1 -1
- package/dist/{Validator-C7GsVQOH.d.cts → Validator-D6okG9tr.d.cts} +1 -1
- package/dist/index.cjs +75 -29
- package/dist/index.d.cts +10 -4
- package/dist/index.d.ts +10 -4
- package/dist/index.js +75 -29
- package/dist/plugins/custom-format.cjs +33 -17
- package/dist/plugins/custom-format.d.cts +1 -1
- package/dist/plugins/custom-format.d.ts +1 -1
- package/dist/plugins/custom-format.js +33 -17
- package/dist/plugins/custom-type-example.cjs +33 -17
- package/dist/plugins/custom-type-example.d.cts +1 -1
- package/dist/plugins/custom-type-example.d.ts +1 -1
- package/dist/plugins/custom-type-example.js +33 -17
- package/dist/plugins/custom-validator.cjs +0 -2
- package/dist/plugins/custom-validator.d.cts +1 -1
- package/dist/plugins/custom-validator.d.ts +1 -1
- package/dist/plugins/custom-validator.js +0 -2
- package/docs/FEATURE-INDEX.md +553 -553
- package/docs/add-custom-locale.md +496 -496
- package/docs/add-keyword.md +24 -24
- package/docs/api-reference.md +1047 -1047
- package/docs/api.md +13 -13
- package/docs/best-practices-project-structure.md +417 -417
- package/docs/best-practices.md +712 -712
- package/docs/cache-manager.md +344 -344
- package/docs/compile.md +45 -45
- package/docs/conditional-api.md +1307 -1307
- package/docs/custom-extensions-guide.md +339 -339
- package/docs/design-philosophy.md +606 -606
- package/docs/doc-index.md +324 -324
- package/docs/dsl-syntax.md +714 -714
- package/docs/dynamic-locale.md +608 -608
- package/docs/enum.md +482 -482
- package/docs/error-handling.md +1975 -1975
- package/docs/export-guide.md +501 -501
- package/docs/export-limitations.md +567 -567
- package/docs/faq.md +596 -596
- package/docs/frontend-i18n-guide.md +307 -307
- package/docs/i18n-user-guide.md +487 -487
- package/docs/i18n.md +476 -476
- package/docs/index.md +48 -48
- package/docs/json-schema-basics.md +40 -40
- package/docs/label-vs-description.md +271 -271
- package/docs/markdown-exporter.md +406 -406
- package/docs/mongodb-exporter.md +302 -302
- package/docs/multi-language.md +26 -26
- package/docs/multi-type-support.md +322 -322
- package/docs/mysql-exporter.md +280 -280
- package/docs/number-operators.md +449 -449
- package/docs/optional-marker-guide.md +326 -326
- package/docs/performance-guide.md +49 -49
- package/docs/plugin-system.md +381 -381
- package/docs/plugin-type-registration.md +34 -34
- package/docs/postgresql-exporter.md +311 -311
- package/docs/public/favicon.svg +4 -4
- package/docs/quick-start.md +435 -435
- package/docs/runtime-locale-support.md +532 -532
- package/docs/schema-helper.md +345 -345
- package/docs/schema-utils-advanced-issues.md +23 -23
- package/docs/schema-utils-best-practices.md +20 -20
- package/docs/schema-utils-chaining.md +150 -150
- package/docs/schema-utils.md +524 -524
- package/docs/security-checklist.md +20 -20
- package/docs/string-extensions.md +488 -488
- package/docs/troubleshooting.md +486 -486
- package/docs/type-converter.md +310 -310
- package/docs/type-reference.md +242 -242
- package/docs/typescript-guide.md +584 -584
- package/docs/union-type-guide.md +157 -157
- package/docs/union-types.md +284 -284
- package/docs/validate-async.md +491 -491
- package/docs/validate-batch.md +49 -49
- package/docs/validate-dsl-object-support.md +578 -578
- package/docs/validate.md +506 -506
- package/docs/validation-guide.md +502 -502
- package/docs/validator.md +39 -39
- package/package.json +131 -131
- package/plugins/custom-format.cjs +8 -8
- package/plugins/custom-type-example.cjs +8 -8
- package/plugins/custom-validator.cjs +8 -8
- package/src/adapters/DslAdapter.ts +111 -111
- package/src/adapters/index.ts +1 -1
- package/src/config/constants.ts +83 -83
- package/src/config/index.ts +2 -2
- package/src/config/patterns.ts +77 -77
- package/src/core/CacheManager.ts +169 -159
- package/src/core/ConditionalBuilder.ts +382 -382
- package/src/core/ConditionalRuntime.ts +27 -27
- package/src/core/ConditionalValidator.ts +254 -254
- package/src/core/DslBuilder.ts +687 -677
- package/src/core/ErrorCodes.ts +38 -38
- package/src/core/ErrorFormatter.ts +271 -271
- package/src/core/JSONSchemaCore.ts +65 -65
- package/src/core/Locale.ts +187 -187
- package/src/core/MessageTemplate.ts +42 -42
- package/src/core/ObjectDslBuilder.ts +64 -64
- package/src/core/PluginManager.ts +326 -326
- package/src/core/StringExtensions.ts +140 -140
- package/src/core/TemplateEngine.ts +44 -44
- package/src/core/Validator.ts +448 -448
- package/src/errors/I18nError.ts +159 -159
- package/src/errors/ValidationError.ts +105 -105
- package/src/exporters/BaseExporter.ts +60 -60
- package/src/exporters/MarkdownExporter.ts +305 -305
- package/src/exporters/MongoDBExporter.ts +126 -126
- package/src/exporters/MySQLExporter.ts +156 -155
- package/src/exporters/PostgreSQLExporter.ts +222 -222
- package/src/exporters/index.ts +18 -18
- package/src/index.ts +651 -633
- package/src/locales/en-US.ts +160 -160
- package/src/locales/es-ES.ts +160 -160
- package/src/locales/fr-FR.ts +160 -160
- package/src/locales/index.ts +103 -103
- package/src/locales/ja-JP.ts +160 -160
- package/src/locales/types.ts +156 -156
- package/src/locales/zh-CN.ts +160 -160
- package/src/parser/ConstraintParser.ts +101 -101
- package/src/parser/DslParser.ts +470 -470
- package/src/parser/SchemaCompiler.ts +66 -66
- package/src/parser/TypeRegistry.ts +250 -250
- package/src/parser/index.ts +6 -6
- package/src/plugins/custom-format.ts +124 -126
- package/src/plugins/custom-type-example.ts +106 -108
- package/src/plugins/custom-validator.ts +138 -140
- package/src/types/conditional.ts +28 -28
- package/src/types/config.ts +59 -59
- package/src/types/dsl.ts +131 -131
- package/src/types/error.ts +60 -60
- package/src/types/index.ts +17 -17
- package/src/types/infer.ts +127 -127
- package/src/types/plugin.ts +58 -58
- package/src/types/safe-regex.d.ts +9 -9
- package/src/types/schema.ts +66 -66
- package/src/types/validate.ts +71 -71
- package/src/utils/SchemaHelper.ts +196 -196
- package/src/utils/SchemaUtils.ts +365 -346
- package/src/utils/TypeConverter.ts +215 -215
- package/src/utils/index.ts +10 -10
- package/src/validators/CustomKeywords.ts +477 -477
package/src/utils/SchemaUtils.ts
CHANGED
|
@@ -1,346 +1,365 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SchemaUtils — Advanced schema operations (reuse, merge, extend, performance monitoring)
|
|
3
|
-
*
|
|
4
|
-
* v2 note: v1's extend/validateBatch used require('../adapters/DslAdapter'),
|
|
5
|
-
* v2 uses dynamic import or accepts pre-compiled schema directly (avoids circular deps)
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type { JSONSchema } from '../types/schema.js'
|
|
9
|
-
import { DslAdapter } from '../adapters/DslAdapter.js'
|
|
10
|
-
|
|
11
|
-
// Internal: chainable schema wrapper type
|
|
12
|
-
interface ChainableSchema extends JSONSchema {
|
|
13
|
-
_isChainable: true
|
|
14
|
-
partial(fields?: string[]): ChainableSchema
|
|
15
|
-
pick(fields: string[]): ChainableSchema
|
|
16
|
-
omit(fields: string[]): ChainableSchema
|
|
17
|
-
extend(extensions: Record<string, unknown>): ChainableSchema
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// ==================== SchemaUtils ====================
|
|
21
|
-
|
|
22
|
-
export class SchemaUtils {
|
|
23
|
-
// ========== Schema Reuse ==========
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Create a reusable schema factory.
|
|
27
|
-
* @example const emailField = SchemaUtils.reusable(() => dsl('email!').label('email'))
|
|
28
|
-
*/
|
|
29
|
-
static reusable<T>(factory: () => T): () => T {
|
|
30
|
-
return factory
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Create a schema fragment library.
|
|
35
|
-
* @example const fields = SchemaUtils.createLibrary({ email: () => dsl('email!') })
|
|
36
|
-
*/
|
|
37
|
-
static createLibrary<T extends Record<string, () => unknown>>(fragments: T): T {
|
|
38
|
-
return fragments
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// ========== Schema Reuse & Extension ==========
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* Extend a schema (like inheritance) — merges extension fields into the base schema.
|
|
45
|
-
*/
|
|
46
|
-
static extend(baseSchema: JSONSchema, extensions: JSONSchema | Record<string, unknown>): ChainableSchema {
|
|
47
|
-
const result: Record<string, unknown> = {
|
|
48
|
-
type: 'object',
|
|
49
|
-
properties: {} as Record<string, unknown>,
|
|
50
|
-
required: [] as string[],
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Copy base schema
|
|
54
|
-
if (baseSchema.properties) {
|
|
55
|
-
result['properties'] = this._mergeProperties(
|
|
56
|
-
result['properties'] as Record<string, unknown>,
|
|
57
|
-
baseSchema.properties as Record<string, unknown>,
|
|
58
|
-
)
|
|
59
|
-
}
|
|
60
|
-
if (baseSchema.required) {
|
|
61
|
-
result['required'] = [...baseSchema.required]
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Detect flat DSL definition: if no 'properties' key but has string values, treat as DSL
|
|
65
|
-
let extSchema: JSONSchema
|
|
66
|
-
if (!('properties' in extensions) && Object.values(extensions).some(v => typeof v === 'string')) {
|
|
67
|
-
extSchema = DslAdapter.parseObject(extensions as Record<string, string>).toSchema()
|
|
68
|
-
} else {
|
|
69
|
-
extSchema = extensions as JSONSchema
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// Merge extension schema (deep-merge same-name nested objects instead of replacing)
|
|
73
|
-
if (extSchema.properties) {
|
|
74
|
-
result['properties'] = this._mergeProperties(
|
|
75
|
-
result['properties'] as Record<string, unknown>,
|
|
76
|
-
extSchema.properties as Record<string, unknown>,
|
|
77
|
-
)
|
|
78
|
-
}
|
|
79
|
-
if (extSchema.required) {
|
|
80
|
-
result['required'] = [...new Set([
|
|
81
|
-
...(result['required'] as string[]),
|
|
82
|
-
...extSchema.required,
|
|
83
|
-
])]
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
return this._makeChainable(result as JSONSchema)
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Pick a subset of fields from a schema.
|
|
91
|
-
*/
|
|
92
|
-
static pick(schema: JSONSchema, fields: string[]): ChainableSchema {
|
|
93
|
-
const result: Record<string, unknown> = {
|
|
94
|
-
type: 'object',
|
|
95
|
-
properties: {} as Record<string, unknown>,
|
|
96
|
-
required: [] as string[],
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
for (const field of fields) {
|
|
100
|
-
if (schema.properties?.[field]) {
|
|
101
|
-
(result['properties'] as Record<string, unknown>)[field] = this._clone(schema.properties[field] as JSONSchema)
|
|
102
|
-
if (schema.required?.includes(field)) {
|
|
103
|
-
(result['required'] as string[]).push(field)
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
return this._makeChainable(result as JSONSchema)
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Omit fields from a schema.
|
|
113
|
-
*/
|
|
114
|
-
static omit(schema: JSONSchema, fields: string[]): ChainableSchema {
|
|
115
|
-
const result = this._clone(schema)
|
|
116
|
-
|
|
117
|
-
for (const field of fields) {
|
|
118
|
-
if (result['properties']) {
|
|
119
|
-
delete (result['properties'] as Record<string, unknown>)[field]
|
|
120
|
-
}
|
|
121
|
-
if (Array.isArray(result['required'])) {
|
|
122
|
-
result['required'] = (result['required'] as string[]).filter((f: string) => f !== field)
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// Remove empty required array
|
|
127
|
-
if (Array.isArray(result['required']) && (result['required'] as string[]).length === 0) {
|
|
128
|
-
delete result['required']
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return this._makeChainable(result as JSONSchema)
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Make all fields optional (removes required).
|
|
136
|
-
* @param fields - optional; only process these fields (others remain unchanged)
|
|
137
|
-
*/
|
|
138
|
-
static partial(schema: JSONSchema, fields?: string[] | null): ChainableSchema {
|
|
139
|
-
let raw: Record<string, unknown>
|
|
140
|
-
|
|
141
|
-
if (fields) {
|
|
142
|
-
const picked = this.pick(schema, fields)
|
|
143
|
-
raw = this._extractSchema(picked)
|
|
144
|
-
} else {
|
|
145
|
-
raw = this._clone(schema)
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
this._deleteRequired(raw)
|
|
149
|
-
|
|
150
|
-
return this._makeChainable(raw as JSONSchema)
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
// ========== Performance Monitoring ==========
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Wrap a Validator instance with performance monitoring.
|
|
157
|
-
*/
|
|
158
|
-
static withPerformance<V extends { validate: (...args: unknown[]) => unknown }>(validator: V): V {
|
|
159
|
-
const originalValidate = validator.validate.bind(validator)
|
|
160
|
-
validator.validate = (...args: unknown[]) => {
|
|
161
|
-
const startTime = Date.now()
|
|
162
|
-
const result = originalValidate(...args) as Record<string, unknown>
|
|
163
|
-
result['performance'] = { duration: Date.now() - startTime, timestamp: new Date().toISOString() }
|
|
164
|
-
return result
|
|
165
|
-
}
|
|
166
|
-
return validator
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Batch validate using a pre-compiled Ajv validate function.
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
if (prop.
|
|
232
|
-
|
|
233
|
-
if (
|
|
234
|
-
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
1
|
+
/**
|
|
2
|
+
* SchemaUtils — Advanced schema operations (reuse, merge, extend, performance monitoring)
|
|
3
|
+
*
|
|
4
|
+
* v2 note: v1's extend/validateBatch used require('../adapters/DslAdapter'),
|
|
5
|
+
* v2 uses dynamic import or accepts pre-compiled schema directly (avoids circular deps)
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { JSONSchema } from '../types/schema.js'
|
|
9
|
+
import { DslAdapter } from '../adapters/DslAdapter.js'
|
|
10
|
+
|
|
11
|
+
// Internal: chainable schema wrapper type
|
|
12
|
+
interface ChainableSchema extends JSONSchema {
|
|
13
|
+
_isChainable: true
|
|
14
|
+
partial(fields?: string[]): ChainableSchema
|
|
15
|
+
pick(fields: string[]): ChainableSchema
|
|
16
|
+
omit(fields: string[]): ChainableSchema
|
|
17
|
+
extend(extensions: Record<string, unknown>): ChainableSchema
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// ==================== SchemaUtils ====================
|
|
21
|
+
|
|
22
|
+
export class SchemaUtils {
|
|
23
|
+
// ========== Schema Reuse ==========
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Create a reusable schema factory.
|
|
27
|
+
* @example const emailField = SchemaUtils.reusable(() => dsl('email!').label('email'))
|
|
28
|
+
*/
|
|
29
|
+
static reusable<T>(factory: () => T): () => T {
|
|
30
|
+
return factory
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Create a schema fragment library.
|
|
35
|
+
* @example const fields = SchemaUtils.createLibrary({ email: () => dsl('email!') })
|
|
36
|
+
*/
|
|
37
|
+
static createLibrary<T extends Record<string, () => unknown>>(fragments: T): T {
|
|
38
|
+
return fragments
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ========== Schema Reuse & Extension ==========
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Extend a schema (like inheritance) — merges extension fields into the base schema.
|
|
45
|
+
*/
|
|
46
|
+
static extend(baseSchema: JSONSchema, extensions: JSONSchema | Record<string, unknown>): ChainableSchema {
|
|
47
|
+
const result: Record<string, unknown> = {
|
|
48
|
+
type: 'object',
|
|
49
|
+
properties: {} as Record<string, unknown>,
|
|
50
|
+
required: [] as string[],
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Copy base schema
|
|
54
|
+
if (baseSchema.properties) {
|
|
55
|
+
result['properties'] = this._mergeProperties(
|
|
56
|
+
result['properties'] as Record<string, unknown>,
|
|
57
|
+
baseSchema.properties as Record<string, unknown>,
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
if (baseSchema.required) {
|
|
61
|
+
result['required'] = [...baseSchema.required]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Detect flat DSL definition: if no 'properties' key but has string values, treat as DSL
|
|
65
|
+
let extSchema: JSONSchema
|
|
66
|
+
if (!('properties' in extensions) && Object.values(extensions).some(v => typeof v === 'string')) {
|
|
67
|
+
extSchema = DslAdapter.parseObject(extensions as Record<string, string>).toSchema()
|
|
68
|
+
} else {
|
|
69
|
+
extSchema = extensions as JSONSchema
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Merge extension schema (deep-merge same-name nested objects instead of replacing)
|
|
73
|
+
if (extSchema.properties) {
|
|
74
|
+
result['properties'] = this._mergeProperties(
|
|
75
|
+
result['properties'] as Record<string, unknown>,
|
|
76
|
+
extSchema.properties as Record<string, unknown>,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
if (extSchema.required) {
|
|
80
|
+
result['required'] = [...new Set([
|
|
81
|
+
...(result['required'] as string[]),
|
|
82
|
+
...extSchema.required,
|
|
83
|
+
])]
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return this._makeChainable(result as JSONSchema)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Pick a subset of fields from a schema.
|
|
91
|
+
*/
|
|
92
|
+
static pick(schema: JSONSchema, fields: string[]): ChainableSchema {
|
|
93
|
+
const result: Record<string, unknown> = {
|
|
94
|
+
type: 'object',
|
|
95
|
+
properties: {} as Record<string, unknown>,
|
|
96
|
+
required: [] as string[],
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
for (const field of fields) {
|
|
100
|
+
if (schema.properties?.[field]) {
|
|
101
|
+
(result['properties'] as Record<string, unknown>)[field] = this._clone(schema.properties[field] as JSONSchema)
|
|
102
|
+
if (schema.required?.includes(field)) {
|
|
103
|
+
(result['required'] as string[]).push(field)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return this._makeChainable(result as JSONSchema)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Omit fields from a schema.
|
|
113
|
+
*/
|
|
114
|
+
static omit(schema: JSONSchema, fields: string[]): ChainableSchema {
|
|
115
|
+
const result = this._clone(schema)
|
|
116
|
+
|
|
117
|
+
for (const field of fields) {
|
|
118
|
+
if (result['properties']) {
|
|
119
|
+
delete (result['properties'] as Record<string, unknown>)[field]
|
|
120
|
+
}
|
|
121
|
+
if (Array.isArray(result['required'])) {
|
|
122
|
+
result['required'] = (result['required'] as string[]).filter((f: string) => f !== field)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Remove empty required array
|
|
127
|
+
if (Array.isArray(result['required']) && (result['required'] as string[]).length === 0) {
|
|
128
|
+
delete result['required']
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return this._makeChainable(result as JSONSchema)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Make all fields optional (removes required).
|
|
136
|
+
* @param fields - optional; only process these fields (others remain unchanged)
|
|
137
|
+
*/
|
|
138
|
+
static partial(schema: JSONSchema, fields?: string[] | null): ChainableSchema {
|
|
139
|
+
let raw: Record<string, unknown>
|
|
140
|
+
|
|
141
|
+
if (fields) {
|
|
142
|
+
const picked = this.pick(schema, fields)
|
|
143
|
+
raw = this._extractSchema(picked)
|
|
144
|
+
} else {
|
|
145
|
+
raw = this._clone(schema)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
this._deleteRequired(raw)
|
|
149
|
+
|
|
150
|
+
return this._makeChainable(raw as JSONSchema)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ========== Performance Monitoring ==========
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Wrap a Validator instance with performance monitoring.
|
|
157
|
+
*/
|
|
158
|
+
static withPerformance<V extends { validate: (...args: unknown[]) => unknown }>(validator: V): V {
|
|
159
|
+
const originalValidate = validator.validate.bind(validator)
|
|
160
|
+
validator.validate = (...args: unknown[]) => {
|
|
161
|
+
const startTime = Date.now()
|
|
162
|
+
const result = originalValidate(...args) as Record<string, unknown>
|
|
163
|
+
result['performance'] = { duration: Date.now() - startTime, timestamp: new Date().toISOString() }
|
|
164
|
+
return result
|
|
165
|
+
}
|
|
166
|
+
return validator
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Batch validate using a pre-compiled Ajv validate function.
|
|
171
|
+
*
|
|
172
|
+
* Note: the schema is compiled once per call but not cached between calls.
|
|
173
|
+
* For repeated batch validation of the same schema, prefer `Validator.validateBatch()`
|
|
174
|
+
* which benefits from the built-in compile cache and returns typed `ValidationResult[]`.
|
|
175
|
+
*/
|
|
176
|
+
static validateBatch(
|
|
177
|
+
schema: JSONSchema,
|
|
178
|
+
dataArray: unknown[],
|
|
179
|
+
ajvInstance: { compile: (schema: JSONSchema) => (data: unknown) => boolean } & { errors?: unknown },
|
|
180
|
+
): {
|
|
181
|
+
results: Array<{ index: number; valid: boolean; errors: unknown; data: unknown }>
|
|
182
|
+
summary: { total: number; valid: number; invalid: number; duration: number; averageTime: number }
|
|
183
|
+
} {
|
|
184
|
+
const startTime = Date.now()
|
|
185
|
+
const compiledValidate = ajvInstance.compile(schema)
|
|
186
|
+
|
|
187
|
+
const results = dataArray.map((data, index) => {
|
|
188
|
+
const valid = compiledValidate(data)
|
|
189
|
+
return {
|
|
190
|
+
index,
|
|
191
|
+
valid,
|
|
192
|
+
errors: valid ? null : (compiledValidate as unknown as { errors: unknown }).errors,
|
|
193
|
+
data: valid ? data : null,
|
|
194
|
+
}
|
|
195
|
+
})
|
|
196
|
+
|
|
197
|
+
const duration = Date.now() - startTime
|
|
198
|
+
return {
|
|
199
|
+
results,
|
|
200
|
+
summary: {
|
|
201
|
+
total: dataArray.length,
|
|
202
|
+
valid: results.filter(r => r.valid).length,
|
|
203
|
+
invalid: results.filter(r => !r.valid).length,
|
|
204
|
+
duration,
|
|
205
|
+
averageTime: dataArray.length > 0 ? duration / dataArray.length : 0,
|
|
206
|
+
},
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// ========== Schema Export ==========
|
|
211
|
+
|
|
212
|
+
static toMarkdown(schema: JSONSchema, options: { title?: string } = {}): string {
|
|
213
|
+
const { title = 'Schema Documentation' } = options
|
|
214
|
+
let md = `# ${title}\n\n`
|
|
215
|
+
|
|
216
|
+
if (schema.properties) {
|
|
217
|
+
md += '## Fields\n\n'
|
|
218
|
+
md += '| Field | Type | Required | Description |\n'
|
|
219
|
+
md += '|-------|------|----------|-------------|\n'
|
|
220
|
+
|
|
221
|
+
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
222
|
+
const required = schema.required?.includes(key) ? '✅' : '❌'
|
|
223
|
+
const type = SchemaUtils._escapeMdCell((prop.type as string) ?? 'any')
|
|
224
|
+
const p = prop as Record<string, unknown>
|
|
225
|
+
const label = SchemaUtils._escapeMdCell((p['_label'] as string) ?? key)
|
|
226
|
+
const escapedKey = SchemaUtils._escapeMdCell(key)
|
|
227
|
+
|
|
228
|
+
md += `| ${escapedKey} | ${type} | ${required} | ${label} |\n`
|
|
229
|
+
|
|
230
|
+
const constraints: string[] = []
|
|
231
|
+
if (prop.minLength) constraints.push(`minLength: ${prop.minLength}`)
|
|
232
|
+
if (prop.maxLength) constraints.push(`maxLength: ${prop.maxLength}`)
|
|
233
|
+
if (prop.minimum !== undefined) constraints.push(`minimum: ${prop.minimum}`)
|
|
234
|
+
if (prop.maximum !== undefined) constraints.push(`maximum: ${prop.maximum}`)
|
|
235
|
+
if (prop.pattern) constraints.push(`pattern: \`${SchemaUtils._escapeMdCell(String(prop.pattern))}\``)
|
|
236
|
+
if (prop.enum) constraints.push(`enum: ${(prop.enum as unknown[]).join(', ')}`)
|
|
237
|
+
|
|
238
|
+
if (constraints.length > 0) {
|
|
239
|
+
md += `| | | | ${SchemaUtils._escapeMdCell(constraints.join('; '))} |\n`
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return md
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
static clone(schema: JSONSchema): JSONSchema {
|
|
248
|
+
return JSON.parse(JSON.stringify(schema)) as JSONSchema
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* toHTML — v1 compat: export schema as HTML document
|
|
253
|
+
*/
|
|
254
|
+
static toHTML(schema: JSONSchema, options: { title?: string } = {}): string {
|
|
255
|
+
const { title = 'Schema Documentation' } = options
|
|
256
|
+
const safeTitle = SchemaUtils._escapeHtml(title)
|
|
257
|
+
let html = `<!DOCTYPE html>\n<html>\n<head><meta charset="utf-8"><title>${safeTitle}</title></head>\n<body>\n<h1>${safeTitle}</h1>\n`
|
|
258
|
+
|
|
259
|
+
if (schema.properties) {
|
|
260
|
+
html += '<table border="1" cellpadding="4">\n'
|
|
261
|
+
html += '<tr><th>Field</th><th>Type</th><th>Required</th><th>Description</th></tr>\n'
|
|
262
|
+
|
|
263
|
+
for (const [key, prop] of Object.entries(schema.properties)) {
|
|
264
|
+
const required = schema.required?.includes(key) ? '✅' : '❌'
|
|
265
|
+
const type = SchemaUtils._escapeHtml((prop.type as string) ?? 'any')
|
|
266
|
+
const p = prop as Record<string, unknown>
|
|
267
|
+
const label = SchemaUtils._escapeHtml((p['_label'] as string) ?? key)
|
|
268
|
+
|
|
269
|
+
html += `<tr><td>${SchemaUtils._escapeHtml(key)}</td><td>${type}</td><td>${required}</td><td>${label}</td></tr>\n`
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
html += '</table>\n'
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
html += '</body>\n</html>'
|
|
276
|
+
return html
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ==================== Private Utilities ====================
|
|
280
|
+
|
|
281
|
+
private static _escapeMdCell(str: string): string {
|
|
282
|
+
return str.replace(/\|/g, '\\|').replace(/\r\n|\r|\n/g, '<br>')
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private static _escapeHtml(str: string): string {
|
|
286
|
+
return str
|
|
287
|
+
.replace(/&/g, '&')
|
|
288
|
+
.replace(/</g, '<')
|
|
289
|
+
.replace(/>/g, '>')
|
|
290
|
+
.replace(/"/g, '"')
|
|
291
|
+
.replace(/'/g, ''')
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private static _mergeProperties(
|
|
295
|
+
base: Record<string, unknown>,
|
|
296
|
+
ext: Record<string, unknown>,
|
|
297
|
+
): Record<string, unknown> {
|
|
298
|
+
const result = { ...base }
|
|
299
|
+
for (const [key, extVal] of Object.entries(ext)) {
|
|
300
|
+
const baseVal = result[key]
|
|
301
|
+
if (
|
|
302
|
+
baseVal && extVal &&
|
|
303
|
+
typeof baseVal === 'object' && typeof extVal === 'object' &&
|
|
304
|
+
!Array.isArray(baseVal) && !Array.isArray(extVal)
|
|
305
|
+
) {
|
|
306
|
+
result[key] = SchemaUtils._mergeProperties(
|
|
307
|
+
baseVal as Record<string, unknown>,
|
|
308
|
+
extVal as Record<string, unknown>,
|
|
309
|
+
)
|
|
310
|
+
} else {
|
|
311
|
+
result[key] = extVal
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return result
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private static _deleteRequired(obj: Record<string, unknown>): void {
|
|
318
|
+
delete obj['required']
|
|
319
|
+
const props = obj['properties']
|
|
320
|
+
if (props && typeof props === 'object') {
|
|
321
|
+
for (const prop of Object.values(props as Record<string, unknown>)) {
|
|
322
|
+
if (prop && typeof prop === 'object') {
|
|
323
|
+
this._deleteRequired(prop as Record<string, unknown>)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private static _clone(schema: JSONSchema | ChainableSchema): Record<string, unknown> {
|
|
330
|
+
const raw = '_isChainable' in schema ? this._extractSchema(schema as ChainableSchema) : schema
|
|
331
|
+
return JSON.parse(JSON.stringify(raw)) as Record<string, unknown>
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
private static _makeChainable(schema: JSONSchema): ChainableSchema {
|
|
335
|
+
const chainable = Object.assign({}, schema) as Record<string, unknown>
|
|
336
|
+
|
|
337
|
+
Object.defineProperty(chainable, '_isChainable', {
|
|
338
|
+
value: true, enumerable: false, configurable: false,
|
|
339
|
+
})
|
|
340
|
+
|
|
341
|
+
const methods = ['partial', 'pick', 'omit', 'extend'] as const
|
|
342
|
+
for (const method of methods) {
|
|
343
|
+
Object.defineProperty(chainable, method, {
|
|
344
|
+
value: (...args: unknown[]) => {
|
|
345
|
+
const rawSchema = SchemaUtils._extractSchema(chainable as ChainableSchema)
|
|
346
|
+
return (SchemaUtils[method] as (...args: unknown[]) => unknown)(rawSchema, ...args)
|
|
347
|
+
},
|
|
348
|
+
enumerable: false,
|
|
349
|
+
configurable: false,
|
|
350
|
+
})
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return chainable as ChainableSchema
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private static _extractSchema(chainable: ChainableSchema | Record<string, unknown>): Record<string, unknown> {
|
|
357
|
+
const schema: Record<string, unknown> = {}
|
|
358
|
+
for (const key of Object.keys(chainable)) {
|
|
359
|
+
if (key !== '_isChainable') {
|
|
360
|
+
schema[key] = chainable[key]
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return schema
|
|
364
|
+
}
|
|
365
|
+
}
|