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.
Files changed (145) hide show
  1. package/CHANGELOG.md +130 -113
  2. package/LICENSE +21 -21
  3. package/README.md +628 -628
  4. package/dist/{DslBuilder-DkLaOo9Q.d.ts → DslBuilder-BIgQOAXp.d.ts} +2 -0
  5. package/dist/{DslBuilder-DQDN0ZxZ.d.cts → DslBuilder-CjHTucNQ.d.cts} +2 -0
  6. package/dist/{Validator-hFWKGxir.d.ts → Validator-CllRdrY0.d.ts} +1 -1
  7. package/dist/{Validator-C7GsVQOH.d.cts → Validator-D6okG9tr.d.cts} +1 -1
  8. package/dist/index.cjs +75 -29
  9. package/dist/index.d.cts +10 -4
  10. package/dist/index.d.ts +10 -4
  11. package/dist/index.js +75 -29
  12. package/dist/plugins/custom-format.cjs +33 -17
  13. package/dist/plugins/custom-format.d.cts +1 -1
  14. package/dist/plugins/custom-format.d.ts +1 -1
  15. package/dist/plugins/custom-format.js +33 -17
  16. package/dist/plugins/custom-type-example.cjs +33 -17
  17. package/dist/plugins/custom-type-example.d.cts +1 -1
  18. package/dist/plugins/custom-type-example.d.ts +1 -1
  19. package/dist/plugins/custom-type-example.js +33 -17
  20. package/dist/plugins/custom-validator.cjs +0 -2
  21. package/dist/plugins/custom-validator.d.cts +1 -1
  22. package/dist/plugins/custom-validator.d.ts +1 -1
  23. package/dist/plugins/custom-validator.js +0 -2
  24. package/docs/FEATURE-INDEX.md +553 -553
  25. package/docs/add-custom-locale.md +496 -496
  26. package/docs/add-keyword.md +24 -24
  27. package/docs/api-reference.md +1047 -1047
  28. package/docs/api.md +13 -13
  29. package/docs/best-practices-project-structure.md +417 -417
  30. package/docs/best-practices.md +712 -712
  31. package/docs/cache-manager.md +344 -344
  32. package/docs/compile.md +45 -45
  33. package/docs/conditional-api.md +1307 -1307
  34. package/docs/custom-extensions-guide.md +339 -339
  35. package/docs/design-philosophy.md +606 -606
  36. package/docs/doc-index.md +324 -324
  37. package/docs/dsl-syntax.md +714 -714
  38. package/docs/dynamic-locale.md +608 -608
  39. package/docs/enum.md +482 -482
  40. package/docs/error-handling.md +1975 -1975
  41. package/docs/export-guide.md +501 -501
  42. package/docs/export-limitations.md +567 -567
  43. package/docs/faq.md +596 -596
  44. package/docs/frontend-i18n-guide.md +307 -307
  45. package/docs/i18n-user-guide.md +487 -487
  46. package/docs/i18n.md +476 -476
  47. package/docs/index.md +48 -48
  48. package/docs/json-schema-basics.md +40 -40
  49. package/docs/label-vs-description.md +271 -271
  50. package/docs/markdown-exporter.md +406 -406
  51. package/docs/mongodb-exporter.md +302 -302
  52. package/docs/multi-language.md +26 -26
  53. package/docs/multi-type-support.md +322 -322
  54. package/docs/mysql-exporter.md +280 -280
  55. package/docs/number-operators.md +449 -449
  56. package/docs/optional-marker-guide.md +326 -326
  57. package/docs/performance-guide.md +49 -49
  58. package/docs/plugin-system.md +381 -381
  59. package/docs/plugin-type-registration.md +34 -34
  60. package/docs/postgresql-exporter.md +311 -311
  61. package/docs/public/favicon.svg +4 -4
  62. package/docs/quick-start.md +435 -435
  63. package/docs/runtime-locale-support.md +532 -532
  64. package/docs/schema-helper.md +345 -345
  65. package/docs/schema-utils-advanced-issues.md +23 -23
  66. package/docs/schema-utils-best-practices.md +20 -20
  67. package/docs/schema-utils-chaining.md +150 -150
  68. package/docs/schema-utils.md +524 -524
  69. package/docs/security-checklist.md +20 -20
  70. package/docs/string-extensions.md +488 -488
  71. package/docs/troubleshooting.md +486 -486
  72. package/docs/type-converter.md +310 -310
  73. package/docs/type-reference.md +242 -242
  74. package/docs/typescript-guide.md +584 -584
  75. package/docs/union-type-guide.md +157 -157
  76. package/docs/union-types.md +284 -284
  77. package/docs/validate-async.md +491 -491
  78. package/docs/validate-batch.md +49 -49
  79. package/docs/validate-dsl-object-support.md +578 -578
  80. package/docs/validate.md +506 -506
  81. package/docs/validation-guide.md +502 -502
  82. package/docs/validator.md +39 -39
  83. package/package.json +131 -131
  84. package/plugins/custom-format.cjs +8 -8
  85. package/plugins/custom-type-example.cjs +8 -8
  86. package/plugins/custom-validator.cjs +8 -8
  87. package/src/adapters/DslAdapter.ts +111 -111
  88. package/src/adapters/index.ts +1 -1
  89. package/src/config/constants.ts +83 -83
  90. package/src/config/index.ts +2 -2
  91. package/src/config/patterns.ts +77 -77
  92. package/src/core/CacheManager.ts +169 -159
  93. package/src/core/ConditionalBuilder.ts +382 -382
  94. package/src/core/ConditionalRuntime.ts +27 -27
  95. package/src/core/ConditionalValidator.ts +254 -254
  96. package/src/core/DslBuilder.ts +687 -677
  97. package/src/core/ErrorCodes.ts +38 -38
  98. package/src/core/ErrorFormatter.ts +271 -271
  99. package/src/core/JSONSchemaCore.ts +65 -65
  100. package/src/core/Locale.ts +187 -187
  101. package/src/core/MessageTemplate.ts +42 -42
  102. package/src/core/ObjectDslBuilder.ts +64 -64
  103. package/src/core/PluginManager.ts +326 -326
  104. package/src/core/StringExtensions.ts +140 -140
  105. package/src/core/TemplateEngine.ts +44 -44
  106. package/src/core/Validator.ts +448 -448
  107. package/src/errors/I18nError.ts +159 -159
  108. package/src/errors/ValidationError.ts +105 -105
  109. package/src/exporters/BaseExporter.ts +60 -60
  110. package/src/exporters/MarkdownExporter.ts +305 -305
  111. package/src/exporters/MongoDBExporter.ts +126 -126
  112. package/src/exporters/MySQLExporter.ts +156 -155
  113. package/src/exporters/PostgreSQLExporter.ts +222 -222
  114. package/src/exporters/index.ts +18 -18
  115. package/src/index.ts +651 -633
  116. package/src/locales/en-US.ts +160 -160
  117. package/src/locales/es-ES.ts +160 -160
  118. package/src/locales/fr-FR.ts +160 -160
  119. package/src/locales/index.ts +103 -103
  120. package/src/locales/ja-JP.ts +160 -160
  121. package/src/locales/types.ts +156 -156
  122. package/src/locales/zh-CN.ts +160 -160
  123. package/src/parser/ConstraintParser.ts +101 -101
  124. package/src/parser/DslParser.ts +470 -470
  125. package/src/parser/SchemaCompiler.ts +66 -66
  126. package/src/parser/TypeRegistry.ts +250 -250
  127. package/src/parser/index.ts +6 -6
  128. package/src/plugins/custom-format.ts +124 -126
  129. package/src/plugins/custom-type-example.ts +106 -108
  130. package/src/plugins/custom-validator.ts +138 -140
  131. package/src/types/conditional.ts +28 -28
  132. package/src/types/config.ts +59 -59
  133. package/src/types/dsl.ts +131 -131
  134. package/src/types/error.ts +60 -60
  135. package/src/types/index.ts +17 -17
  136. package/src/types/infer.ts +127 -127
  137. package/src/types/plugin.ts +58 -58
  138. package/src/types/safe-regex.d.ts +9 -9
  139. package/src/types/schema.ts +66 -66
  140. package/src/types/validate.ts +71 -71
  141. package/src/utils/SchemaHelper.ts +196 -196
  142. package/src/utils/SchemaUtils.ts +365 -346
  143. package/src/utils/TypeConverter.ts +215 -215
  144. package/src/utils/index.ts +10 -10
  145. package/src/validators/CustomKeywords.ts +477 -477
@@ -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
- static validateBatch(
173
- schema: JSONSchema,
174
- dataArray: unknown[],
175
- ajvInstance: { compile: (schema: JSONSchema) => (data: unknown) => boolean } & { errors?: unknown },
176
- ): {
177
- results: Array<{ index: number; valid: boolean; errors: unknown; data: unknown }>
178
- summary: { total: number; valid: number; invalid: number; duration: number; averageTime: number }
179
- } {
180
- const startTime = Date.now()
181
- const compiledValidate = ajvInstance.compile(schema)
182
-
183
- const results = dataArray.map((data, index) => {
184
- const valid = compiledValidate(data)
185
- return {
186
- index,
187
- valid,
188
- errors: valid ? null : (compiledValidate as unknown as { errors: unknown }).errors,
189
- data: valid ? data : null,
190
- }
191
- })
192
-
193
- const duration = Date.now() - startTime
194
- return {
195
- results,
196
- summary: {
197
- total: dataArray.length,
198
- valid: results.filter(r => r.valid).length,
199
- invalid: results.filter(r => !r.valid).length,
200
- duration,
201
- averageTime: dataArray.length > 0 ? duration / dataArray.length : 0,
202
- },
203
- }
204
- }
205
-
206
- // ========== Schema Export ==========
207
-
208
- static toMarkdown(schema: JSONSchema, options: { title?: string } = {}): string {
209
- const { title = 'Schema Documentation' } = options
210
- let md = `# ${title}\n\n`
211
-
212
- if (schema.properties) {
213
- md += '## Fields\n\n'
214
- md += '| Field | Type | Required | Description |\n'
215
- md += '|-------|------|----------|-------------|\n'
216
-
217
- for (const [key, prop] of Object.entries(schema.properties)) {
218
- const required = schema.required?.includes(key) ? '✅' : '❌'
219
- const type = (prop.type as string) ?? 'any'
220
- const p = prop as Record<string, unknown>
221
- const label = (p['_label'] as string) ?? key
222
-
223
- md += `| ${key} | ${type} | ${required} | ${label} |\n`
224
-
225
- const constraints: string[] = []
226
- if (prop.minLength) constraints.push(`minLength: ${prop.minLength}`)
227
- if (prop.maxLength) constraints.push(`maxLength: ${prop.maxLength}`)
228
- if (prop.minimum !== undefined) constraints.push(`minimum: ${prop.minimum}`)
229
- if (prop.maximum !== undefined) constraints.push(`maximum: ${prop.maximum}`)
230
- if (prop.pattern) constraints.push(`pattern: \`${prop.pattern}\``)
231
- if (prop.enum) constraints.push(`enum: ${(prop.enum as unknown[]).join(', ')}`)
232
-
233
- if (constraints.length > 0) {
234
- md += `| | | | ${constraints.join('; ')} |\n`
235
- }
236
- }
237
- }
238
-
239
- return md
240
- }
241
-
242
- static clone(schema: JSONSchema): JSONSchema {
243
- return JSON.parse(JSON.stringify(schema)) as JSONSchema
244
- }
245
-
246
- /**
247
- * toHTML — v1 compat: export schema as HTML document
248
- */
249
- static toHTML(schema: JSONSchema, options: { title?: string } = {}): string {
250
- const { title = 'Schema Documentation' } = options
251
- let html = `<!DOCTYPE html>\n<html>\n<head><meta charset="utf-8"><title>${title}</title></head>\n<body>\n<h1>${title}</h1>\n`
252
-
253
- if (schema.properties) {
254
- html += '<table border="1" cellpadding="4">\n'
255
- html += '<tr><th>Field</th><th>Type</th><th>Required</th><th>Description</th></tr>\n'
256
-
257
- for (const [key, prop] of Object.entries(schema.properties)) {
258
- const required = schema.required?.includes(key) ? '✅' : '❌'
259
- const type = (prop.type as string) ?? 'any'
260
- const p = prop as Record<string, unknown>
261
- const label = (p['_label'] as string) ?? key
262
-
263
- html += `<tr><td>${key}</td><td>${type}</td><td>${required}</td><td>${label}</td></tr>\n`
264
- }
265
-
266
- html += '</table>\n'
267
- }
268
-
269
- html += '</body>\n</html>'
270
- return html
271
- }
272
-
273
- // ==================== Private Utilities ====================
274
-
275
- private static _mergeProperties(
276
- base: Record<string, unknown>,
277
- ext: Record<string, unknown>,
278
- ): Record<string, unknown> {
279
- const result = { ...base }
280
- for (const [key, extVal] of Object.entries(ext)) {
281
- const baseVal = result[key]
282
- if (
283
- baseVal && extVal &&
284
- typeof baseVal === 'object' && typeof extVal === 'object' &&
285
- !Array.isArray(baseVal) && !Array.isArray(extVal)
286
- ) {
287
- result[key] = SchemaUtils._mergeProperties(
288
- baseVal as Record<string, unknown>,
289
- extVal as Record<string, unknown>,
290
- )
291
- } else {
292
- result[key] = extVal
293
- }
294
- }
295
- return result
296
- }
297
-
298
- private static _deleteRequired(obj: Record<string, unknown>): void {
299
- delete obj['required']
300
- const props = obj['properties']
301
- if (props && typeof props === 'object') {
302
- for (const prop of Object.values(props as Record<string, unknown>)) {
303
- if (prop && typeof prop === 'object') {
304
- this._deleteRequired(prop as Record<string, unknown>)
305
- }
306
- }
307
- }
308
- }
309
-
310
- private static _clone(schema: JSONSchema | ChainableSchema): Record<string, unknown> {
311
- const raw = '_isChainable' in schema ? this._extractSchema(schema as ChainableSchema) : schema
312
- return JSON.parse(JSON.stringify(raw)) as Record<string, unknown>
313
- }
314
-
315
- private static _makeChainable(schema: JSONSchema): ChainableSchema {
316
- const chainable = Object.assign({}, schema) as Record<string, unknown>
317
-
318
- Object.defineProperty(chainable, '_isChainable', {
319
- value: true, enumerable: false, configurable: false,
320
- })
321
-
322
- const methods = ['partial', 'pick', 'omit', 'extend'] as const
323
- for (const method of methods) {
324
- Object.defineProperty(chainable, method, {
325
- value: (...args: unknown[]) => {
326
- const rawSchema = SchemaUtils._extractSchema(chainable as ChainableSchema)
327
- return (SchemaUtils[method] as (...args: unknown[]) => unknown)(rawSchema, ...args)
328
- },
329
- enumerable: false,
330
- configurable: false,
331
- })
332
- }
333
-
334
- return chainable as ChainableSchema
335
- }
336
-
337
- private static _extractSchema(chainable: ChainableSchema | Record<string, unknown>): Record<string, unknown> {
338
- const schema: Record<string, unknown> = {}
339
- for (const key of Object.keys(chainable)) {
340
- if (key !== '_isChainable') {
341
- schema[key] = chainable[key]
342
- }
343
- }
344
- return schema
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, '&amp;')
288
+ .replace(/</g, '&lt;')
289
+ .replace(/>/g, '&gt;')
290
+ .replace(/"/g, '&quot;')
291
+ .replace(/'/g, '&#x27;')
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
+ }