schema-dsl 1.2.5 → 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 (243) hide show
  1. package/CHANGELOG.md +130 -238
  2. package/LICENSE +21 -21
  3. package/README.md +628 -2486
  4. package/dist/DslBuilder-BIgQOAXp.d.ts +343 -0
  5. package/dist/DslBuilder-CjHTucNQ.d.cts +343 -0
  6. package/dist/Validator-CllRdrY0.d.ts +192 -0
  7. package/dist/Validator-D6okG9tr.d.cts +192 -0
  8. package/dist/index.cjs +6640 -0
  9. package/dist/index.d.cts +1151 -0
  10. package/dist/index.d.ts +1151 -0
  11. package/dist/index.js +6574 -0
  12. package/dist/plugin-CIKtTMtS.d.cts +246 -0
  13. package/dist/plugin-CIKtTMtS.d.ts +246 -0
  14. package/dist/plugins/custom-format.cjs +3818 -0
  15. package/dist/plugins/custom-format.d.cts +12 -0
  16. package/dist/plugins/custom-format.d.ts +12 -0
  17. package/dist/plugins/custom-format.js +3788 -0
  18. package/dist/plugins/custom-type-example.cjs +3811 -0
  19. package/dist/plugins/custom-type-example.d.cts +8 -0
  20. package/dist/plugins/custom-type-example.d.ts +8 -0
  21. package/dist/plugins/custom-type-example.js +3781 -0
  22. package/dist/plugins/custom-validator.cjs +144 -0
  23. package/dist/plugins/custom-validator.d.cts +10 -0
  24. package/dist/plugins/custom-validator.d.ts +10 -0
  25. package/dist/plugins/custom-validator.js +119 -0
  26. package/docs/FEATURE-INDEX.md +553 -519
  27. package/docs/add-custom-locale.md +496 -483
  28. package/docs/add-keyword.md +24 -0
  29. package/docs/api-reference.md +1047 -805
  30. package/docs/api.md +13 -0
  31. package/docs/best-practices-project-structure.md +417 -408
  32. package/docs/best-practices.md +712 -672
  33. package/docs/cache-manager.md +344 -336
  34. package/docs/compile.md +45 -0
  35. package/docs/conditional-api.md +1307 -1278
  36. package/docs/custom-extensions-guide.md +339 -411
  37. package/docs/design-philosophy.md +606 -601
  38. package/docs/doc-index.md +324 -0
  39. package/docs/dsl-syntax.md +714 -664
  40. package/docs/dynamic-locale.md +608 -598
  41. package/docs/enum.md +482 -475
  42. package/docs/error-handling.md +1975 -1966
  43. package/docs/export-guide.md +501 -462
  44. package/docs/export-limitations.md +567 -551
  45. package/docs/faq.md +596 -577
  46. package/docs/frontend-i18n-guide.md +307 -293
  47. package/docs/i18n-user-guide.md +487 -474
  48. package/docs/i18n.md +476 -457
  49. package/docs/index.md +48 -0
  50. package/docs/json-schema-basics.md +40 -0
  51. package/docs/label-vs-description.md +271 -262
  52. package/docs/markdown-exporter.md +406 -397
  53. package/docs/mongodb-exporter.md +302 -295
  54. package/docs/multi-language.md +26 -0
  55. package/docs/multi-type-support.md +322 -329
  56. package/docs/mysql-exporter.md +280 -273
  57. package/docs/number-operators.md +449 -442
  58. package/docs/optional-marker-guide.md +326 -321
  59. package/docs/performance-guide.md +49 -0
  60. package/docs/plugin-system.md +381 -542
  61. package/docs/plugin-type-registration.md +34 -0
  62. package/docs/postgresql-exporter.md +311 -304
  63. package/docs/public/favicon.svg +5 -0
  64. package/docs/quick-start.md +435 -761
  65. package/docs/runtime-locale-support.md +532 -521
  66. package/docs/schema-helper.md +345 -340
  67. package/docs/schema-utils-advanced-issues.md +23 -0
  68. package/docs/schema-utils-best-practices.md +20 -0
  69. package/docs/schema-utils-chaining.md +150 -143
  70. package/docs/schema-utils.md +524 -490
  71. package/docs/security-checklist.md +20 -0
  72. package/docs/string-extensions.md +488 -480
  73. package/docs/troubleshooting.md +486 -471
  74. package/docs/type-converter.md +310 -319
  75. package/docs/type-reference.md +242 -219
  76. package/docs/typescript-guide.md +584 -573
  77. package/docs/union-type-guide.md +157 -147
  78. package/docs/union-types.md +284 -277
  79. package/docs/validate-async.md +491 -480
  80. package/docs/validate-batch.md +49 -0
  81. package/docs/validate-dsl-object-support.md +578 -573
  82. package/docs/validate.md +506 -486
  83. package/docs/validation-guide.md +502 -484
  84. package/docs/validator.md +39 -0
  85. package/package.json +131 -73
  86. package/plugins/custom-format.cjs +8 -0
  87. package/plugins/custom-type-example.cjs +8 -0
  88. package/plugins/custom-validator.cjs +8 -0
  89. package/src/adapters/DslAdapter.ts +111 -0
  90. package/src/adapters/index.ts +1 -0
  91. package/src/config/constants.ts +83 -0
  92. package/src/config/index.ts +2 -0
  93. package/src/config/patterns.ts +77 -0
  94. package/src/core/CacheManager.ts +169 -0
  95. package/src/core/ConditionalBuilder.ts +382 -0
  96. package/src/core/ConditionalRuntime.ts +28 -0
  97. package/src/core/ConditionalValidator.ts +255 -0
  98. package/src/core/DslBuilder.ts +687 -0
  99. package/src/core/ErrorCodes.ts +38 -0
  100. package/src/core/ErrorFormatter.ts +271 -0
  101. package/src/core/JSONSchemaCore.ts +65 -0
  102. package/src/core/Locale.ts +187 -0
  103. package/src/core/MessageTemplate.ts +42 -0
  104. package/src/core/ObjectDslBuilder.ts +64 -0
  105. package/src/core/PluginManager.ts +326 -0
  106. package/src/core/StringExtensions.ts +140 -0
  107. package/src/core/TemplateEngine.ts +44 -0
  108. package/src/core/Validator.ts +448 -0
  109. package/src/errors/I18nError.ts +159 -0
  110. package/src/errors/ValidationError.ts +105 -0
  111. package/src/exporters/BaseExporter.ts +60 -0
  112. package/src/exporters/MarkdownExporter.ts +305 -0
  113. package/src/exporters/MongoDBExporter.ts +126 -0
  114. package/src/exporters/MySQLExporter.ts +156 -0
  115. package/src/exporters/PostgreSQLExporter.ts +222 -0
  116. package/src/exporters/index.ts +18 -0
  117. package/src/index.ts +651 -0
  118. package/{lib/locales/en-US.js → src/locales/en-US.ts} +160 -176
  119. package/{lib/locales/es-ES.js → src/locales/es-ES.ts} +160 -113
  120. package/{lib/locales/fr-FR.js → src/locales/fr-FR.ts} +160 -113
  121. package/src/locales/index.ts +103 -0
  122. package/{lib/locales/ja-JP.js → src/locales/ja-JP.ts} +160 -118
  123. package/src/locales/types.ts +156 -0
  124. package/{lib/locales/zh-CN.js → src/locales/zh-CN.ts} +160 -177
  125. package/src/parser/ConstraintParser.ts +101 -0
  126. package/src/parser/DslParser.ts +470 -0
  127. package/src/parser/SchemaCompiler.ts +66 -0
  128. package/src/parser/TypeRegistry.ts +250 -0
  129. package/src/parser/index.ts +6 -0
  130. package/src/plugins/custom-format.ts +124 -0
  131. package/src/plugins/custom-type-example.ts +106 -0
  132. package/src/plugins/custom-validator.ts +138 -0
  133. package/src/types/conditional.ts +28 -0
  134. package/src/types/config.ts +59 -0
  135. package/src/types/dsl.ts +131 -0
  136. package/src/types/error.ts +60 -0
  137. package/src/types/index.ts +17 -0
  138. package/src/types/infer.ts +128 -0
  139. package/src/types/plugin.ts +58 -0
  140. package/src/types/safe-regex.d.ts +9 -0
  141. package/src/types/schema.ts +66 -0
  142. package/src/types/validate.ts +71 -0
  143. package/src/utils/SchemaHelper.ts +196 -0
  144. package/src/utils/SchemaUtils.ts +365 -0
  145. package/src/utils/TypeConverter.ts +215 -0
  146. package/src/utils/index.ts +10 -0
  147. package/src/validators/CustomKeywords.ts +477 -0
  148. package/.eslintignore +0 -11
  149. package/.eslintrc.json +0 -27
  150. package/CONTRIBUTING.md +0 -368
  151. package/STATUS.md +0 -491
  152. package/changelogs/v1.0.0.md +0 -328
  153. package/changelogs/v1.0.9.md +0 -367
  154. package/changelogs/v1.1.0.md +0 -389
  155. package/changelogs/v1.1.1.md +0 -308
  156. package/changelogs/v1.1.2.md +0 -183
  157. package/changelogs/v1.1.3.md +0 -161
  158. package/changelogs/v1.1.4.md +0 -432
  159. package/changelogs/v1.1.5.md +0 -493
  160. package/changelogs/v1.1.6.md +0 -211
  161. package/changelogs/v1.1.8.md +0 -376
  162. package/changelogs/v1.2.3.md +0 -124
  163. package/docs/INDEX.md +0 -252
  164. package/docs/issues-resolved-summary.md +0 -196
  165. package/docs/performance-benchmark-report.md +0 -179
  166. package/docs/performance-quick-reference.md +0 -123
  167. package/docs/user-questions-answered.md +0 -353
  168. package/docs/validation-rules-v1.0.2.md +0 -1608
  169. package/examples/README.md +0 -81
  170. package/examples/array-dsl-example.js +0 -227
  171. package/examples/conditional-example.js +0 -288
  172. package/examples/conditional-non-object.js +0 -129
  173. package/examples/conditional-validate-example.js +0 -321
  174. package/examples/custom-extension.js +0 -85
  175. package/examples/dsl-match-example.js +0 -74
  176. package/examples/dsl-style.js +0 -118
  177. package/examples/dynamic-locale-configuration.js +0 -348
  178. package/examples/dynamic-locale-example.js +0 -287
  179. package/examples/enum.examples.js +0 -324
  180. package/examples/export-demo.js +0 -130
  181. package/examples/express-integration.js +0 -376
  182. package/examples/i18n-error-handling-complete.js +0 -381
  183. package/examples/i18n-error-handling-quickstart.md +0 -0
  184. package/examples/i18n-error.examples.js +0 -181
  185. package/examples/i18n-full-demo.js +0 -301
  186. package/examples/i18n-memory-safety.examples.js +0 -268
  187. package/examples/markdown-export.js +0 -71
  188. package/examples/middleware-usage.js +0 -93
  189. package/examples/new-features-comparison.js +0 -315
  190. package/examples/password-reset/README.md +0 -153
  191. package/examples/password-reset/schema.js +0 -26
  192. package/examples/password-reset/test.js +0 -101
  193. package/examples/plugin-system.examples.js +0 -205
  194. package/examples/schema-utils-chaining.examples.js +0 -250
  195. package/examples/simple-example.js +0 -122
  196. package/examples/slug.examples.js +0 -179
  197. package/examples/string-extensions.js +0 -297
  198. package/examples/union-type-example.js +0 -127
  199. package/examples/union-types-example.js +0 -77
  200. package/examples/user-registration/README.md +0 -156
  201. package/examples/user-registration/routes.js +0 -92
  202. package/examples/user-registration/schema.js +0 -150
  203. package/examples/user-registration/server.js +0 -74
  204. package/index.d.ts +0 -3658
  205. package/index.js +0 -475
  206. package/index.mjs +0 -60
  207. package/lib/adapters/DslAdapter.js +0 -995
  208. package/lib/adapters/index.js +0 -20
  209. package/lib/config/constants.js +0 -286
  210. package/lib/config/patterns/common.js +0 -47
  211. package/lib/config/patterns/creditCard.js +0 -9
  212. package/lib/config/patterns/idCard.js +0 -9
  213. package/lib/config/patterns/index.js +0 -9
  214. package/lib/config/patterns/licensePlate.js +0 -4
  215. package/lib/config/patterns/passport.js +0 -4
  216. package/lib/config/patterns/phone.js +0 -9
  217. package/lib/config/patterns/postalCode.js +0 -5
  218. package/lib/core/CacheManager.js +0 -376
  219. package/lib/core/ConditionalBuilder.js +0 -503
  220. package/lib/core/DslBuilder.js +0 -1589
  221. package/lib/core/ErrorCodes.js +0 -233
  222. package/lib/core/ErrorFormatter.js +0 -445
  223. package/lib/core/JSONSchemaCore.js +0 -347
  224. package/lib/core/Locale.js +0 -130
  225. package/lib/core/MessageTemplate.js +0 -98
  226. package/lib/core/PluginManager.js +0 -448
  227. package/lib/core/StringExtensions.js +0 -240
  228. package/lib/core/Validator.js +0 -654
  229. package/lib/errors/I18nError.js +0 -328
  230. package/lib/errors/ValidationError.js +0 -191
  231. package/lib/exporters/MarkdownExporter.js +0 -420
  232. package/lib/exporters/MongoDBExporter.js +0 -162
  233. package/lib/exporters/MySQLExporter.js +0 -212
  234. package/lib/exporters/PostgreSQLExporter.js +0 -289
  235. package/lib/exporters/index.js +0 -24
  236. package/lib/locales/index.js +0 -8
  237. package/lib/utils/LRUCache.js +0 -174
  238. package/lib/utils/SchemaHelper.js +0 -240
  239. package/lib/utils/SchemaUtils.js +0 -445
  240. package/lib/utils/TypeConverter.js +0 -245
  241. package/lib/utils/index.js +0 -13
  242. package/lib/validators/CustomKeywords.js +0 -616
  243. package/lib/validators/index.js +0 -11
@@ -1,805 +1,1047 @@
1
- # schema-dsl API 参考文档
2
-
3
-
4
- > **更新时间**: 2025-12-25
5
-
6
- ---
7
-
8
- ## 📑 目录
9
-
10
- - [dsl() 函数](#dsl-函数)
11
- - [DslBuilder 类](#dslbuilder-类)
12
- - [String 扩展](#string-扩展)
13
- - [Validator 类](#validator-类)
14
- - [导出器](#导出器)
15
- - [工具函数](#工具函数)
16
-
17
- ---
18
-
19
- ## dsl() 函数
20
-
21
- ### 描述
22
-
23
- DSL 主入口函数,支持字符串和对象两种定义方式。
24
-
25
- ### 语法
26
-
27
- ```javascript
28
- dsl(definition: string | object): DslBuilder | JSONSchema
29
- ```
30
-
31
- ### 参数
32
-
33
- - `definition` (**string** | **object**) - DSL定义
34
- - 字符串:返回 DslBuilder 实例(可链式调用)
35
- - 对象:返回 JSON Schema 对象
36
-
37
- ### 返回值
38
-
39
- - **DslBuilder** - 当参数为字符串时
40
- - **Object** - 当参数为对象时(JSON Schema)
41
-
42
- ### 示例
43
-
44
- ```javascript
45
- // 字符串:返回 DslBuilder
46
- const builder = dsl('email!');
47
- builder.pattern(/custom/).label('邮箱');
48
-
49
- // 对象:返回 JSON Schema
50
- const schema = dsl({
51
- username: 'string:3-32!',
52
- email: 'email!'
53
- });
54
- ```
55
-
56
- ---
57
-
58
- ## DslBuilder 类
59
-
60
- ### 描述
61
-
62
- Schema 构建器类,支持链式调用添加验证规则。
63
-
64
- ### 构造函数
65
-
66
- ```javascript
67
- new DslBuilder(dslString: string)
68
- ```
69
-
70
- **参数**:
71
- - `dslString` (**string**) - DSL字符串,如 `'string:3-32!'`
72
-
73
- ### 方法
74
-
75
- #### `.pattern(regex, message?)`
76
-
77
- 添加正则表达式验证。
78
-
79
- **参数**:
80
- - `regex` (**RegExp** | **string**) - 正则表达式
81
- - `message` (**string**, 可选) - 自定义错误消息
82
-
83
- **返回**: **DslBuilder**
84
-
85
- **示例**:
86
- ```javascript
87
- dsl('string:3-32!')
88
- .pattern(/^[a-zA-Z0-9_]+$/, '只能包含字母、数字和下划线')
89
- ```
90
-
91
- ---
92
-
93
- #### `.label(text)`
94
-
95
- 设置字段标签(用于错误消息)。
96
-
97
- **参数**:
98
- - `text` (**string**) - 标签文本
99
-
100
- **返回**: **DslBuilder**
101
-
102
- **示例**:
103
- ```javascript
104
- dsl('email!').label('邮箱地址')
105
- ```
106
-
107
- ---
108
-
109
- #### `.messages(messages)`
110
-
111
- 自定义错误消息。
112
-
113
- **参数**:
114
- - `messages` (**Object**) - 错误消息对象
115
- - 键:错误代码(如 `'string.min'`)
116
- - 值:错误消息模板
117
-
118
- **返回**: **DslBuilder**
119
-
120
- **示例**:
121
- ```javascript
122
- dsl('string:3-32!')
123
- .messages({
124
- 'min': '至少{{#limit}}个字符',
125
- 'max': '最多{{#limit}}个字符'
126
- })
127
- ```
128
-
129
- ---
130
-
131
- #### `.description(text)`
132
-
133
- 设置字段描述。
134
-
135
- **参数**:
136
- - `text` (**string**) - 描述文本
137
-
138
- **返回**: **DslBuilder**
139
-
140
- **示例**:
141
- ```javascript
142
- dsl('url').description('个人主页链接')
143
- ```
144
-
145
- ---
146
-
147
- #### `.custom(validator)`
148
-
149
- 添加自定义验证器。
150
-
151
- **参数**:
152
- - `validator` (**Function**) - 验证函数
153
- - 签名:`(value) => boolean | Promise<boolean> | { error, message }`
154
- - 返回 `true` 表示通过
155
- - 返回 `false` 或错误对象表示失败
156
-
157
- **返回**: **DslBuilder**
158
-
159
- **示例**:
160
- ```javascript
161
- dsl('string:3-32!')
162
- .custom(async (value) => {
163
- const exists = await checkUsernameExists(value);
164
- if (exists) {
165
- return { error: 'username.exists', message: '用户名已存在' };
166
- }
167
- return true;
168
- })
169
- ```
170
-
171
-
172
- ---
173
-
174
- #### `.default(value)`
175
-
176
- 设置默认值。
177
-
178
- **参数**:
179
- - `value` (**any**) - 默认值
180
-
181
- **返回**: **DslBuilder**
182
-
183
- **示例**:
184
- ```javascript
185
- dsl('string').default('guest')
186
- ```
187
-
188
- ---
189
-
190
- #### `.username(preset?)`
191
-
192
- 用户名验证(自动设置长度和正则)。
193
-
194
- **参数**:
195
- - `preset` (**string** | **Object**, 可选) - 预设配置
196
- - 字符串:`'short'` | `'medium'` | `'long'` | `'5-20'`
197
- - 对象:`{ minLength, maxLength, allowUnderscore, allowNumber }`
198
- - 默认值:`'medium'` (3-32位)
199
-
200
- **返回**: **DslBuilder**
201
-
202
- **示例**:
203
- ```javascript
204
- // 默认 medium (3-32位)
205
- dsl('string!').username()
206
-
207
- // 自定义范围
208
- dsl('string!').username('5-20')
209
-
210
- // 使用预设
211
- dsl('string!').username('short') // 3-16位
212
- ```
213
-
214
- ---
215
-
216
- #### `.password(strength?)`
217
-
218
- 密码强度验证(自动设置长度和正则)。
219
-
220
- **参数**:
221
- - `strength` (**string**, 可选) - 强度级别
222
- - `'weak'` - 最少6位
223
- - `'medium'` - 8位,字母+数字(默认)
224
- - `'strong'` - 8位,大小写+数字
225
- - `'veryStrong'` - 10位,大小写+数字+特殊字符
226
-
227
- **返回**: **DslBuilder**
228
-
229
- **示例**:
230
- ```javascript
231
- dsl('string!').password('strong')
232
- ```
233
-
234
- ---
235
-
236
- #### `.phone(country?)`
237
-
238
- 手机号验证(自动设置长度和正则)。
239
-
240
- **参数**:
241
- - `country` (**string**, 可选) - 国家代码
242
- - `'cn'` - 中国(默认)
243
- - `'us'` - 美国
244
- - `'uk'` - 英国
245
- - `'hk'` - 香港
246
- - `'tw'` - 台湾
247
- - `'international'` - 国际格式
248
-
249
- **返回**: **DslBuilder**
250
-
251
- **注意**: 自动将类型纠正为 `string`(即使写成 `number` 也会自动修正)
252
-
253
- **示例**:
254
- ```javascript
255
- // 推荐写法
256
- dsl('string!').phone('cn')
257
-
258
- // 自动纠正:number string
259
- dsl('number!').phone('cn') // 自动纠正为 string
260
- ```
261
-
262
- ---
263
-
264
- #### `.toSchema()`
265
-
266
- 转换为 JSON Schema 对象。
267
-
268
- **返回**: **Object** - JSON Schema对象
269
-
270
- **示例**:
271
- ```javascript
272
- const schema = dsl('email!').label('邮箱').toSchema();
273
- // { type: 'string', format: 'email', _label: '邮箱', _required: true }
274
- ```
275
-
276
- ---
277
-
278
- #### `.validate(data, context?)`
279
-
280
- 验证数据(便捷方法)。
281
-
282
- **参数**:
283
- - `data` (**any**) - 待验证数据
284
- - `context` (**Object**, 可选) - 验证上下文
285
-
286
- **返回**: **Promise<Object>** - 验证结果
287
- - `valid` (**boolean**) - 是否通过
288
- - `errors` (**Array**, 可选) - 错误列表
289
- - `data` (**any**, 可选) - 验证通过的数据
290
-
291
- **示例**:
292
- ```javascript
293
- const result = await dsl('email!').validate('user@example.com');
294
- console.log(result.valid); // true
295
- ```
296
-
297
- ---
298
-
299
- ### 静态方法
300
-
301
- #### `dsl.match(field, map)```
302
-
303
- 创建条件验证规则(类似 switch-case)。
304
-
305
- **参数**:
306
- - `field` (**string**) - 依赖的字段名
307
- - `map` (**Object**) - 值与Schema的映射
308
- - `[value: string]`: 对应的Schema
309
- - `_default` (**optional**): 默认Schema
310
-
311
- **返回**: **Object** - 内部Match结构
312
-
313
- **示例**:
314
- ```javascript
315
- dsl.match('type', {
316
- email: 'email!',
317
- phone: 'string:11!',
318
- _default: 'string'
319
- })
320
- ```
321
-
322
- #### `dsl.if(condition, thenSchema, elseSchema)`
323
-
324
- 创建简单的条件验证规则。
325
-
326
- **参数**:
327
- - `condition` (**string**) - 条件字段名
328
- - `thenSchema` (**string|Object**) - 满足条件时的Schema
329
- - `elseSchema` (**string|Object**, 可选) - 不满足条件时的Schema
330
-
331
- **返回**: **Object** - 内部If结构
332
-
333
- **示例**:
334
- ```javascript
335
- dsl.if('isVip', 'number:0-50', 'number:0-10')
336
- ```
337
-
338
- ---
339
-
340
- ## Validator
341
-
342
- **参数**:
343
- - `dslString` (**string**) - DSL字符串,如 `'string:3-32!'`
344
-
345
- ### 方法
346
-
347
- #### `.pattern(regex, message?)`
348
-
349
- 添加正则表达式验证。
350
-
351
- **参数**:
352
- - `regex` (**RegExp** | **string**) - 正则表达式
353
- - `message` (**string**, 可选) - 自定义错误消息
354
-
355
- **返回**: **DslBuilder**
356
-
357
- **示例**:
358
- ```javascript
359
- dsl('string:3-32!')
360
- .pattern(/^[a-zA-Z0-9_]+$/, '只能包含字母、数字和下划线')
361
- ```
362
-
363
- ---
364
-
365
- #### `.label(text)`
366
-
367
- 设置字段标签(用于错误消息)。
368
-
369
- **参数**:
370
- - `text` (**string**) - 标签文本
371
-
372
- **返回**: **DslBuilder**
373
-
374
- **示例**:
375
- ```javascript
376
- dsl('email!').label('邮箱地址')
377
- ```
378
-
379
- ---
380
-
381
- #### `.messages(messages)`
382
-
383
- 自定义错误消息。
384
-
385
- **参数**:
386
- - `messages` (**Object**) - 错误消息对象
387
- - 键:错误代码(如 `'string.min'`)
388
- - 值:错误消息模板
389
-
390
- **返回**: **DslBuilder**
391
-
392
- **示例**:
393
- ```javascript
394
- dsl('string:3-32!')
395
- .messages({
396
- 'string.min': '至少{{#limit}}个字符',
397
- 'string.max': '最多{{#limit}}个字符'
398
- })
399
- ```
400
-
401
- ---
402
-
403
- #### `.description(text)`
404
-
405
- 设置字段描述。
406
-
407
- **参数**:
408
- - `text` (**string**) - 描述文本
409
-
410
- **返回**: **DslBuilder**
411
-
412
- **示例**:
413
- ```javascript
414
- dsl('url').description('个人主页链接')
415
- ```
416
-
417
- ---
418
-
419
- #### `.custom(validator)`
420
-
421
- 添加自定义验证器。
422
-
423
- **参数**:
424
- - `validator` (**Function**) - 验证函数
425
- - 签名:`(value) => boolean | Promise<boolean> | { error, message }`
426
- - 返回 `true` 表示通过
427
- - 返回 `false` 或错误对象表示失败
428
-
429
- **返回**: **DslBuilder**
430
-
431
- **示例**:
432
- ```javascript
433
- dsl('string:3-32!')
434
- .custom(async (value) => {
435
- const exists = await checkUsernameExists(value);
436
- if (exists) {
437
- return { error: 'username.exists', message: '用户名已存在' };
438
- }
439
- return true;
440
- })
441
- ```
442
-
443
- ---
444
-
445
- #### `.default(value)`
446
-
447
- 设置默认值。
448
-
449
- **参数**:
450
- - `value` (**any**) - 默认值
451
-
452
- **返回**: **DslBuilder**
453
-
454
- **示例**:
455
- ```javascript
456
- dsl('string').default('guest')
457
- ```
458
-
459
- ---
460
-
461
- #### `.username(preset?)`
462
-
463
- 用户名验证(自动设置长度和正则)。
464
-
465
- **参数**:
466
- - `preset` (**string** | **Object**, 可选) - 预设配置
467
- - 字符串:`'short'` | `'medium'` | `'long'` | `'5-20'`
468
- - 对象:`{ minLength, maxLength, allowUnderscore, allowNumber }`
469
- - 默认值:`'medium'` (3-32位)
470
-
471
- **返回**: **DslBuilder**
472
-
473
- **示例**:
474
- ```javascript
475
- // 默认 medium (3-32位)
476
- dsl('string!').username()
477
-
478
- // 自定义范围
479
- dsl('string!').username('5-20')
480
-
481
- // 使用预设
482
- dsl('string!').username('short') // 3-16位
483
- ```
484
-
485
- ---
486
-
487
- #### `.password(strength?)`
488
-
489
- 密码强度验证(自动设置长度和正则)。
490
-
491
- **参数**:
492
- - `strength` (**string**, 可选) - 强度级别
493
- - `'weak'` - 最少6位
494
- - `'medium'` - 8位,字母+数字(默认)
495
- - `'strong'` - 8位,大小写+数字
496
- - `'veryStrong'` - 10位,大小写+数字+特殊字符
497
-
498
- **返回**: **DslBuilder**
499
-
500
- **示例**:
501
- ```javascript
502
- dsl('string!').password('strong')
503
- ```
504
-
505
- ---
506
-
507
- #### `.phone(country?)`
508
-
509
- 手机号验证(自动设置长度和正则)。
510
-
511
- **参数**:
512
- - `country` (**string**, 可选) - 国家代码
513
- - `'cn'` - 中国(默认)
514
- - `'us'` - 美国
515
- - `'uk'` - 英国
516
- - `'hk'` - 香港
517
- - `'tw'` - 台湾
518
- - `'international'` - 国际格式
519
-
520
- **返回**: **DslBuilder**
521
-
522
- **注意**: 自动将类型纠正为 `string`(即使写成 `number` 也会自动修正)
523
-
524
- **示例**:
525
- ```javascript
526
- // 推荐写法
527
- dsl('string!').phone('cn')
528
-
529
- // 自动纠正:number → string
530
- dsl('number!').phone('cn') // 自动纠正为 string
531
- ```
532
-
533
- ---
534
-
535
- #### `.toSchema()`
536
-
537
- 转换为 JSON Schema 对象。
538
-
539
- **返回**: **Object** - JSON Schema对象
540
-
541
- **示例**:
542
- ```javascript
543
- const schema = dsl('email!').label('邮箱').toSchema();
544
- // { type: 'string', format: 'email', _label: '邮箱', _required: true }
545
- ```
546
-
547
- ---
548
-
549
- #### `.validate(data, context?)`
550
-
551
- 验证数据(便捷方法)。
552
-
553
- **参数**:
554
- - `data` (**any**) - 待验证数据
555
- - `context` (**Object**, 可选) - 验证上下文
556
-
557
- **返回**: **Promise<Object>** - 验证结果
558
- - `valid` (**boolean**) - 是否通过
559
- - `errors` (**Array**, 可选) - 错误列表
560
- - `data` (**any**, 可选) - 验证通过的数据
561
-
562
- **示例**:
563
- ```javascript
564
- const result = await dsl('email!').validate('user@example.com');
565
- console.log(result.valid); // true
566
- ```
567
-
568
- ---
569
-
570
- ### 静态方法
571
-
572
- #### `dsl.match(field, map)```
573
-
574
- 创建条件验证规则(类似 switch-case)。
575
-
576
- **参数**:
577
- - `field` (**string**) - 依赖的字段名
578
- - `map` (**Object**) - 值与Schema的映射
579
- - `[value: string]`: 对应的Schema
580
- - `_default` (**optional**): 默认Schema
581
-
582
- **返回**: **Object** - 内部Match结构
583
-
584
- **示例**:
585
- ```javascript
586
- dsl.match('type', {
587
- email: 'email!',
588
- phone: 'string:11!',
589
- _default: 'string'
590
- })
591
- ```
592
-
593
- #### `dsl.if(condition, thenSchema, elseSchema)`
594
-
595
- 创建简单的条件验证规则。
596
-
597
- **参数**:
598
- - `condition` (**string**) - 条件字段名
599
- - `thenSchema` (**string|Object**) - 满足条件时的Schema
600
- - `elseSchema` (**string|Object**, 可选) - 不满足条件时的Schema
601
-
602
- **返回**: **Object** - 内部If结构
603
-
604
- **示例**:
605
- ```javascript
606
- dsl.if('isVip', 'number:0-50', 'number:0-10')
607
- ```
608
-
609
- ---
610
-
611
- ## 导出器
612
-
613
- ### MongoDBExporter
614
-
615
- 导出为 MongoDB 验证Schema
616
-
617
- ```javascript
618
- const { MongoDBExporter } = require('schema-dsl');
619
-
620
- const exporter = new MongoDBExporter({ strict: true });
621
- const mongoSchema = exporter.export(jsonSchema);
622
- const command = exporter.generateCommand('users', jsonSchema);
623
- ```
624
-
625
- **方法**:
626
- - `export(schema)` - 导出为MongoDB Schema
627
- - `generateCommand(collection, schema)` - 生成 createCollection 命令
628
-
629
- ---
630
-
631
- ### MySQLExporter
632
-
633
- 导出为 MySQL DDL。
634
-
635
- ```javascript
636
- const { MySQLExporter } = require('schema-dsl');
637
-
638
- const exporter = new MySQLExporter();
639
- const ddl = exporter.export(jsonSchema, { tableName: 'users' });
640
- ```
641
-
642
- **方法**:
643
- - `export(schema, options)` - 导出为MySQL DDL
644
-
645
- ---
646
-
647
- ### PostgreSQLExporter
648
-
649
- 导出为 PostgreSQL DDL。
650
-
651
- ```javascript
652
- const { PostgreSQLExporter } = require('schema-dsl');
653
-
654
- const exporter = new PostgreSQLExporter();
655
- const ddl = exporter.export(jsonSchema, { tableName: 'users' });
656
- ```
657
-
658
- **方法**:
659
- - `export(schema, options)` - 导出为PostgreSQL DDL
660
-
661
- ---
662
-
663
- ## 工具函数
664
-
665
- ### TypeConverter
666
-
667
- 类型转换工具。
668
-
669
- ```javascript
670
- const { TypeConverter } = require('schema-dsl');
671
-
672
- TypeConverter.toJSONSchema(dslSchema);
673
- ```
674
-
675
- ---
676
-
677
- ### SchemaHelper
678
-
679
- Schema辅助工具。
680
-
681
- ```javascript
682
- const { SchemaHelper } = require('schema-dsl');
683
-
684
- SchemaHelper.merge(schema1, schema2);
685
- SchemaHelper.clone(schema);
686
- ```
687
-
688
- ---
689
-
690
- ## DSL 语法快速参考
691
-
692
- ### 基本类型
693
-
694
- ```
695
- string, number, integer, boolean
696
- email, url, uuid, date, datetime
697
- ```
698
-
699
- ### 约束
700
-
701
- ```
702
- string:min-max # 字符串长度
703
- number:min-max # 数字范围
704
- value1|value2 # 枚举
705
- ! # 必填
706
- ```
707
-
708
- ### 数组
709
-
710
- ```
711
- array<type> # 数组
712
- array<string:1-50> # 带约束的数组元素
713
- ```
714
-
715
- ### 示例
716
-
717
- ```javascript
718
- 'string:3-32!' // 必填字符串,长度3-32
719
- 'email!' // 必填邮箱
720
- 'number:18-120' // 可选数字,范围18-120
721
- 'active|inactive|pending' // 枚举
722
- 'array<string:1-20>' // 字符串数组
723
- ```
724
-
725
- ---
726
-
727
- ## 常量
728
-
729
- ### ErrorCodes
730
-
731
- 错误代码常量。
732
-
733
- ```javascript
734
- const { ErrorCodes } = require('schema-dsl');
735
-
736
- console.log(ErrorCodes.STRING_MIN); // 'string.min'
737
- console.log(ErrorCodes.NUMBER_RANGE); // 'number.range'
738
- ```
739
-
740
- ---
741
-
742
- ### Locale
743
-
744
- 多语言支持。
745
-
746
- ```javascript
747
- const { Locale } = require('schema-dsl');
748
-
749
- Locale.setLocale('zh-CN'); // 设置中文
750
- Locale.setLocale('en-US'); // 设置英文
751
- ```
752
-
753
- ---
754
-
755
- ## 完整示例
756
-
757
- ```javascript
758
- const { dsl, Validator } = require('schema-dsl');
759
-
760
- // 定义Schema(使用String扩展)
761
- const userSchema = dsl({
762
- username: 'string:3-32!'
763
- .pattern(/^[a-zA-Z0-9_]+$/)
764
- .messages({
765
- 'string.pattern': '只能包含字母、数字和下划线'
766
- })
767
- .label('用户名'),
768
-
769
- email: 'email!'
770
- .label('邮箱地址'),
771
-
772
- password: 'string:8-64!'
773
- .pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)
774
- .label('密码'),
775
-
776
- age: 'number:18-120',
777
- role: 'user|admin|moderator'
778
- });
779
-
780
- // 验证数据
781
- const validator = new Validator();
782
- const result = validator.validate(userSchema, {
783
- username: 'john_doe',
784
- email: 'john@example.com',
785
- password: 'Password123',
786
- age: 25,
787
- role: 'user'
788
- });
789
-
790
- console.log(result.valid); // true
791
- ```
792
-
793
- ---
794
-
795
- ## 更多资源
796
-
797
- - [DSL 语法完整指南](./dsl-syntax.md)
798
- - [错误处理](./error-handling.md)
799
- - [示例代码](../examples/)
800
- - [GitHub](https://github.com/yourname/schema-dsl)
801
-
802
- ---
803
-
804
- **最后更新**: 2025-12-29
805
-
1
+ # schema-dsl API 参考文档
2
+
3
+
4
+ > **更新时间**: 2026-05-22
5
+
6
+ ---
7
+
8
+ ## 📑 目录
9
+
10
+ - [dsl() 函数](#dsl-函数)
11
+ - [DslBuilder 类](#dslbuilder-类)
12
+ - [String 扩展](#string-扩展)
13
+ - [Validator 类](#validator-类)
14
+ - [导出器](#导出器)
15
+ - [工具函数](#工具函数)
16
+
17
+ ---
18
+
19
+ ## dsl() 函数
20
+
21
+ ### 描述
22
+
23
+ DSL 主入口函数,支持字符串和对象两种定义方式。
24
+
25
+ ### 语法
26
+
27
+ ```javascript
28
+ dsl(definition: string | object): DslBuilder | JSONSchema
29
+ ```
30
+
31
+ ### 参数
32
+
33
+ - `definition` (**string** | **object**) - DSL定义
34
+ - 字符串:返回 DslBuilder 实例(可链式调用)
35
+ - 对象:返回 JSON Schema 对象
36
+
37
+ ### 返回值
38
+
39
+ - **DslBuilder** - 当参数为字符串时
40
+ - **Object** - 当参数为对象时(JSON Schema)
41
+
42
+ ### 示例
43
+
44
+ ```javascript
45
+ // 字符串:返回 DslBuilder
46
+ const builder = dsl('email!');
47
+ builder.pattern(/custom/).label('邮箱');
48
+
49
+ // 对象:返回 JSON Schema
50
+ const schema = dsl({
51
+ username: 'string:3-32!',
52
+ email: 'email!'
53
+ });
54
+ ```
55
+
56
+ ---
57
+
58
+ ## DslBuilder 类
59
+
60
+ ### 描述
61
+
62
+ Schema 构建器类,支持链式调用添加验证规则。
63
+
64
+ ### 构造函数
65
+
66
+ ```javascript
67
+ new DslBuilder(dslString: string)
68
+ ```
69
+
70
+ **参数**:
71
+ - `dslString` (**string**) - DSL字符串,如 `'string:3-32!'`
72
+
73
+ ### 方法
74
+
75
+ #### `.pattern(regex, message?)`
76
+
77
+ 添加正则表达式验证。
78
+
79
+ **参数**:
80
+ - `regex` (**RegExp** | **string**) - 正则表达式
81
+ - `message` (**string**, 可选) - 自定义错误消息
82
+
83
+ **返回**: **DslBuilder**
84
+
85
+ **示例**:
86
+ ```javascript
87
+ dsl('string:3-32!')
88
+ .pattern(/^[a-zA-Z0-9_]+$/, '只能包含字母、数字和下划线')
89
+ ```
90
+
91
+ ---
92
+
93
+ #### `.label(text)`
94
+
95
+ 设置字段标签(用于错误消息)。
96
+
97
+ **参数**:
98
+ - `text` (**string**) - 标签文本
99
+
100
+ **返回**: **DslBuilder**
101
+
102
+ **示例**:
103
+ ```javascript
104
+ dsl('email!').label('邮箱地址')
105
+ ```
106
+
107
+ ---
108
+
109
+ #### `.messages(messages)`
110
+
111
+ 自定义错误消息。
112
+
113
+ **参数**:
114
+ - `messages` (**Object**) - 错误消息对象
115
+ - 键:错误代码(如 `'string.min'`)
116
+ - 值:错误消息模板
117
+
118
+ **返回**: **DslBuilder**
119
+
120
+ **示例**:
121
+ ```javascript
122
+ dsl('string:3-32!')
123
+ .messages({
124
+ 'min': '至少{{#limit}}个字符',
125
+ 'max': '最多{{#limit}}个字符'
126
+ })
127
+ ```
128
+
129
+ ---
130
+
131
+ #### `.description(text)`
132
+
133
+ 设置字段描述。
134
+
135
+ **参数**:
136
+ - `text` (**string**) - 描述文本
137
+
138
+ **返回**: **DslBuilder**
139
+
140
+ **示例**:
141
+ ```javascript
142
+ dsl('url').description('个人主页链接')
143
+ ```
144
+
145
+ ---
146
+
147
+ #### `.custom(validator)`
148
+
149
+ 添加自定义验证器。
150
+
151
+ **参数**:
152
+ - `validator` (**Function**) - 验证函数
153
+ - 签名:`(value) => boolean | string | { error, message } | void`
154
+ - 返回 `true` 表示通过
155
+ - 返回 `false`、错误消息字符串或错误对象表示失败
156
+ - 同步验证器由 `validate()` 和 `validateAsync()` 均执行;异步验证器(返回 `Promise`)仅由 `validateAsync()` 执行,`validate()` 调用时会跳过异步 validator
157
+
158
+ **返回**: **DslBuilder**
159
+
160
+ **示例**:
161
+ ```javascript
162
+ dsl('string:3-32!')
163
+ .custom((value) => {
164
+ if (value === 'admin') {
165
+ return { error: 'username.exists', message: '用户名已存在' };
166
+ }
167
+ })
168
+ ```
169
+
170
+
171
+ ---
172
+
173
+ #### `.default(value)`
174
+
175
+ 设置默认值。
176
+
177
+ **参数**:
178
+ - `value` (**any**) - 默认值
179
+
180
+ **返回**: **DslBuilder**
181
+
182
+ **示例**:
183
+ ```javascript
184
+ dsl('string').default('guest')
185
+ ```
186
+
187
+ ---
188
+
189
+ #### `.username(preset?)`
190
+
191
+ 用户名验证(自动设置长度和正则)。
192
+
193
+ **参数**:
194
+ - `preset` (**string** | **Object**, 可选) - 预设配置
195
+ - 字符串:`'short'` | `'medium'` | `'long'` | `'5-20'`
196
+ - 对象:`{ minLength, maxLength, allowUnderscore, allowNumber }`
197
+ - 默认值:`'medium'` (3-32位)
198
+
199
+ **返回**: **DslBuilder**
200
+
201
+ **示例**:
202
+ ```javascript
203
+ // 默认 medium (3-32位)
204
+ dsl('string!').username()
205
+
206
+ // 自定义范围
207
+ dsl('string!').username('5-20')
208
+
209
+ // 使用预设
210
+ dsl('string!').username('short') // 3-16位
211
+ ```
212
+
213
+ ---
214
+
215
+ #### `.password(strength?)`
216
+
217
+ 密码强度验证(自动设置长度和正则)。
218
+
219
+ **参数**:
220
+ - `strength` (**string**, 可选) - 强度级别
221
+ - `'weak'` - 最少6位
222
+ - `'medium'` - 8位,字母+数字(默认)
223
+ - `'strong'` - 8位,大小写+数字
224
+ - `'veryStrong'` - 10位,大小写+数字+特殊字符
225
+
226
+ **返回**: **DslBuilder**
227
+
228
+ **示例**:
229
+ ```javascript
230
+ dsl('string!').password('strong')
231
+ ```
232
+
233
+ ---
234
+
235
+ #### `.phone(country?)`
236
+
237
+ 手机号验证(自动设置长度和正则)。
238
+
239
+ **参数**:
240
+ - `country` (**string**, 可选) - 国家代码
241
+ - `'cn'` - 中国(默认)
242
+ - `'us'` - 美国
243
+ - `'uk'` - 英国
244
+ - `'hk'` - 香港
245
+ - `'tw'` - 台湾
246
+ - `'international'` - 国际格式
247
+
248
+ **返回**: **DslBuilder**
249
+
250
+ **注意**: 自动将类型纠正为 `string`(即使写成 `number` 也会自动修正)
251
+
252
+ **示例**:
253
+ ```javascript
254
+ // 推荐写法
255
+ dsl('string!').phone('cn')
256
+
257
+ // 自动纠正:number → string
258
+ dsl('number!').phone('cn') // 自动纠正为 string
259
+ ```
260
+
261
+ ---
262
+
263
+ #### `.toSchema()`
264
+
265
+ 转换为 JSON Schema 对象(含内部标记)。
266
+
267
+ **返回**: **Object** - JSON Schema 对象(包含 `_required`、`_customMessages`、`_label` 等 schema-dsl 内部字段)
268
+
269
+ **示例**:
270
+ ```javascript
271
+ const schema = dsl('email!').label('邮箱').toSchema();
272
+ // { type: 'string', format: 'email', _label: '邮箱', _required: true }
273
+ ```
274
+
275
+ ---
276
+
277
+ #### `.toJsonSchema()` <sup>v1.2.5+</sup>
278
+
279
+ 转换为纯净的 JSON Schema 对象(无内部标记)。
280
+
281
+ 与 `toSchema()` 不同,`toJsonSchema()` 会自动清理所有 schema-dsl 内部标记:
282
+ - **下划线前缀字段**:`_required`、`_customMessages`、`_label`、`_customValidators`、`_whenConditions`
283
+ - **自定义验证关键字(直接清除)**:`alphanum`、`lowercase`、`uppercase`、`trim`、`jsonString`、`port`、`requiredAll`、`strictSchema`、`noSparse`、`includesRequired`、`dateFormat`、`dateGreater`、`dateLess`、`precision`
284
+ - **`exactLength` 特殊翻译**:不直接清除,而是转换为标准 JSON Schema `{ minLength: N, maxLength: N }`(与 v1 DslBuilder `string:N` 行为兼容)
285
+
286
+ > ⚠️ `multipleOf` 是标准 JSON Schema 字段,**不会**被清除(v2 修复了 v1 的错误行为)。
287
+
288
+ 返回的对象可直接嵌入 OpenAPI / JSON Schema 等标准文档中,无需下游再做清理。
289
+
290
+ **返回**: **Object** - 纯净的 JSON Schema 对象
291
+
292
+ **适用场景**:
293
+ - 生成 OpenAPI 文档
294
+ - 导出给外部系统消费
295
+ - 任何需要标准 JSON Schema 的场景
296
+
297
+ **示例**:
298
+ ```javascript
299
+ // 对比 toSchema() 与 toJsonSchema()
300
+ const builder = dsl('string:3-32!').label('用户名').messages({ min: '至少3个字符' });
301
+
302
+ builder.toSchema();
303
+ // { type: 'string', minLength: 3, maxLength: 32, _required: true, _label: '用户名', _customMessages: { min: '至少3个字符' } }
304
+
305
+ builder.toJsonSchema();
306
+ // { type: 'string', minLength: 3, maxLength: 32 }
307
+ // 注意:不含 _required、_label、_customMessages 等内部字段
308
+
309
+ // string:N 单值语法(exactLength → minLength + maxLength)
310
+ const exact = dsl('string:6!');
311
+ exact.toSchema();
312
+ // { type: 'string', exactLength: 6, _required: true }
313
+ exact.toJsonSchema();
314
+ // { type: 'string', minLength: 6, maxLength: 6 }
315
+ // 注:exactLength 自动翻译为标准 JSON Schema 的 minLength + maxLength(v1 兼容行为)
316
+
317
+ // enum 示例
318
+ const enumBuilder = dsl('enum:admin,user,guest!');
319
+ enumBuilder.toJsonSchema();
320
+ // { type: 'string', enum: ['admin', 'user', 'guest'] }
321
+
322
+ // 用于 OpenAPI 文档生成
323
+ const schema = dsl({
324
+ username: 'string:3-32!',
325
+ email: 'email!',
326
+ age: 'number:0-120'
327
+ });
328
+ // 遍历各字段调用 toJsonSchema() 即可获得标准 JSON Schema
329
+ ```
330
+
331
+ ---
332
+
333
+ #### `.validate(data)`
334
+
335
+ 验证数据(便捷方法)。
336
+
337
+ **参数**:
338
+ - `data` (**any**) - 待验证数据
339
+
340
+ **返回**: **Promise<Object>** - 验证结果
341
+ - `valid` (**boolean**) - 是否通过
342
+ - `errors` (**Array**, 可选) - 错误列表
343
+ - `data` (**any**, 可选) - 验证通过的数据
344
+
345
+ **示例**:
346
+ ```javascript
347
+ const result = await dsl('email!').validate('user@example.com');
348
+ console.log(result.valid); // true
349
+ ```
350
+
351
+ ---
352
+
353
+ ### 静态方法
354
+
355
+ #### `dsl.match(field, map)```
356
+
357
+ 创建条件验证规则(类似 switch-case)。
358
+
359
+ **参数**:
360
+ - `field` (**string**) - 依赖的字段名
361
+ - `map` (**Object**) - 值与Schema的映射
362
+ - `[value: string]`: 对应的Schema
363
+ - `_default` (**optional**): 默认Schema
364
+
365
+ **返回**: **Object** - 内部Match结构
366
+
367
+ **示例**:
368
+ ```javascript
369
+ dsl.match('type', {
370
+ email: 'email!',
371
+ phone: 'string:11!',
372
+ _default: 'string'
373
+ })
374
+ ```
375
+
376
+ #### `dsl.if(condition, thenSchema, elseSchema)`
377
+
378
+ 创建简单的条件验证规则。
379
+
380
+ **参数**:
381
+ - `condition` (**string**) - 条件字段名
382
+ - `thenSchema` (**string|Object**) - 满足条件时的Schema
383
+ - `elseSchema` (**string|Object**, 可选) - 不满足条件时的Schema
384
+
385
+ **返回**: **Object** - 内部If结构
386
+
387
+ **示例**:
388
+ ```javascript
389
+ dsl.if('isVip', 'number:0-50', 'number:0-10')
390
+ ```
391
+
392
+ ---
393
+
394
+ ## 运行时辅助函数
395
+
396
+ ### `dsl.config(options)`
397
+
398
+ 全局配置入口,在应用启动时调用一次,设置 i18n、缓存、自定义正则和严格类型解析模式。
399
+
400
+ ```javascript
401
+ const { dsl } = require('schema-dsl');
402
+
403
+ dsl.config({
404
+ // i18n:内置语言包路径 / 内联 locale bundle / { localesPath } / { locales }
405
+ i18n: './locales',
406
+
407
+ // 默认语言(默认 'en-US')
408
+ defaultLocale: 'zh-CN',
409
+
410
+ // 编译缓存配置
411
+ cache: { maxSize: 2000, ttl: 0, enabled: true },
412
+
413
+ // strict: true → 遇到未知类型直接抛出 Error(默认 false:warn + 回退 string)
414
+ strict: true,
415
+
416
+ // 追加自定义正则规则(phone / idCard / creditCard 等)
417
+ patterns: {
418
+ phone: { us: /^\+1\d{10}$/ }
419
+ }
420
+ });
421
+ ```
422
+
423
+ **参数** (`DslConfigOptions`):
424
+
425
+ | 字段 | 类型 | 默认 | 说明 |
426
+ |------|------|------|------|
427
+ | `i18n` | `string \| object` | — | 语言包路径或内联对象 |
428
+ | `defaultLocale` | `string` | `'en-US'` | 默认语言 |
429
+ | `cache` | `CacheOptions` | — | `maxSize` / `ttl` / `enabled` / `statsEnabled` |
430
+ | `strict` | `boolean` | `false` | `true` 时解析未知 DSL 类型抛出 Error |
431
+ | `patterns` | `object` | — | 追加自定义格式正则(phone/idCard/creditCard) |
432
+
433
+ ---
434
+
435
+ ### `getDefaultValidator()`
436
+
437
+ 获取顶层 `validate()` / `validateAsync()` 便捷函数内部复用的默认 `Validator` 单例。
438
+
439
+ ```javascript
440
+ const { getDefaultValidator } = require('schema-dsl');
441
+
442
+ const validator = getDefaultValidator();
443
+ console.log(validator.getCacheStats());
444
+ ```
445
+
446
+ ---
447
+
448
+ ### `resetDefaultValidator()`
449
+
450
+ 重置顶层 `validate()` / `validateAsync()` 使用的默认 `Validator` 单例。
451
+
452
+ ```javascript
453
+ const { resetDefaultValidator } = require('schema-dsl');
454
+
455
+ resetDefaultValidator();
456
+ ```
457
+
458
+ ---
459
+
460
+ ### `installStringExtensions(dslFunction?)`
461
+
462
+ 手动安装 String 扩展。模块导入时默认已自动安装;只有在调用过 `uninstallStringExtensions()` 或需要显式恢复扩展时才需要手动执行。
463
+
464
+ ```javascript
465
+ const { installStringExtensions } = require('schema-dsl');
466
+
467
+ installStringExtensions();
468
+ ```
469
+
470
+ ---
471
+
472
+ ### `uninstallStringExtensions()`
473
+
474
+ 卸载挂载到 `String.prototype` 上的扩展方法。
475
+
476
+ ```javascript
477
+ const { uninstallStringExtensions } = require('schema-dsl');
478
+
479
+ uninstallStringExtensions();
480
+ ```
481
+
482
+ ---
483
+
484
+ ## Validator 类
485
+
486
+ **参数**:
487
+ - `options` (**Object**, 可选) - Validator 配置项
488
+
489
+ ### 方法
490
+
491
+ #### `.compile(schema, cacheKey?)`
492
+
493
+ 编译 Schema AJV 验证函数。
494
+
495
+ **参数**:
496
+ - `schema` (**Object**) - JSON Schema
497
+ - `cacheKey` (**string** | **null**, 可选) - 缓存键
498
+
499
+ **返回**: **Function** - AJV 验证函数
500
+
501
+ **示例**:
502
+ ```javascript
503
+ const validator = new Validator();
504
+ const validate = validator.compile(schema, 'user-schema');
505
+ const ok = validate(data);
506
+ ```
507
+
508
+ ---
509
+
510
+ #### `.validate(schema, data, options?)`
511
+
512
+ 同步验证。
513
+
514
+ **参数**:
515
+ - `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
516
+ - `data` (**any**) - 待验证数据
517
+ - `options` (**Object**, 可选) - 验证选项
518
+
519
+ **返回**: **Object**
520
+ - `valid` (**boolean**) - 是否通过
521
+ - `errors` (**Array**, 可选) - 错误列表
522
+ - `data` (**any**, 可选) - 经过处理后的数据
523
+
524
+ **示例**:
525
+ ```javascript
526
+ const validator = new Validator();
527
+ const result = validator.validate(schema, payload);
528
+ console.log(result.valid);
529
+ ```
530
+
531
+ ---
532
+
533
+ #### `.validateAsync(schema, data, options?)`
534
+
535
+ 异步验证。验证失败时抛出 `ValidationError`。
536
+
537
+ **参数**:
538
+ - `schema` (**Object** | **Function**) - JSON Schema 或已编译的验证函数
539
+ - `data` (**any**) - 待验证数据
540
+ - `options` (**Object**, 可选) - 验证选项
541
+
542
+ **返回**: **Promise<any>** - 验证通过后的数据
543
+
544
+ **示例**:
545
+ ```javascript
546
+ const validator = new Validator();
547
+ await validator.validateAsync(schema, payload);
548
+ ```
549
+
550
+ ---
551
+
552
+ #### `.validateBatch(schema, dataArray)`
553
+
554
+ 批量验证。Schema 只编译一次,多次复用。
555
+
556
+ **参数**:
557
+ - `schema` (**Object**) - JSON Schema
558
+ - `dataArray` (**Array**) - 待验证数据数组
559
+
560
+ **返回**: **Array<Object>** - 每项对应一个验证结果
561
+
562
+ **示例**:
563
+ ```javascript
564
+ const validator = new Validator();
565
+ const results = validator.validateBatch(schema, records);
566
+ ```
567
+
568
+ ---
569
+
570
+ #### `.addKeyword(keyword, definition)`
571
+
572
+ 添加 AJV 自定义关键字。
573
+
574
+ **参数**:
575
+ - `keyword` (**string**) - 关键字名称
576
+ - `definition` (**Object**) - AJV 关键字定义
577
+
578
+ **返回**: **Validator**
579
+
580
+ **示例**:
581
+ ```javascript
582
+ const validator = new Validator();
583
+ validator.addKeyword('isEven', {
584
+ type: 'number',
585
+ validate: (_schema, data) => data % 2 === 0
586
+ });
587
+ ```
588
+
589
+ ---
590
+
591
+ #### `.addFormat(name, validator)`
592
+
593
+ 添加 AJV 自定义格式。
594
+
595
+ **参数**:
596
+ - `name` (**string**) - 格式名称
597
+ - `validator` (**Function** | **Object**) - AJV format 定义
598
+
599
+ **返回**: **Validator**
600
+
601
+ **示例**:
602
+ ```javascript
603
+ const validator = new Validator();
604
+ validator.addFormat('phone-cn', /^1[3-9]\d{9}$/);
605
+ ```
606
+
607
+ ---
608
+
609
+ #### `.addSchema(uri, schema)`
610
+
611
+ 添加 schema 引用。
612
+
613
+ **参数**:
614
+ - `uri` (**string**) - schema 标识
615
+ - `schema` (**Object**) - JSON Schema
616
+
617
+ **返回**: **Validator**
618
+
619
+ **示例**:
620
+ ```javascript
621
+ const validator = new Validator();
622
+ validator.addSchema('user.schema.json', schema);
623
+ ```
624
+
625
+ ---
626
+
627
+ #### `.removeSchema(uri)`
628
+
629
+ 删除 schema 引用。
630
+
631
+ **参数**:
632
+ - `uri` (**string**) - schema 标识
633
+
634
+ **返回**: **Validator**
635
+
636
+ **示例**:
637
+ ```javascript
638
+ const validator = new Validator();
639
+ validator.removeSchema('user.schema.json');
640
+ ```
641
+
642
+ ---
643
+
644
+ #### `.getAjv()`
645
+
646
+ 获取底层 AJV 实例。
647
+
648
+ **返回**: **Ajv**
649
+
650
+ **示例**:
651
+ ```javascript
652
+ const validator = new Validator();
653
+ const ajv = validator.getAjv();
654
+ ```
655
+
656
+ ---
657
+
658
+ #### `.clearCache()`
659
+
660
+ 清空编译缓存。
661
+
662
+ **返回**: `void`
663
+
664
+ **示例**:
665
+ ```javascript
666
+ const validator = new Validator();
667
+ validator.clearCache();
668
+ ```
669
+
670
+ ---
671
+
672
+ #### `.getCacheStats()`
673
+
674
+ 获取缓存统计信息。
675
+
676
+ **返回**: **Object**
677
+
678
+ **示例**:
679
+ ```javascript
680
+ const validator = new Validator();
681
+ console.log(validator.getCacheStats());
682
+ ```
683
+
684
+ ---
685
+
686
+ ### 静态方法
687
+
688
+ #### `Validator.create(options?)`
689
+
690
+ 创建 `Validator` 实例。
691
+
692
+ **返回**: **Validator**
693
+
694
+ **示例**:
695
+ ```javascript
696
+ const validator = Validator.create();
697
+ ```
698
+
699
+ ---
700
+
701
+ #### `Validator.quickValidate(schema, data)`
702
+
703
+ 快速验证。
704
+
705
+ **参数**:
706
+ - `schema` (**Object**) - JSON Schema
707
+ - `data` (**any**) - 待验证数据
708
+
709
+ **返回**: **boolean**
710
+
711
+ **示例**:
712
+ ```javascript
713
+ const ok = Validator.quickValidate(schema, data);
714
+ ```
715
+
716
+ ---
717
+
718
+ ## 导出器
719
+
720
+ ### MongoDBExporter
721
+
722
+ 导出为 MongoDB 验证Schema。
723
+
724
+ ```javascript
725
+ const { MongoDBExporter } = require('schema-dsl');
726
+
727
+ const exporter = new MongoDBExporter({ strict: true });
728
+ const mongoSchema = exporter.export(jsonSchema);
729
+ const command = exporter.generateCommand('users', jsonSchema);
730
+ ```
731
+
732
+ **方法**:
733
+ - `export(schema)` - 导出为MongoDB Schema
734
+ - `generateCommand(collection, schema)` - 生成 createCollection 命令
735
+
736
+ ---
737
+
738
+ ### MySQLExporter
739
+
740
+ 导出为 MySQL DDL。
741
+
742
+ ```javascript
743
+ const { MySQLExporter } = require('schema-dsl');
744
+
745
+ const exporter = new MySQLExporter();
746
+ const ddl = exporter.export('users', jsonSchema);
747
+ ```
748
+
749
+ **方法**:
750
+ - `export(tableName, schema)` - 导出为MySQL DDL
751
+
752
+ ---
753
+
754
+ ### PostgreSQLExporter
755
+
756
+ 导出为 PostgreSQL DDL。
757
+
758
+ ```javascript
759
+ const { PostgreSQLExporter } = require('schema-dsl');
760
+
761
+ const exporter = new PostgreSQLExporter();
762
+ const ddl = exporter.export('users', jsonSchema);
763
+ ```
764
+
765
+ **方法**:
766
+ - `export(tableName, schema)` - 导出为PostgreSQL DDL
767
+
768
+ ---
769
+
770
+ ## 工具函数
771
+
772
+ ### TypeConverter
773
+
774
+ 类型转换工具。
775
+
776
+ ```javascript
777
+ const { TypeConverter } = require('schema-dsl');
778
+
779
+ TypeConverter.toJSONSchemaType('string');
780
+ TypeConverter.toMongoDBType('integer');
781
+ ```
782
+
783
+ ---
784
+
785
+ ### SchemaHelper
786
+
787
+ Schema辅助工具。
788
+
789
+ ```javascript
790
+ const { SchemaHelper } = require('schema-dsl');
791
+
792
+ SchemaHelper.merge(schema1, schema2);
793
+ SchemaHelper.clone(schema);
794
+ ```
795
+
796
+ ---
797
+
798
+ ### ErrorFormatter
799
+
800
+ 验证错误格式化工具,用于把 Ajv 原始错误数组或简化错误对象转换成统一的错误项结构或消息文本。
801
+
802
+ ```javascript
803
+ const { ErrorFormatter } = require('schema-dsl');
804
+
805
+ const formatter = new ErrorFormatter('zh-CN');
806
+ const errors = formatter.formatDetailed(ajvValidate.errors);
807
+ console.log(errors[0].message);
808
+ ```
809
+
810
+ **方法**:
811
+ - `new ErrorFormatter(locale?, messages?)` - 创建错误格式化器
812
+ - `format(error, locale?)` - 格式化单个错误为消息字符串
813
+ - `formatDetailed(errors, locale?, customMessages?, alreadyMerged?)` - 格式化错误数组为标准错误项列表
814
+
815
+ ---
816
+
817
+ ### MessageTemplate
818
+
819
+ 错误消息模板封装类,内部委托 `renderTemplate()` 执行占位符替换。
820
+
821
+ ```javascript
822
+ const { MessageTemplate } = require('schema-dsl');
823
+
824
+ const template = new MessageTemplate('{{#label}} is required');
825
+ console.log(template.render({ label: 'Email' }));
826
+ ```
827
+
828
+ **方法**:
829
+ - `new MessageTemplate(template)` - 创建模板实例
830
+ - `render(context)` - 渲染当前模板
831
+ - `MessageTemplate.render(template, context)` - 静态快速渲染
832
+ - `MessageTemplate.renderBatch(templates, context)` - 批量渲染多个模板
833
+
834
+ ---
835
+
836
+ ### renderTemplate(template, params)
837
+
838
+ 底层模板渲染函数,同时兼容 `{{#key}}` 和 `{key}` 两种占位符格式。
839
+
840
+ ```javascript
841
+ const { renderTemplate } = require('schema-dsl');
842
+
843
+ const msg = renderTemplate('{field} must be {min}~{max}', {
844
+ field: 'age',
845
+ min: 18,
846
+ max: 65,
847
+ });
848
+
849
+ console.log(msg); // age must be 18~65
850
+ ```
851
+
852
+ ---
853
+
854
+ ### JSONSchemaCore
855
+
856
+ `JSONSchemaCore` 是 v1 兼容外观类,用于以链式方式构建 JSON Schema,并可直接调用 `validate()` 做快速校验。
857
+
858
+ ```javascript
859
+ const { JSONSchemaCore } = require('schema-dsl');
860
+
861
+ const schema = new JSONSchemaCore()
862
+ .type('object')
863
+ .property('email', { type: 'string', format: 'email' })
864
+ .required('email')
865
+ .getSchema();
866
+ ```
867
+
868
+ **常用方法**:
869
+ - `type(typeName)`
870
+ - `property(name, schema)`
871
+ - `properties(properties)`
872
+ - `required(fields)`
873
+ - `format(formatName)`
874
+ - `pattern(pattern)`
875
+ - `items(schema)`
876
+ - `toSchema()` / `getSchema()`
877
+ - `validate(data)`
878
+
879
+ ---
880
+
881
+ ### 类型注册与内部解析边界
882
+
883
+ `schema-dsl` 的 root API 只保留业务可依赖的稳定入口。DSL 解析器、约束解析器、Schema 编译器和 Adapter 属于内部实现细节,不再作为 root API 文档化导出;业务代码应优先使用 `dsl()`、`DslBuilder`、`Validator` 和 `validate()`。
884
+
885
+ #### TypeRegistry
886
+
887
+ 统一类型注册表。它是自定义类型扩展的公开入口;如果只需要注册 DSL 类型,也可以优先使用更高层的 `DslBuilder.registerType()`。
888
+
889
+ - `TypeRegistry.resolve(typeName)`
890
+ - `TypeRegistry.register(name, def)`
891
+ - `TypeRegistry.registerDynamic(name, factory)`
892
+ - `TypeRegistry.unregister(name)`
893
+ - `TypeRegistry.has(typeName)`
894
+ - `TypeRegistry.getInternalKeys()`
895
+ - `TypeRegistry.toJsonSchema(schema)`
896
+ - `TypeRegistry.clearCustomTypes()` — 清空所有自定义类型(含通过 `DslAdapter.registerType()` 注册的类型),适合测试后清理状态
897
+ - `TypeRegistry.setStrict(flag)` — 设置严格模式,等效于 `dsl.config({ strict: flag })`
898
+
899
+ ---
900
+
901
+ ## DSL 语法快速参考
902
+
903
+ ### 基本类型
904
+
905
+ ```text
906
+ string, number, integer, boolean
907
+ email, url, uuid, date, datetime
908
+ ```
909
+
910
+ ### 约束
911
+
912
+ ```text
913
+ string:N # 精确长度(exactLength = N,等同于 minLength: N, maxLength: N)
914
+ string:min-max # 字符串长度范围
915
+ number:min-max # 数字范围
916
+ value1|value2 # 枚举
917
+ ! # 必填
918
+ ```
919
+
920
+ ### 数组
921
+
922
+ ```text
923
+ array<type> # 数组
924
+ array<string:1-50> # 带约束的数组元素
925
+ ```
926
+
927
+ ### 示例
928
+
929
+ ```javascript
930
+ 'string:3-32!' // 必填字符串,长度3-32
931
+ 'email!' // 必填邮箱
932
+ 'number:18-120' // 可选数字,范围18-120
933
+ 'active|inactive|pending' // 枚举
934
+ 'array<string:1-20>' // 字符串数组
935
+ ```
936
+
937
+ ---
938
+
939
+ ## 常量
940
+
941
+ ### ErrorCodes
942
+
943
+ 错误代码常量。
944
+
945
+ ```javascript
946
+ const { ErrorCodes } = require('schema-dsl');
947
+
948
+ console.log(ErrorCodes.STRING_MIN); // 'string.min'
949
+ console.log(ErrorCodes.NUMBER_RANGE); // 'number.range'
950
+ ```
951
+
952
+ ---
953
+
954
+ ### Locale
955
+
956
+ 多语言支持。
957
+
958
+ ```javascript
959
+ const { Locale } = require('schema-dsl');
960
+
961
+ Locale.setLocale('zh-CN'); // 设置中文
962
+ Locale.setLocale('en-US'); // 设置英文
963
+ ```
964
+
965
+ ---
966
+
967
+ ### ConditionalBuilder
968
+
969
+ `dsl.if(conditionFn)` 返回的链式条件构建器,适用于运行时动态条件校验。
970
+
971
+ **常用方法**:
972
+ - `if(condition)`
973
+ - `and(condition)`
974
+ - `or(condition)`
975
+ - `elseIf(condition)`
976
+ - `message(msg)`
977
+ - `then(schema)`
978
+ - `else(schema)`
979
+ - `toSchema()`
980
+ - `build()` - `toSchema()` 的别名
981
+ - `validate(data, options?)`
982
+ - `validateAsync(data, options?)`
983
+ - `assert(data, options?)`
984
+ - `check(data)`
985
+
986
+ 更完整的示例和行为说明请参考 [conditional-api.md](./conditional-api.md)。
987
+
988
+ ---
989
+
990
+ ## 完整示例
991
+
992
+ ```javascript
993
+ const { dsl, Validator } = require('schema-dsl');
994
+
995
+ // 定义Schema(使用String扩展)
996
+ const userSchema = dsl({
997
+ username: 'string:3-32!'
998
+ .pattern(/^[a-zA-Z0-9_]+$/)
999
+ .messages({
1000
+ 'string.pattern': '只能包含字母、数字和下划线'
1001
+ })
1002
+ .label('用户名'),
1003
+
1004
+ email: 'email!'
1005
+ .label('邮箱地址'),
1006
+
1007
+ password: 'string:8-64!'
1008
+ .pattern(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)
1009
+ .label('密码'),
1010
+
1011
+ age: 'number:18-120',
1012
+ role: 'user|admin|moderator'
1013
+ });
1014
+
1015
+ // 验证数据
1016
+ const validator = new Validator();
1017
+ const result = validator.validate(userSchema, {
1018
+ username: 'john_doe',
1019
+ email: 'john@example.com',
1020
+ password: 'Password123',
1021
+ age: 25,
1022
+ role: 'user'
1023
+ });
1024
+
1025
+ console.log(result.valid); // true
1026
+ ```
1027
+
1028
+ ---
1029
+
1030
+ ## 更多资源
1031
+
1032
+ - [DSL 语法完整指南](./dsl-syntax.md)
1033
+ - [错误处理](./error-handling.md)
1034
+ - [示例代码](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
1035
+ - [GitHub](https://github.com/vextjs/schema-dsl)
1036
+
1037
+ ---
1038
+
1039
+ ## 对应示例文件
1040
+
1041
+ **示例入口**: [api-reference.ts](https://github.com/vextjs/schema-dsl/blob/main/examples/docs/api-reference.ts)
1042
+ **说明**: 覆盖 `dsl()`、`validate()`、`validateAsync()`、默认 `Validator` 单例、模板渲染、`JSONSchemaCore`、`ErrorFormatter` 以及底层解析 / 编译工具的可运行调用链。
1043
+
1044
+ ---
1045
+
1046
+ **最后更新**: 2026-05-08
1047
+