@tsed/ajv 6.67.0 → 6.68.3

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/lib/index.js CHANGED
@@ -1,11 +1,302 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./errors/AjvValidationError"), exports);
5
- tslib_1.__exportStar(require("./services/AjvService"), exports);
6
- tslib_1.__exportStar(require("./services/Ajv"), exports);
7
- tslib_1.__exportStar(require("./decorators/keyword"), exports);
8
- tslib_1.__exportStar(require("./interfaces/KeywordMethods"), exports);
9
- tslib_1.__exportStar(require("./decorators/formats"), exports);
10
- tslib_1.__exportStar(require("./interfaces/FormatsMethods"), exports);
11
- //# sourceMappingURL=index.js.map
1
+ var exceptions = require('@tsed/exceptions');
2
+ var tslib = require('tslib');
3
+ var core = require('@tsed/core');
4
+ var di = require('@tsed/di');
5
+ var schema = require('@tsed/schema');
6
+ var Ajv = require('ajv');
7
+ var AjvFormats = require('ajv-formats');
8
+
9
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
+
11
+ var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
12
+ var AjvFormats__default = /*#__PURE__*/_interopDefaultLegacy(AjvFormats);
13
+
14
+ class AjvValidationError extends exceptions.BadRequest {
15
+ constructor(message, errors = []) {
16
+ super(message);
17
+ this.name = "AJV_VALIDATION_ERROR";
18
+ this.errors = errors;
19
+ }
20
+
21
+ }
22
+
23
+ function _extends() {
24
+ _extends = Object.assign || function (target) {
25
+ for (var i = 1; i < arguments.length; i++) {
26
+ var source = arguments[i];
27
+
28
+ for (var key in source) {
29
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
30
+ target[key] = source[key];
31
+ }
32
+ }
33
+ }
34
+
35
+ return target;
36
+ };
37
+
38
+ return _extends.apply(this, arguments);
39
+ }
40
+
41
+ function _objectWithoutPropertiesLoose(source, excluded) {
42
+ if (source == null) return {};
43
+ var target = {};
44
+ var sourceKeys = Object.keys(source);
45
+ var key, i;
46
+
47
+ for (i = 0; i < sourceKeys.length; i++) {
48
+ key = sourceKeys[i];
49
+ if (excluded.indexOf(key) >= 0) continue;
50
+ target[key] = source[key];
51
+ }
52
+
53
+ return target;
54
+ }
55
+
56
+ function getPath(error) {
57
+ return core.getValue(error, "dataPath", core.getValue(error, "instancePath", "")).replace(/\//gi, ".");
58
+ }
59
+
60
+ function defaultErrorFormatter(error) {
61
+ const value = JSON.stringify(error.data === undefined ? "undefined" : error.data);
62
+
63
+ const join = list => list.filter(Boolean).join("").trim();
64
+
65
+ error.dataPath = getPath(error);
66
+ const [, indexPath, ...paths] = error.dataPath.split(".");
67
+ const deepPaths = paths.length ? "." + paths.join(".") : "";
68
+
69
+ if (error.collectionName) {
70
+ switch (error.collectionName) {
71
+ case "Array":
72
+ return join([`${error.modelName || ""}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
73
+
74
+ case "Map":
75
+ return join([`Map<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
76
+
77
+ case "Set":
78
+ return join([`Set<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
79
+ }
80
+ }
81
+
82
+ return join([!error.modelName && "Value", `${error.modelName || ""}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);
83
+ }
84
+
85
+ const _excluded$1 = ["errorFormatter", "keywords"];
86
+
87
+ function getHandler(key, service) {
88
+ if (service[key]) {
89
+ return service[key].bind(service);
90
+ }
91
+ }
92
+
93
+ function getKeywordProviders(injector) {
94
+ return injector.getProviders("ajv:keyword");
95
+ }
96
+
97
+ function bindKeywords(injector) {
98
+ return getKeywordProviders(injector).map(provider => {
99
+ const options = provider.store.get("ajv:keyword", {});
100
+ const service = injector.invoke(provider.token);
101
+ return core.cleanObject(_extends({}, options, {
102
+ validate: getHandler("validate", service),
103
+ compile: getHandler("compile", service),
104
+ code: getHandler("code", service),
105
+ macro: getHandler("macro", service)
106
+ }));
107
+ });
108
+ }
109
+
110
+ function getFormatsProviders(injector) {
111
+ return injector.getProviders("ajv:formats");
112
+ }
113
+
114
+ function getFormats(injector) {
115
+ return getFormatsProviders(injector).map(provider => {
116
+ var _service$compare;
117
+
118
+ const {
119
+ name,
120
+ options
121
+ } = provider.store.get("ajv:formats", {});
122
+ const service = injector.invoke(provider.token);
123
+ return {
124
+ name,
125
+ options: _extends({}, options, {
126
+ validate: service.validate.bind(service),
127
+ compare: (_service$compare = service.compare) == null ? void 0 : _service$compare.bind(service)
128
+ })
129
+ };
130
+ });
131
+ }
132
+
133
+ di.registerProvider({
134
+ provide: Ajv__default['default'],
135
+ deps: [di.Configuration, di.InjectorService],
136
+ scope: di.ProviderScope.SINGLETON,
137
+
138
+ useFactory(configuration, injector) {
139
+ const _ref = configuration.get("ajv") || {},
140
+ {
141
+ keywords = []
142
+ } = _ref,
143
+ props = _objectWithoutPropertiesLoose(_ref, _excluded$1);
144
+
145
+ const options = _extends({
146
+ verbose: false,
147
+ coerceTypes: true,
148
+ strict: false,
149
+ keywords: [...keywords, ...bindKeywords(injector)]
150
+ }, props);
151
+
152
+ const ajv = new Ajv__default['default'](options);
153
+ AjvFormats__default['default'](ajv);
154
+ getFormats(injector).forEach(({
155
+ name,
156
+ options
157
+ }) => {
158
+ ajv.addFormat(name, options);
159
+ });
160
+ return ajv;
161
+ }
162
+
163
+ });
164
+
165
+ const _excluded = ["schema", "type", "collectionType"];
166
+ exports.AjvService = class AjvService {
167
+ async validate(value, options) {
168
+ let _this$mapOptions = this.mapOptions(options),
169
+ {
170
+ schema: schema$1,
171
+ type,
172
+ collectionType
173
+ } = _this$mapOptions,
174
+ additionalOptions = _objectWithoutPropertiesLoose(_this$mapOptions, _excluded);
175
+
176
+ schema$1 = schema$1 || schema.getJsonSchema(type, _extends({}, additionalOptions, {
177
+ customKeys: true
178
+ }));
179
+
180
+ if (schema$1) {
181
+ const localValue = core.deepClone(value);
182
+ const valid = await this.ajv.validate(schema$1, localValue);
183
+
184
+ if (!valid) {
185
+ throw this.mapErrors(this.ajv.errors || [], {
186
+ type,
187
+ collectionType,
188
+ async: true,
189
+ value: localValue
190
+ });
191
+ }
192
+ }
193
+
194
+ return value;
195
+ }
196
+
197
+ mapOptions(options) {
198
+ if (options instanceof schema.JsonSchema) {
199
+ return {
200
+ schema: options.toJSON({
201
+ customKeys: true
202
+ })
203
+ };
204
+ }
205
+
206
+ return options;
207
+ }
208
+
209
+ mapErrors(errors, options) {
210
+ const {
211
+ type,
212
+ collectionType,
213
+ value
214
+ } = options;
215
+ const message = errors.map(error => {
216
+ if (collectionType) {
217
+ error.collectionName = core.nameOf(collectionType);
218
+ }
219
+
220
+ const dataPath = getPath(error);
221
+
222
+ if (!error.data) {
223
+ if (dataPath) {
224
+ error.data = core.getValue(value, dataPath.replace(/^\./, ""));
225
+ } else if (error.schemaPath !== "#/required") {
226
+ error.data = value;
227
+ }
228
+ }
229
+
230
+ if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {
231
+ error.data = "[REDACTED]";
232
+ }
233
+
234
+ if (type) {
235
+ error.modelName = core.nameOf(type);
236
+ error.message = this.mapClassError(error, type);
237
+ }
238
+
239
+ return this.errorFormatter.call(this, error, {});
240
+ }).join("\n");
241
+ return new AjvValidationError(message, errors);
242
+ }
243
+
244
+ mapClassError(error, targetType) {
245
+ const propertyKey = core.getValue(error, "params.missingProperty");
246
+
247
+ if (propertyKey) {
248
+ const store = schema.JsonEntityStore.from(core.prototypeOf(targetType), propertyKey);
249
+
250
+ if (store) {
251
+ core.setValue(error, "params.missingProperty", store.name || propertyKey);
252
+ return error.message.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);
253
+ }
254
+ }
255
+
256
+ return error.message;
257
+ }
258
+
259
+ };
260
+
261
+ tslib.__decorate([di.Constant("ajv.errorFormatter", defaultErrorFormatter), tslib.__metadata("design:type", Function)], exports.AjvService.prototype, "errorFormatter", void 0);
262
+
263
+ tslib.__decorate([di.Inject(), tslib.__metadata("design:type", Ajv__default['default'])], exports.AjvService.prototype, "ajv", void 0);
264
+
265
+ exports.AjvService = tslib.__decorate([di.Injectable()], exports.AjvService);
266
+
267
+ /**
268
+ * Create new keyword custom validator
269
+ * @param options
270
+ * @decorator
271
+ * @ajv
272
+ */
273
+
274
+ function Keyword(options) {
275
+ return core.useDecorators(di.Injectable({
276
+ type: "ajv:keyword"
277
+ }), core.StoreSet("ajv:keyword", _extends({}, options, {
278
+ metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema
279
+ })));
280
+ }
281
+
282
+ /**
283
+ * Create a new custom formats validator
284
+ * @param name
285
+ * @param options
286
+ * @decorator
287
+ * @ajv
288
+ */
289
+
290
+ function Formats(name, options = {}) {
291
+ return core.useDecorators(di.Injectable({
292
+ type: "ajv:formats"
293
+ }), core.StoreSet("ajv:formats", {
294
+ name,
295
+ options
296
+ }));
297
+ }
298
+
299
+ exports.AjvValidationError = AjvValidationError;
300
+ exports.Formats = Formats;
301
+ exports.Keyword = Keyword;
302
+ //# sourceMappingURL=index.js.map
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,sEAA4C;AAC5C,gEAAsC;AACtC,yDAA+B;AAC/B,+DAAqC;AACrC,sEAA4C;AAC5C,+DAAqC;AACrC,sEAA4C","sourcesContent":["export * from \"./errors/AjvValidationError\";\nexport * from \"./services/AjvService\";\nexport * from \"./services/Ajv\";\nexport * from \"./decorators/keyword\";\nexport * from \"./interfaces/KeywordMethods\";\nexport * from \"./decorators/formats\";\nexport * from \"./interfaces/FormatsMethods\";\n\nimport {IAjvSettings} from \"./interfaces/IAjvSettings\";\n\ndeclare global {\n namespace TsED {\n interface Configuration {\n // @ts-ignore\n ajv?: IAjvSettings;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sources":["../src/errors/AjvValidationError.ts","../src/utils/getPath.ts","../src/utils/defaultErrorFormatter.ts","../src/services/Ajv.ts","../src/services/AjvService.ts","../src/decorators/keyword.ts","../src/decorators/formats.ts"],"sourcesContent":["import {BadRequest} from \"@tsed/exceptions\";\n\nexport class AjvValidationError extends BadRequest {\n public name: string = \"AJV_VALIDATION_ERROR\";\n public errors: any[];\n\n constructor(message: string, errors: any[] = []) {\n super(message);\n this.errors = errors;\n }\n}\n","import {getValue} from \"@tsed/core\";\n\nexport function getPath(error: any) {\n return getValue(error, \"dataPath\", getValue(error, \"instancePath\", \"\")).replace(/\\//gi, \".\");\n}\n","import {AjvErrorObject} from \"../interfaces/IAjvSettings\";\nimport {getPath} from \"./getPath\";\n\nexport function defaultErrorFormatter(error: AjvErrorObject & {dataPath: string}) {\n const value = JSON.stringify(error.data === undefined ? \"undefined\" : error.data);\n const join = (list: any[]): string => list.filter(Boolean).join(\"\").trim();\n\n error.dataPath = getPath(error);\n\n const [, indexPath, ...paths] = error.dataPath.split(\".\");\n const deepPaths = paths.length ? \".\" + paths.join(\".\") : \"\";\n\n if (error.collectionName) {\n switch (error.collectionName) {\n case \"Array\":\n return join([`${error.modelName || \"\"}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Map\":\n return join([`Map<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Set\":\n return join([`Set<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n }\n }\n\n return join([!error.modelName && \"Value\", `${error.modelName || \"\"}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);\n}\n","import {cleanObject} from \"@tsed/core\";\nimport {Configuration, InjectorService, ProviderScope, registerProvider} from \"@tsed/di\";\nimport Ajv, {Format, KeywordDefinition, Vocabulary} from \"ajv\";\nimport AjvFormats from \"ajv-formats\";\nimport {FormatsMethods} from \"../interfaces/FormatsMethods\";\nimport {IAjvSettings} from \"../interfaces/IAjvSettings\";\n\nfunction getHandler(key: string, service: any) {\n if (service[key]) {\n return service[key].bind(service);\n }\n}\n\nfunction getKeywordProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:keyword\");\n}\n\nfunction bindKeywords(injector: InjectorService): Vocabulary {\n return getKeywordProviders(injector).map((provider) => {\n const options = provider.store.get<Omit<KeywordDefinition, \"compile\">>(\"ajv:keyword\", {})!;\n const service = injector.invoke(provider.token);\n\n return <KeywordDefinition>cleanObject({\n ...options,\n validate: getHandler(\"validate\", service),\n compile: getHandler(\"compile\", service),\n code: getHandler(\"code\", service),\n macro: getHandler(\"macro\", service)\n });\n });\n}\n\nfunction getFormatsProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:formats\");\n}\n\nfunction getFormats(injector: InjectorService): {name: string; options: Format}[] {\n return getFormatsProviders(injector).map((provider) => {\n const {name, options} = provider.store.get<any>(\"ajv:formats\", {})!;\n const service = injector.invoke<FormatsMethods<any>>(provider.token);\n\n return {\n name,\n options: {\n ...options,\n validate: service.validate.bind(service),\n compare: service.compare?.bind(service)\n }\n };\n });\n}\n\nregisterProvider({\n provide: Ajv,\n deps: [Configuration, InjectorService],\n scope: ProviderScope.SINGLETON,\n useFactory(configuration: Configuration, injector: InjectorService) {\n const {errorFormatter, keywords = [], ...props} = configuration.get<IAjvSettings>(\"ajv\") || {};\n const options = {\n verbose: false,\n coerceTypes: true,\n strict: false,\n keywords: [...keywords, ...bindKeywords(injector)],\n ...props\n };\n\n const ajv = new Ajv(options);\n\n AjvFormats(ajv as any);\n\n getFormats(injector).forEach(({name, options}) => {\n ajv.addFormat(name, options);\n });\n\n return ajv;\n }\n});\n","import {deepClone, getValue, nameOf, prototypeOf, setValue, Type} from \"@tsed/core\";\nimport {Constant, Inject, Injectable} from \"@tsed/di\";\nimport {getJsonSchema, JsonEntityStore, JsonSchema, JsonSchemaObject} from \"@tsed/schema\";\nimport Ajv, {ErrorObject} from \"ajv\";\nimport {AjvValidationError} from \"../errors/AjvValidationError\";\nimport {AjvErrorObject, ErrorFormatter} from \"../interfaces/IAjvSettings\";\nimport {defaultErrorFormatter} from \"../utils/defaultErrorFormatter\";\nimport \"./Ajv\";\nimport {getPath} from \"../utils/getPath\";\n\nexport interface AjvValidateOptions extends Record<string, any> {\n schema?: JsonSchema | Partial<JsonSchemaObject>;\n type?: Type<any> | any;\n collectionType?: Type<any> | any;\n}\n\n@Injectable()\nexport class AjvService {\n @Constant(\"ajv.errorFormatter\", defaultErrorFormatter)\n protected errorFormatter: ErrorFormatter;\n\n @Inject()\n protected ajv: Ajv;\n\n async validate(value: any, options: AjvValidateOptions | JsonSchema): Promise<any> {\n let {schema, type, collectionType, ...additionalOptions} = this.mapOptions(options);\n\n schema = schema || getJsonSchema(type, {...additionalOptions, customKeys: true});\n\n if (schema) {\n const localValue = deepClone(value);\n const valid = await this.ajv.validate(schema as any, localValue);\n if (!valid) {\n throw this.mapErrors(this.ajv.errors || [], {\n type,\n collectionType,\n async: true,\n value: localValue\n });\n }\n }\n\n return value;\n }\n\n protected mapOptions(options: AjvValidateOptions | JsonSchema): AjvValidateOptions {\n if (options instanceof JsonSchema) {\n return {\n schema: options.toJSON({customKeys: true})\n };\n }\n\n return options;\n }\n\n protected mapErrors(errors: ErrorObject[], options: any) {\n const {type, collectionType, value} = options;\n\n const message = errors\n .map((error: AjvErrorObject) => {\n if (collectionType) {\n error.collectionName = nameOf(collectionType);\n }\n\n const dataPath = getPath(error);\n\n if (!error.data) {\n if (dataPath) {\n error.data = getValue(value, dataPath.replace(/^\\./, \"\"));\n } else if (error.schemaPath !== \"#/required\") {\n error.data = value;\n }\n }\n\n if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {\n error.data = \"[REDACTED]\";\n }\n\n if (type) {\n error.modelName = nameOf(type);\n error.message = this.mapClassError(error, type);\n }\n\n return this.errorFormatter.call(this, error, {});\n })\n .join(\"\\n\");\n\n return new AjvValidationError(message, errors);\n }\n\n protected mapClassError(error: AjvErrorObject, targetType: Type<any>) {\n const propertyKey = getValue(error, \"params.missingProperty\");\n\n if (propertyKey) {\n const store = JsonEntityStore.from<JsonEntityStore>(prototypeOf(targetType), propertyKey);\n\n if (store) {\n setValue(error, \"params.missingProperty\", store.name || propertyKey);\n\n return error.message!.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);\n }\n }\n\n return error.message;\n }\n}\n","import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, KeywordDefinition} from \"ajv\";\n\nexport type KeywordOptions = Partial<Omit<KeywordDefinition, \"metaSchema\">> & {\n metaSchema?: AnySchemaObject | JsonSchema;\n};\n\n/**\n * Create new keyword custom validator\n * @param options\n * @decorator\n * @ajv\n */\nexport function Keyword(options: KeywordOptions): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:keyword\"\n }),\n StoreSet(\"ajv:keyword\", {\n ...options,\n metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema\n })\n );\n}\n","import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, AsyncFormatDefinition, FormatDefinition, KeywordDefinition} from \"ajv\";\nexport type FormatsOptions = Omit<FormatDefinition<any>, \"validate\" | \"compare\"> | Omit<AsyncFormatDefinition<any>, \"validate\" | \"compare\">;\n/**\n * Create a new custom formats validator\n * @param name\n * @param options\n * @decorator\n * @ajv\n */\nexport function Formats(name: string, options: FormatsOptions = {}): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:formats\"\n }),\n StoreSet(\"ajv:formats\", {\n name,\n options\n })\n );\n}\n"],"names":["AjvValidationError","BadRequest","constructor","message","errors","getPath","error","getValue","replace","defaultErrorFormatter","value","JSON","stringify","data","undefined","join","list","filter","Boolean","trim","dataPath","indexPath","paths","split","deepPaths","length","collectionName","modelName","getHandler","key","service","bind","getKeywordProviders","injector","getProviders","bindKeywords","map","provider","options","store","get","invoke","token","cleanObject","validate","compile","code","macro","getFormatsProviders","getFormats","name","compare","registerProvider","provide","Ajv","deps","Configuration","InjectorService","scope","ProviderScope","SINGLETON","useFactory","configuration","keywords","props","verbose","coerceTypes","strict","ajv","AjvFormats","forEach","addFormat","AjvService","mapOptions","schema","type","collectionType","additionalOptions","getJsonSchema","customKeys","localValue","deepClone","valid","mapErrors","async","JsonSchema","toJSON","nameOf","schemaPath","match","mapClassError","errorFormatter","call","targetType","propertyKey","JsonEntityStore","from","prototypeOf","setValue","__decorate","Constant","Inject","Injectable","Keyword","useDecorators","StoreSet","metaSchema","Formats"],"mappings":";;;;;;;;;;;;;MAEaA,2BAA2BC;AAItCC,EAAAA,YAAYC,SAAiBC,SAAgB;AAC3C,UAAMD,OAAN;AAJK,aAAA,GAAe,sBAAf;AAKL,SAAKC,MAAL,GAAcA,MAAd;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SCPaC,QAAQC;AACtB,SAAOC,aAAQ,CAACD,KAAD,EAAQ,UAAR,EAAoBC,aAAQ,CAACD,KAAD,EAAQ,cAAR,EAAwB,EAAxB,CAA5B,CAAR,CAAiEE,OAAjE,CAAyE,MAAzE,EAAiF,GAAjF,CAAP;AACD;;SCDeC,sBAAsBH;AACpC,QAAMI,KAAK,GAAGC,IAAI,CAACC,SAAL,CAAeN,KAAK,CAACO,IAAN,KAAeC,SAAf,GAA2B,WAA3B,GAAyCR,KAAK,CAACO,IAA9D,CAAd;;AACA,QAAME,IAAI,GAAIC,IAAD,IAAyBA,IAAI,CAACC,MAAL,CAAYC,OAAZ,EAAqBH,IAArB,CAA0B,EAA1B,EAA8BI,IAA9B,EAAtC;;AAEAb,EAAAA,KAAK,CAACc,QAAN,GAAiBf,OAAO,CAACC,KAAD,CAAxB;AAEA,QAAM,GAAGe,SAAH,E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N,IAAc4C,cAA7D,CAAP;AACD;AACF;;AAED,WAAOxF,KAAK,CAACH,OAAb;AACD;;;;AArFDgG,kBADCC,WAAQ,CAAC,oBAAD,EAAuB3F,qBAAvB,sGACT;;AAGA0F,kBADCE,SAAM,oCACQ/C,uEAAf;;AALWkB,kBAAU,qBADtB8B,aAAU,KACE9B,mBAAA;;ACRb;;;;;;;SAMgB+B,QAAQjE;AACtB,SAAOkE,kBAAa,CAClBF,aAAU,CAAC;AACT3B,IAAAA,IAAI,EAAE;AADG,GAAD,CADQ,EAIlB8B,aAAQ,CAAC,aAAD,eACHnE,OADG;AAENoE,IAAAA,UAAU,EAAEpE,OAAO,CAACoE,UAAR,IAAsBpE,OAAO,CAACoE,UAAR,CAAmBpB,MAAzC,GAAkDhD,OAAO,CAACoE,UAAR,CAAmBpB,MAAnB,EAAlD,GAAgFhD,OAAO,CAACoE;AAF9F,KAJU,CAApB;AASD;;ACpBD;;;;;;;;SAOgBC,QAAQzD,MAAcZ,UAA0B;AAC9D,SAAOkE,kBAAa,CAClBF,aAAU,CAAC;AACT3B,IAAAA,IAAI,EAAE;AADG,GAAD,CADQ,EAIlB8B,aAAQ,CAAC,aAAD,EAAgB;AACtBvD,IAAAA,IADsB;AAEtBZ,IAAAA;AAFsB,GAAhB,CAJU,CAApB;AASD;;;;;;"}
@@ -0,0 +1,295 @@
1
+ import { BadRequest } from '@tsed/exceptions';
2
+ import { __decorate, __metadata } from 'tslib';
3
+ import { getValue, cleanObject, deepClone, nameOf, prototypeOf, setValue, useDecorators, StoreSet } from '@tsed/core';
4
+ import { registerProvider, Configuration, InjectorService, ProviderScope, Constant, Inject, Injectable } from '@tsed/di';
5
+ import { getJsonSchema, JsonSchema, JsonEntityStore } from '@tsed/schema';
6
+ import Ajv from 'ajv';
7
+ import AjvFormats from 'ajv-formats';
8
+
9
+ class AjvValidationError extends BadRequest {
10
+ constructor(message, errors = []) {
11
+ super(message);
12
+ this.name = "AJV_VALIDATION_ERROR";
13
+ this.errors = errors;
14
+ }
15
+
16
+ }
17
+
18
+ function _extends() {
19
+ _extends = Object.assign || function (target) {
20
+ for (var i = 1; i < arguments.length; i++) {
21
+ var source = arguments[i];
22
+
23
+ for (var key in source) {
24
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
25
+ target[key] = source[key];
26
+ }
27
+ }
28
+ }
29
+
30
+ return target;
31
+ };
32
+
33
+ return _extends.apply(this, arguments);
34
+ }
35
+
36
+ function _objectWithoutPropertiesLoose(source, excluded) {
37
+ if (source == null) return {};
38
+ var target = {};
39
+ var sourceKeys = Object.keys(source);
40
+ var key, i;
41
+
42
+ for (i = 0; i < sourceKeys.length; i++) {
43
+ key = sourceKeys[i];
44
+ if (excluded.indexOf(key) >= 0) continue;
45
+ target[key] = source[key];
46
+ }
47
+
48
+ return target;
49
+ }
50
+
51
+ function getPath(error) {
52
+ return getValue(error, "dataPath", getValue(error, "instancePath", "")).replace(/\//gi, ".");
53
+ }
54
+
55
+ function defaultErrorFormatter(error) {
56
+ const value = JSON.stringify(error.data === undefined ? "undefined" : error.data);
57
+
58
+ const join = list => list.filter(Boolean).join("").trim();
59
+
60
+ error.dataPath = getPath(error);
61
+ const [, indexPath, ...paths] = error.dataPath.split(".");
62
+ const deepPaths = paths.length ? "." + paths.join(".") : "";
63
+
64
+ if (error.collectionName) {
65
+ switch (error.collectionName) {
66
+ case "Array":
67
+ return join([`${error.modelName || ""}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
68
+
69
+ case "Map":
70
+ return join([`Map<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
71
+
72
+ case "Set":
73
+ return join([`Set<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
74
+ }
75
+ }
76
+
77
+ return join([!error.modelName && "Value", `${error.modelName || ""}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);
78
+ }
79
+
80
+ const _excluded$1 = ["errorFormatter", "keywords"];
81
+
82
+ function getHandler(key, service) {
83
+ if (service[key]) {
84
+ return service[key].bind(service);
85
+ }
86
+ }
87
+
88
+ function getKeywordProviders(injector) {
89
+ return injector.getProviders("ajv:keyword");
90
+ }
91
+
92
+ function bindKeywords(injector) {
93
+ return getKeywordProviders(injector).map(provider => {
94
+ const options = provider.store.get("ajv:keyword", {});
95
+ const service = injector.invoke(provider.token);
96
+ return cleanObject(_extends({}, options, {
97
+ validate: getHandler("validate", service),
98
+ compile: getHandler("compile", service),
99
+ code: getHandler("code", service),
100
+ macro: getHandler("macro", service)
101
+ }));
102
+ });
103
+ }
104
+
105
+ function getFormatsProviders(injector) {
106
+ return injector.getProviders("ajv:formats");
107
+ }
108
+
109
+ function getFormats(injector) {
110
+ return getFormatsProviders(injector).map(provider => {
111
+ var _service$compare;
112
+
113
+ const {
114
+ name,
115
+ options
116
+ } = provider.store.get("ajv:formats", {});
117
+ const service = injector.invoke(provider.token);
118
+ return {
119
+ name,
120
+ options: _extends({}, options, {
121
+ validate: service.validate.bind(service),
122
+ compare: (_service$compare = service.compare) == null ? void 0 : _service$compare.bind(service)
123
+ })
124
+ };
125
+ });
126
+ }
127
+
128
+ registerProvider({
129
+ provide: Ajv,
130
+ deps: [Configuration, InjectorService],
131
+ scope: ProviderScope.SINGLETON,
132
+
133
+ useFactory(configuration, injector) {
134
+ const _ref = configuration.get("ajv") || {},
135
+ {
136
+ keywords = []
137
+ } = _ref,
138
+ props = _objectWithoutPropertiesLoose(_ref, _excluded$1);
139
+
140
+ const options = _extends({
141
+ verbose: false,
142
+ coerceTypes: true,
143
+ strict: false,
144
+ keywords: [...keywords, ...bindKeywords(injector)]
145
+ }, props);
146
+
147
+ const ajv = new Ajv(options);
148
+ AjvFormats(ajv);
149
+ getFormats(injector).forEach(({
150
+ name,
151
+ options
152
+ }) => {
153
+ ajv.addFormat(name, options);
154
+ });
155
+ return ajv;
156
+ }
157
+
158
+ });
159
+
160
+ const _excluded = ["schema", "type", "collectionType"];
161
+ let AjvService = class AjvService {
162
+ async validate(value, options) {
163
+ let _this$mapOptions = this.mapOptions(options),
164
+ {
165
+ schema,
166
+ type,
167
+ collectionType
168
+ } = _this$mapOptions,
169
+ additionalOptions = _objectWithoutPropertiesLoose(_this$mapOptions, _excluded);
170
+
171
+ schema = schema || getJsonSchema(type, _extends({}, additionalOptions, {
172
+ customKeys: true
173
+ }));
174
+
175
+ if (schema) {
176
+ const localValue = deepClone(value);
177
+ const valid = await this.ajv.validate(schema, localValue);
178
+
179
+ if (!valid) {
180
+ throw this.mapErrors(this.ajv.errors || [], {
181
+ type,
182
+ collectionType,
183
+ async: true,
184
+ value: localValue
185
+ });
186
+ }
187
+ }
188
+
189
+ return value;
190
+ }
191
+
192
+ mapOptions(options) {
193
+ if (options instanceof JsonSchema) {
194
+ return {
195
+ schema: options.toJSON({
196
+ customKeys: true
197
+ })
198
+ };
199
+ }
200
+
201
+ return options;
202
+ }
203
+
204
+ mapErrors(errors, options) {
205
+ const {
206
+ type,
207
+ collectionType,
208
+ value
209
+ } = options;
210
+ const message = errors.map(error => {
211
+ if (collectionType) {
212
+ error.collectionName = nameOf(collectionType);
213
+ }
214
+
215
+ const dataPath = getPath(error);
216
+
217
+ if (!error.data) {
218
+ if (dataPath) {
219
+ error.data = getValue(value, dataPath.replace(/^\./, ""));
220
+ } else if (error.schemaPath !== "#/required") {
221
+ error.data = value;
222
+ }
223
+ }
224
+
225
+ if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {
226
+ error.data = "[REDACTED]";
227
+ }
228
+
229
+ if (type) {
230
+ error.modelName = nameOf(type);
231
+ error.message = this.mapClassError(error, type);
232
+ }
233
+
234
+ return this.errorFormatter.call(this, error, {});
235
+ }).join("\n");
236
+ return new AjvValidationError(message, errors);
237
+ }
238
+
239
+ mapClassError(error, targetType) {
240
+ const propertyKey = getValue(error, "params.missingProperty");
241
+
242
+ if (propertyKey) {
243
+ const store = JsonEntityStore.from(prototypeOf(targetType), propertyKey);
244
+
245
+ if (store) {
246
+ setValue(error, "params.missingProperty", store.name || propertyKey);
247
+ return error.message.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);
248
+ }
249
+ }
250
+
251
+ return error.message;
252
+ }
253
+
254
+ };
255
+
256
+ __decorate([Constant("ajv.errorFormatter", defaultErrorFormatter), __metadata("design:type", Function)], AjvService.prototype, "errorFormatter", void 0);
257
+
258
+ __decorate([Inject(), __metadata("design:type", Ajv)], AjvService.prototype, "ajv", void 0);
259
+
260
+ AjvService = __decorate([Injectable()], AjvService);
261
+
262
+ /**
263
+ * Create new keyword custom validator
264
+ * @param options
265
+ * @decorator
266
+ * @ajv
267
+ */
268
+
269
+ function Keyword(options) {
270
+ return useDecorators(Injectable({
271
+ type: "ajv:keyword"
272
+ }), StoreSet("ajv:keyword", _extends({}, options, {
273
+ metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema
274
+ })));
275
+ }
276
+
277
+ /**
278
+ * Create a new custom formats validator
279
+ * @param name
280
+ * @param options
281
+ * @decorator
282
+ * @ajv
283
+ */
284
+
285
+ function Formats(name, options = {}) {
286
+ return useDecorators(Injectable({
287
+ type: "ajv:formats"
288
+ }), StoreSet("ajv:formats", {
289
+ name,
290
+ options
291
+ }));
292
+ }
293
+
294
+ export { AjvService, AjvValidationError, Formats, Keyword };
295
+ //# sourceMappingURL=index.modern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.modern.js","sources":["../src/errors/AjvValidationError.ts","../src/utils/getPath.ts","../src/utils/defaultErrorFormatter.ts","../src/services/Ajv.ts","../src/services/AjvService.ts","../src/decorators/keyword.ts","../src/decorators/formats.ts"],"sourcesContent":["import {BadRequest} from \"@tsed/exceptions\";\n\nexport class AjvValidationError extends BadRequest {\n public name: string = \"AJV_VALIDATION_ERROR\";\n public errors: any[];\n\n constructor(message: string, errors: any[] = []) {\n super(message);\n this.errors = errors;\n }\n}\n","import {getValue} from \"@tsed/core\";\n\nexport function getPath(error: any) {\n return getValue(error, \"dataPath\", getValue(error, \"instancePath\", \"\")).replace(/\\//gi, \".\");\n}\n","import {AjvErrorObject} from \"../interfaces/IAjvSettings\";\nimport {getPath} from \"./getPath\";\n\nexport function defaultErrorFormatter(error: AjvErrorObject & {dataPath: string}) {\n const value = JSON.stringify(error.data === undefined ? \"undefined\" : error.data);\n const join = (list: any[]): string => list.filter(Boolean).join(\"\").trim();\n\n error.dataPath = getPath(error);\n\n const [, indexPath, ...paths] = error.dataPath.split(\".\");\n const deepPaths = paths.length ? \".\" + paths.join(\".\") : \"\";\n\n if (error.collectionName) {\n switch (error.collectionName) {\n case \"Array\":\n return join([`${error.modelName || \"\"}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Map\":\n return join([`Map<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Set\":\n return join([`Set<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n }\n }\n\n return join([!error.modelName && \"Value\", `${error.modelName || \"\"}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);\n}\n","import {cleanObject} from \"@tsed/core\";\nimport {Configuration, InjectorService, ProviderScope, registerProvider} from \"@tsed/di\";\nimport Ajv, {Format, KeywordDefinition, Vocabulary} from \"ajv\";\nimport AjvFormats from \"ajv-formats\";\nimport {FormatsMethods} from \"../interfaces/FormatsMethods\";\nimport {IAjvSettings} from \"../interfaces/IAjvSettings\";\n\nfunction getHandler(key: string, service: any) {\n if (service[key]) {\n return service[key].bind(service);\n }\n}\n\nfunction getKeywordProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:keyword\");\n}\n\nfunction bindKeywords(injector: InjectorService): Vocabulary {\n return getKeywordProviders(injector).map((provider) => {\n const options = provider.store.get<Omit<KeywordDefinition, \"compile\">>(\"ajv:keyword\", {})!;\n const service = injector.invoke(provider.token);\n\n return <KeywordDefinition>cleanObject({\n ...options,\n validate: getHandler(\"validate\", service),\n compile: getHandler(\"compile\", service),\n code: getHandler(\"code\", service),\n macro: getHandler(\"macro\", service)\n });\n });\n}\n\nfunction getFormatsProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:formats\");\n}\n\nfunction getFormats(injector: InjectorService): {name: string; options: Format}[] {\n return getFormatsProviders(injector).map((provider) => {\n const {name, options} = provider.store.get<any>(\"ajv:formats\", {})!;\n const service = injector.invoke<FormatsMethods<any>>(provider.token);\n\n return {\n name,\n options: {\n ...options,\n validate: service.validate.bind(service),\n compare: service.compare?.bind(service)\n }\n };\n });\n}\n\nregisterProvider({\n provide: Ajv,\n deps: [Configuration, InjectorService],\n scope: ProviderScope.SINGLETON,\n useFactory(configuration: Configuration, injector: InjectorService) {\n const {errorFormatter, keywords = [], ...props} = configuration.get<IAjvSettings>(\"ajv\") || {};\n const options = {\n verbose: false,\n coerceTypes: true,\n strict: false,\n keywords: [...keywords, ...bindKeywords(injector)],\n ...props\n };\n\n const ajv = new Ajv(options);\n\n AjvFormats(ajv as any);\n\n getFormats(injector).forEach(({name, options}) => {\n ajv.addFormat(name, options);\n });\n\n return ajv;\n }\n});\n","import {deepClone, getValue, nameOf, prototypeOf, setValue, Type} from \"@tsed/core\";\nimport {Constant, Inject, Injectable} from \"@tsed/di\";\nimport {getJsonSchema, JsonEntityStore, JsonSchema, JsonSchemaObject} from \"@tsed/schema\";\nimport Ajv, {ErrorObject} from \"ajv\";\nimport {AjvValidationError} from \"../errors/AjvValidationError\";\nimport {AjvErrorObject, ErrorFormatter} from \"../interfaces/IAjvSettings\";\nimport {defaultErrorFormatter} from \"../utils/defaultErrorFormatter\";\nimport \"./Ajv\";\nimport {getPath} from \"../utils/getPath\";\n\nexport interface AjvValidateOptions extends Record<string, any> {\n schema?: JsonSchema | Partial<JsonSchemaObject>;\n type?: Type<any> | any;\n collectionType?: Type<any> | any;\n}\n\n@Injectable()\nexport class AjvService {\n @Constant(\"ajv.errorFormatter\", defaultErrorFormatter)\n protected errorFormatter: ErrorFormatter;\n\n @Inject()\n protected ajv: Ajv;\n\n async validate(value: any, options: AjvValidateOptions | JsonSchema): Promise<any> {\n let {schema, type, collectionType, ...additionalOptions} = this.mapOptions(options);\n\n schema = schema || getJsonSchema(type, {...additionalOptions, customKeys: true});\n\n if (schema) {\n const localValue = deepClone(value);\n const valid = await this.ajv.validate(schema as any, localValue);\n if (!valid) {\n throw this.mapErrors(this.ajv.errors || [], {\n type,\n collectionType,\n async: true,\n value: localValue\n });\n }\n }\n\n return value;\n }\n\n protected mapOptions(options: AjvValidateOptions | JsonSchema): AjvValidateOptions {\n if (options instanceof JsonSchema) {\n return {\n schema: options.toJSON({customKeys: true})\n };\n }\n\n return options;\n }\n\n protected mapErrors(errors: ErrorObject[], options: any) {\n const {type, collectionType, value} = options;\n\n const message = errors\n .map((error: AjvErrorObject) => {\n if (collectionType) {\n error.collectionName = nameOf(collectionType);\n }\n\n const dataPath = getPath(error);\n\n if (!error.data) {\n if (dataPath) {\n error.data = getValue(value, dataPath.replace(/^\\./, \"\"));\n } else if (error.schemaPath !== \"#/required\") {\n error.data = value;\n }\n }\n\n if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {\n error.data = \"[REDACTED]\";\n }\n\n if (type) {\n error.modelName = nameOf(type);\n error.message = this.mapClassError(error, type);\n }\n\n return this.errorFormatter.call(this, error, {});\n })\n .join(\"\\n\");\n\n return new AjvValidationError(message, errors);\n }\n\n protected mapClassError(error: AjvErrorObject, targetType: Type<any>) {\n const propertyKey = getValue(error, \"params.missingProperty\");\n\n if (propertyKey) {\n const store = JsonEntityStore.from<JsonEntityStore>(prototypeOf(targetType), propertyKey);\n\n if (store) {\n setValue(error, \"params.missingProperty\", store.name || propertyKey);\n\n return error.message!.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);\n }\n }\n\n return error.message;\n }\n}\n","import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, KeywordDefinition} from \"ajv\";\n\nexport type KeywordOptions = Partial<Omit<KeywordDefinition, \"metaSchema\">> & {\n metaSchema?: AnySchemaObject | JsonSchema;\n};\n\n/**\n * Create new keyword custom validator\n * @param options\n * @decorator\n * @ajv\n */\nexport function Keyword(options: KeywordOptions): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:keyword\"\n }),\n StoreSet(\"ajv:keyword\", {\n ...options,\n metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema\n })\n );\n}\n","import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, AsyncFormatDefinition, FormatDefinition, KeywordDefinition} from \"ajv\";\nexport type FormatsOptions = Omit<FormatDefinition<any>, \"validate\" | \"compare\"> | Omit<AsyncFormatDefinition<any>, \"validate\" | \"compare\">;\n/**\n * Create a new custom formats validator\n * @param name\n * @param options\n * @decorator\n * @ajv\n */\nexport function Formats(name: string, options: FormatsOptions = {}): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:formats\"\n }),\n StoreSet(\"ajv:formats\", {\n name,\n options\n })\n );\n}\n"],"names":["AjvValidationError","BadRequest","constructor","message","errors","getPath","error","getValue","replace","defaultErrorFormatter","value","JSON","stringify","data","undefined","join","list","filter","Boolean","trim","dataPath","indexPath","paths","split","deepPaths","length","collectionName","modelName","getHandler","key","service","bind","getKeywordProviders","injector","getProviders","bindKeywords","map","provider","options","store","get","invoke","token","cleanObject","validate","compile","code","macro","getFormatsProviders","getFormats","name","compare","registerProvider","provide","Ajv","deps","Configuration","InjectorService","scope","ProviderScope","SINGLETON","useFactory","configuration","keywords","props","verbose","coerceTypes","strict","ajv","AjvFormats","forEach","addFormat","AjvService","mapOptions","schema","type","collectionType","additionalOptions","getJsonSchema","customKeys","localValue","deepClone","valid","mapErrors","async","JsonSchema","toJSON","nameOf","schemaPath","match","mapClassError","errorFormatter","call","targetType","propertyKey","JsonEntityStore","from","prototypeOf","setValue","__decorate","Constant","Inject","Injectable","Keyword","useDecorators","StoreSet","metaSchema","Formats"],"mappings":";;;;;;;;MAEaA,2BAA2BC;AAItCC,EAAAA,YAAYC,SAAiBC,SAAgB;AAC3C,UAAMD,OAAN;AAJK,aAAA,GAAe,sBAAf;AAKL,SAAKC,MAAL,GAAcA,MAAd;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SCPaC,QAAQC;AACtB,SAAOC,QAAQ,CAACD,KAAD,EAAQ,UAAR,EAAoBC,QAAQ,CAACD,KAAD,EAAQ,cAAR,EAAwB,EAAxB,CAA5B,CAAR,CAAiEE,OAAjE,CAAyE,MAAzE,EAAiF,GAAjF,CAAP;AACD;;SCDeC,sBAAsBH;AACpC,QAAMI,KAAK,GAAGC,IAAI,CAACC,SAAL,CAAeN,KAAK,CAACO,IAAN,KAAeC,SAAf,GAA2B,WAA3B,GAAyCR,KAAK,CAACO,IAA9D,CAAd;;AACA,QAAME,IAAI,GAAIC,IAAD,IAAyBA,IAAI,CAACC,MAAL,CAAYC,OAAZ,EAAqBH,IAArB,CAA0B,EAA1B,EAA8BI,IAA9B,EAAtC;;AAEAb,EAAAA,KAAK,CAACc,QAAN,GAAiBf,OAAO,CAACC,KAAD,CAAxB;AAEA,QAAM,GAAGe,SAAH,EAAc,GAAGC,KAAjB,IAA0BhB,KAAK,CAACc,QAAN,CAAeG,KAAf,CAAqB,GAArB,CAAhC;AACA,QAAMC,SAAS,GAAGF,KAAK,CAACG,MAAN,GAAe,MAAMH,KAAK,CAACP,IAAN,CAAW,GAAX,CAArB,GAAuC,EAAzD;;AAEA,MAAIT,KAAK,CAACoB,cAAV,EAA0B;AACxB,YAAQpB,KAAK,CAACoB,cAAd;AACE,WAAK,OAAL;AACE,eAAOX,IAAI,CAAC,IAAIT,KAAK,CAACqB,SAAN,IAAmB,MAAMN,aAAaG,WAA1C,MAA2DlB,KAAK,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U,EAAEpE,OAAO,CAACoE,UAAR,IAAsBpE,OAAO,CAACoE,UAAR,CAAmBpB,MAAzC,GAAkDhD,OAAO,CAACoE,UAAR,CAAmBpB,MAAnB,EAAlD,GAAgFhD,OAAO,CAACoE;AAF9F,KAJU,CAApB;AASD;;ACpBD;;;;;;;;SAOgBC,QAAQzD,MAAcZ,UAA0B;AAC9D,SAAOkE,aAAa,CAClBF,UAAU,CAAC;AACT3B,IAAAA,IAAI,EAAE;AADG,GAAD,CADQ,EAIlB8B,QAAQ,CAAC,aAAD,EAAgB;AACtBvD,IAAAA,IADsB;AAEtBZ,IAAAA;AAFsB,GAAhB,CAJU,CAApB;AASD;;;;"}
package/package.json CHANGED
@@ -1,38 +1,37 @@
1
1
  {
2
2
  "name": "@tsed/ajv",
3
- "version": "6.67.0",
3
+ "version": "6.68.3",
4
4
  "description": "AJV package for Ts.ED framework",
5
5
  "source": "./src/index.ts",
6
6
  "main": "./lib/index.js",
7
7
  "typings": "./lib/index.d.ts",
8
8
  "private": false,
9
9
  "scripts": {
10
- "build": "tsc --build tsconfig.compile.json",
11
- "tsc": "tsc --build tsconfig.check.json"
10
+ "build": "microbundle --target node --no-compress --format modern,cjs --tsconfig ./tsconfig.compile.json"
12
11
  },
13
12
  "dependencies": {
14
13
  "ajv-formats": "1.5.1",
15
14
  "tslib": "2.2.0"
16
15
  },
17
16
  "devDependencies": {
18
- "@tsed/core": "6.67.0",
19
- "@tsed/di": "6.67.0",
20
- "@tsed/exceptions": "6.67.0",
21
- "@tsed/schema": "6.67.0",
17
+ "@tsed/core": "6.68.3",
18
+ "@tsed/di": "6.68.3",
19
+ "@tsed/exceptions": "6.68.3",
20
+ "@tsed/schema": "6.68.3",
22
21
  "ajv": "8.6.0"
23
22
  },
24
23
  "peerDependencies": {
25
- "@tsed/core": "^6.18.0",
26
- "@tsed/di": "^6.18.0",
27
- "@tsed/exceptions": "^6.18.0",
28
- "@tsed/schema": "^6.18.0",
24
+ "@tsed/core": "^6.68.2",
25
+ "@tsed/di": "^6.68.2",
26
+ "@tsed/exceptions": "^6.68.2",
27
+ "@tsed/schema": "^6.68.2",
29
28
  "ajv": "7||8"
30
29
  },
31
30
  "repository": "https://github.com/tsedio/tsed",
32
31
  "bugs": {
33
32
  "url": "https://github.com/tsedio/tsed/issues"
34
33
  },
35
- "homepage": "https://github.com/tsedio/tsed/tree/production//packages/ajv",
34
+ "homepage": "https://github.com/tsedio/tsed/tree/production//packages/specs/ajv",
36
35
  "author": "Romain Lenzotti",
37
36
  "license": "MIT"
38
37
  }
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Formats = void 0;
4
- const core_1 = require("@tsed/core");
5
- const di_1 = require("@tsed/di");
6
- /**
7
- * Create a new custom formats validator
8
- * @param name
9
- * @param options
10
- * @decorator
11
- * @ajv
12
- */
13
- function Formats(name, options = {}) {
14
- return core_1.useDecorators(di_1.Injectable({
15
- type: "ajv:formats"
16
- }), core_1.StoreSet("ajv:formats", {
17
- name,
18
- options
19
- }));
20
- }
21
- exports.Formats = Formats;
22
- //# sourceMappingURL=formats.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"formats.js","sourceRoot":"","sources":["../../src/decorators/formats.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AACnD,iCAAoC;AAIpC;;;;;;GAMG;AACH,SAAgB,OAAO,CAAC,IAAY,EAAE,UAA0B,EAAE;IAChE,OAAO,oBAAa,CAClB,eAAU,CAAC;QACT,IAAI,EAAE,aAAa;KACpB,CAAC,EACF,eAAQ,CAAC,aAAa,EAAE;QACtB,IAAI;QACJ,OAAO;KACR,CAAC,CACH,CAAC;AACJ,CAAC;AAVD,0BAUC","sourcesContent":["import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, AsyncFormatDefinition, FormatDefinition, KeywordDefinition} from \"ajv\";\nexport type FormatsOptions = Omit<FormatDefinition<any>, \"validate\" | \"compare\"> | Omit<AsyncFormatDefinition<any>, \"validate\" | \"compare\">;\n/**\n * Create a new custom formats validator\n * @param name\n * @param options\n * @decorator\n * @ajv\n */\nexport function Formats(name: string, options: FormatsOptions = {}): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:formats\"\n }),\n StoreSet(\"ajv:formats\", {\n name,\n options\n })\n );\n}\n"]}
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Keyword = void 0;
4
- const core_1 = require("@tsed/core");
5
- const di_1 = require("@tsed/di");
6
- /**
7
- * Create new keyword custom validator
8
- * @param options
9
- * @decorator
10
- * @ajv
11
- */
12
- function Keyword(options) {
13
- return core_1.useDecorators(di_1.Injectable({
14
- type: "ajv:keyword"
15
- }), core_1.StoreSet("ajv:keyword", {
16
- ...options,
17
- metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema
18
- }));
19
- }
20
- exports.Keyword = Keyword;
21
- //# sourceMappingURL=keyword.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"keyword.js","sourceRoot":"","sources":["../../src/decorators/keyword.ts"],"names":[],"mappings":";;;AAAA,qCAAmD;AACnD,iCAAoC;AAQpC;;;;;GAKG;AACH,SAAgB,OAAO,CAAC,OAAuB;IAC7C,OAAO,oBAAa,CAClB,eAAU,CAAC;QACT,IAAI,EAAE,aAAa;KACpB,CAAC,EACF,eAAQ,CAAC,aAAa,EAAE;QACtB,GAAG,OAAO;QACV,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU;KAC/G,CAAC,CACH,CAAC;AACJ,CAAC;AAVD,0BAUC","sourcesContent":["import {StoreSet, useDecorators} from \"@tsed/core\";\nimport {Injectable} from \"@tsed/di\";\nimport {JsonSchema} from \"@tsed/schema\";\nimport {AnySchemaObject, KeywordDefinition} from \"ajv\";\n\nexport type KeywordOptions = Partial<Omit<KeywordDefinition, \"metaSchema\">> & {\n metaSchema?: AnySchemaObject | JsonSchema;\n};\n\n/**\n * Create new keyword custom validator\n * @param options\n * @decorator\n * @ajv\n */\nexport function Keyword(options: KeywordOptions): ClassDecorator {\n return useDecorators(\n Injectable({\n type: \"ajv:keyword\"\n }),\n StoreSet(\"ajv:keyword\", {\n ...options,\n metaSchema: options.metaSchema && options.metaSchema.toJSON ? options.metaSchema.toJSON() : options.metaSchema\n })\n );\n}\n"]}
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AjvValidationError = void 0;
4
- const exceptions_1 = require("@tsed/exceptions");
5
- class AjvValidationError extends exceptions_1.BadRequest {
6
- constructor(message, errors = []) {
7
- super(message);
8
- this.name = "AJV_VALIDATION_ERROR";
9
- this.errors = errors;
10
- }
11
- }
12
- exports.AjvValidationError = AjvValidationError;
13
- //# sourceMappingURL=AjvValidationError.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AjvValidationError.js","sourceRoot":"","sources":["../../src/errors/AjvValidationError.ts"],"names":[],"mappings":";;;AAAA,iDAA4C;AAE5C,MAAa,kBAAmB,SAAQ,uBAAU;IAIhD,YAAY,OAAe,EAAE,SAAgB,EAAE;QAC7C,KAAK,CAAC,OAAO,CAAC,CAAC;QAJV,SAAI,GAAW,sBAAsB,CAAC;QAK3C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AARD,gDAQC","sourcesContent":["import {BadRequest} from \"@tsed/exceptions\";\n\nexport class AjvValidationError extends BadRequest {\n public name: string = \"AJV_VALIDATION_ERROR\";\n public errors: any[];\n\n constructor(message: string, errors: any[] = []) {\n super(message);\n this.errors = errors;\n }\n}\n"]}
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=FormatsMethods.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"FormatsMethods.js","sourceRoot":"","sources":["../../src/interfaces/FormatsMethods.ts"],"names":[],"mappings":"","sourcesContent":["export interface FormatsMethods<T extends string | number> {\n compare?: (data1: T, data2: T) => number | undefined;\n\n validate(data: T): boolean;\n}\n"]}
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=IAjvSettings.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"IAjvSettings.js","sourceRoot":"","sources":["../../src/interfaces/IAjvSettings.ts"],"names":[],"mappings":"","sourcesContent":["import {ErrorObject, Options} from \"ajv\";\n\n/**\n *\n */\nexport interface AjvErrorObject extends ErrorObject {\n modelName: string;\n collectionName?: string;\n}\n\n/**\n *\n */\nexport type ErrorFormatter = (error: AjvErrorObject) => string;\n\n/**\n *\n */\nexport interface IAjvSettings extends Options {\n Ajv?: any;\n errorFormatter?: ErrorFormatter;\n}\n"]}
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=KeywordMethods.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"KeywordMethods.js","sourceRoot":"","sources":["../../src/interfaces/KeywordMethods.ts"],"names":[],"mappings":"","sourcesContent":["import {AnySchemaObject, KeywordCxt, SchemaObjCxt, ValidateFunction} from \"ajv\";\n\nexport interface AjvDataValidationCtx<T extends string | number = string | number> {\n dataPath: string;\n parentData: {[K in T]: any}; // object or array\n parentDataProperty: T; // string or number\n rootData: Record<string, any> | any[];\n dynamicAnchors: {[Ref in string]?: ValidateFunction};\n}\n\nexport interface AjvDataValidateFunction {\n (...args: Parameters<ValidateFunction>): boolean | Promise<any>;\n}\n\nexport interface AjvSchemaValidateFunction {\n (schema: any, data: any, parentSchema?: AnySchemaObject, dataCxt?: AjvDataValidationCtx): boolean | Promise<any>;\n}\n\nexport interface KeywordMethods {\n code?: (cxt: KeywordCxt, ruleType?: string) => void;\n compile?: (schema: any, parentSchema: AnySchemaObject, it: SchemaObjCxt) => AjvDataValidateFunction;\n validate?: AjvSchemaValidateFunction | AjvDataValidateFunction;\n}\n"]}
@@ -1,68 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- const core_1 = require("@tsed/core");
5
- const di_1 = require("@tsed/di");
6
- const ajv_1 = tslib_1.__importDefault(require("ajv"));
7
- const ajv_formats_1 = tslib_1.__importDefault(require("ajv-formats"));
8
- function getHandler(key, service) {
9
- if (service[key]) {
10
- return service[key].bind(service);
11
- }
12
- }
13
- function getKeywordProviders(injector) {
14
- return injector.getProviders("ajv:keyword");
15
- }
16
- function bindKeywords(injector) {
17
- return getKeywordProviders(injector).map((provider) => {
18
- const options = provider.store.get("ajv:keyword", {});
19
- const service = injector.invoke(provider.token);
20
- return core_1.cleanObject({
21
- ...options,
22
- validate: getHandler("validate", service),
23
- compile: getHandler("compile", service),
24
- code: getHandler("code", service),
25
- macro: getHandler("macro", service)
26
- });
27
- });
28
- }
29
- function getFormatsProviders(injector) {
30
- return injector.getProviders("ajv:formats");
31
- }
32
- function getFormats(injector) {
33
- return getFormatsProviders(injector).map((provider) => {
34
- var _a;
35
- const { name, options } = provider.store.get("ajv:formats", {});
36
- const service = injector.invoke(provider.token);
37
- return {
38
- name,
39
- options: {
40
- ...options,
41
- validate: service.validate.bind(service),
42
- compare: (_a = service.compare) === null || _a === void 0 ? void 0 : _a.bind(service)
43
- }
44
- };
45
- });
46
- }
47
- di_1.registerProvider({
48
- provide: ajv_1.default,
49
- deps: [di_1.Configuration, di_1.InjectorService],
50
- scope: di_1.ProviderScope.SINGLETON,
51
- useFactory(configuration, injector) {
52
- const { errorFormatter, keywords = [], ...props } = configuration.get("ajv") || {};
53
- const options = {
54
- verbose: false,
55
- coerceTypes: true,
56
- strict: false,
57
- keywords: [...keywords, ...bindKeywords(injector)],
58
- ...props
59
- };
60
- const ajv = new ajv_1.default(options);
61
- ajv_formats_1.default(ajv);
62
- getFormats(injector).forEach(({ name, options }) => {
63
- ajv.addFormat(name, options);
64
- });
65
- return ajv;
66
- }
67
- });
68
- //# sourceMappingURL=Ajv.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Ajv.js","sourceRoot":"","sources":["../../src/services/Ajv.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AACvC,iCAAyF;AACzF,sDAA+D;AAC/D,sEAAqC;AAIrC,SAAS,UAAU,CAAC,GAAW,EAAE,OAAY;IAC3C,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE;QAChB,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KACnC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,QAAyB;IACpD,OAAO,QAAQ,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;AAC9C,CAAC;AAED,SAAS,YAAY,CAAC,QAAyB;IAC7C,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE;QACpD,MAAM,OAAO,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAqC,aAAa,EAAE,EAAE,CAAE,CAAC;QAC3F,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAEhD,OAA0B,kBAAW,CAAC;YACpC,GAAG,OAAO;YACV,QAAQ,EAAE,UAAU,CAAC,UAAU,EAAE,OAAO,CAAC;YACzC,OAAO,EAAE,UAAU,CAAC,SAAS,EAAE,OAAO,CAAC;YACvC,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,CAAC;YACjC,KAAK,EAAE,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC;SACpC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS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,qBAAU,CAAC,GAAU,CAAC,CAAC;QAEvB,UAAU,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,EAAC,IAAI,EAAE,OAAO,EAAC,EAAE,EAAE;YAC/C,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC/B,CAAC,CAAC,CAAC;QAEH,OAAO,GAAG,CAAC;IACb,CAAC;CACF,CAAC,CAAC","sourcesContent":["import {cleanObject} from \"@tsed/core\";\nimport {Configuration, InjectorService, ProviderScope, registerProvider} from \"@tsed/di\";\nimport Ajv, {Format, KeywordDefinition, Vocabulary} from \"ajv\";\nimport AjvFormats from \"ajv-formats\";\nimport {FormatsMethods} from \"../interfaces/FormatsMethods\";\nimport {IAjvSettings} from \"../interfaces/IAjvSettings\";\n\nfunction getHandler(key: string, service: any) {\n if (service[key]) {\n return service[key].bind(service);\n }\n}\n\nfunction getKeywordProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:keyword\");\n}\n\nfunction bindKeywords(injector: InjectorService): Vocabulary {\n return getKeywordProviders(injector).map((provider) => {\n const options = provider.store.get<Omit<KeywordDefinition, \"compile\">>(\"ajv:keyword\", {})!;\n const service = injector.invoke(provider.token);\n\n return <KeywordDefinition>cleanObject({\n ...options,\n validate: getHandler(\"validate\", service),\n compile: getHandler(\"compile\", service),\n code: getHandler(\"code\", service),\n macro: getHandler(\"macro\", service)\n });\n });\n}\n\nfunction getFormatsProviders(injector: InjectorService) {\n return injector.getProviders(\"ajv:formats\");\n}\n\nfunction getFormats(injector: InjectorService): {name: string; options: Format}[] {\n return getFormatsProviders(injector).map((provider) => {\n const {name, options} = provider.store.get<any>(\"ajv:formats\", {})!;\n const service = injector.invoke<FormatsMethods<any>>(provider.token);\n\n return {\n name,\n options: {\n ...options,\n validate: service.validate.bind(service),\n compare: service.compare?.bind(service)\n }\n };\n });\n}\n\nregisterProvider({\n provide: Ajv,\n deps: [Configuration, InjectorService],\n scope: ProviderScope.SINGLETON,\n useFactory(configuration: Configuration, injector: InjectorService) {\n const {errorFormatter, keywords = [], ...props} = configuration.get<IAjvSettings>(\"ajv\") || {};\n const options = {\n verbose: false,\n coerceTypes: true,\n strict: false,\n keywords: [...keywords, ...bindKeywords(injector)],\n ...props\n };\n\n const ajv = new Ajv(options);\n\n AjvFormats(ajv as any);\n\n getFormats(injector).forEach(({name, options}) => {\n ajv.addFormat(name, options);\n });\n\n return ajv;\n }\n});\n"]}
@@ -1,91 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AjvService = void 0;
4
- const tslib_1 = require("tslib");
5
- const core_1 = require("@tsed/core");
6
- const di_1 = require("@tsed/di");
7
- const schema_1 = require("@tsed/schema");
8
- const ajv_1 = tslib_1.__importDefault(require("ajv"));
9
- const AjvValidationError_1 = require("../errors/AjvValidationError");
10
- const defaultErrorFormatter_1 = require("../utils/defaultErrorFormatter");
11
- require("./Ajv");
12
- const getPath_1 = require("../utils/getPath");
13
- let AjvService = class AjvService {
14
- async validate(value, options) {
15
- let { schema, type, collectionType, ...additionalOptions } = this.mapOptions(options);
16
- schema = schema || schema_1.getJsonSchema(type, { ...additionalOptions, customKeys: true });
17
- if (schema) {
18
- const localValue = core_1.deepClone(value);
19
- const valid = await this.ajv.validate(schema, localValue);
20
- if (!valid) {
21
- throw this.mapErrors(this.ajv.errors || [], {
22
- type,
23
- collectionType,
24
- async: true,
25
- value: localValue
26
- });
27
- }
28
- }
29
- return value;
30
- }
31
- mapOptions(options) {
32
- if (options instanceof schema_1.JsonSchema) {
33
- return {
34
- schema: options.toJSON({ customKeys: true })
35
- };
36
- }
37
- return options;
38
- }
39
- mapErrors(errors, options) {
40
- const { type, collectionType, value } = options;
41
- const message = errors
42
- .map((error) => {
43
- if (collectionType) {
44
- error.collectionName = core_1.nameOf(collectionType);
45
- }
46
- const dataPath = getPath_1.getPath(error);
47
- if (!error.data) {
48
- if (dataPath) {
49
- error.data = core_1.getValue(value, dataPath.replace(/^\./, ""));
50
- }
51
- else if (error.schemaPath !== "#/required") {
52
- error.data = value;
53
- }
54
- }
55
- if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {
56
- error.data = "[REDACTED]";
57
- }
58
- if (type) {
59
- error.modelName = core_1.nameOf(type);
60
- error.message = this.mapClassError(error, type);
61
- }
62
- return this.errorFormatter.call(this, error, {});
63
- })
64
- .join("\n");
65
- return new AjvValidationError_1.AjvValidationError(message, errors);
66
- }
67
- mapClassError(error, targetType) {
68
- const propertyKey = core_1.getValue(error, "params.missingProperty");
69
- if (propertyKey) {
70
- const store = schema_1.JsonEntityStore.from(core_1.prototypeOf(targetType), propertyKey);
71
- if (store) {
72
- core_1.setValue(error, "params.missingProperty", store.name || propertyKey);
73
- return error.message.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);
74
- }
75
- }
76
- return error.message;
77
- }
78
- };
79
- tslib_1.__decorate([
80
- di_1.Constant("ajv.errorFormatter", defaultErrorFormatter_1.defaultErrorFormatter),
81
- tslib_1.__metadata("design:type", Function)
82
- ], AjvService.prototype, "errorFormatter", void 0);
83
- tslib_1.__decorate([
84
- di_1.Inject(),
85
- tslib_1.__metadata("design:type", ajv_1.default)
86
- ], AjvService.prototype, "ajv", void 0);
87
- AjvService = tslib_1.__decorate([
88
- di_1.Injectable()
89
- ], AjvService);
90
- exports.AjvService = AjvService;
91
- //# sourceMappingURL=AjvService.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"AjvService.js","sourceRoot":"","sources":["../../src/services/AjvService.ts"],"names":[],"mappings":";;;;AAAA,qCAAoF;AACpF,iCAAsD;AACtD,yCAA0F;AAC1F,sDAAqC;AACrC,qEAAgE;AAEhE,0EAAqE;AACrE,iBAAe;AACf,8CAAyC;AASzC,IAAa,UAAU,GAAvB,MAAa,UAAU;IAOrB,KAAK,CAAC,QAAQ,CAAC,KAAU,EAAE,OAAwC;QACjE,IAAI,EAAC,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,iB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AC,OAAO,CAAC;IACvB,CAAC;CACF,CAAA;AAtFC;IADC,aAAQ,CAAC,oBAAoB,EAAE,6CAAqB,CAAC;;kDACb;AAGzC;IADC,WAAM,EAAE;sCACM,aAAG;uCAAC;AALR,UAAU;IADtB,eAAU,EAAE;GACA,UAAU,CAwFtB;AAxFY,gCAAU","sourcesContent":["import {deepClone, getValue, nameOf, prototypeOf, setValue, Type} from \"@tsed/core\";\nimport {Constant, Inject, Injectable} from \"@tsed/di\";\nimport {getJsonSchema, JsonEntityStore, JsonSchema, JsonSchemaObject} from \"@tsed/schema\";\nimport Ajv, {ErrorObject} from \"ajv\";\nimport {AjvValidationError} from \"../errors/AjvValidationError\";\nimport {AjvErrorObject, ErrorFormatter} from \"../interfaces/IAjvSettings\";\nimport {defaultErrorFormatter} from \"../utils/defaultErrorFormatter\";\nimport \"./Ajv\";\nimport {getPath} from \"../utils/getPath\";\n\nexport interface AjvValidateOptions extends Record<string, any> {\n schema?: JsonSchema | Partial<JsonSchemaObject>;\n type?: Type<any> | any;\n collectionType?: Type<any> | any;\n}\n\n@Injectable()\nexport class AjvService {\n @Constant(\"ajv.errorFormatter\", defaultErrorFormatter)\n protected errorFormatter: ErrorFormatter;\n\n @Inject()\n protected ajv: Ajv;\n\n async validate(value: any, options: AjvValidateOptions | JsonSchema): Promise<any> {\n let {schema, type, collectionType, ...additionalOptions} = this.mapOptions(options);\n\n schema = schema || getJsonSchema(type, {...additionalOptions, customKeys: true});\n\n if (schema) {\n const localValue = deepClone(value);\n const valid = await this.ajv.validate(schema as any, localValue);\n if (!valid) {\n throw this.mapErrors(this.ajv.errors || [], {\n type,\n collectionType,\n async: true,\n value: localValue\n });\n }\n }\n\n return value;\n }\n\n protected mapOptions(options: AjvValidateOptions | JsonSchema): AjvValidateOptions {\n if (options instanceof JsonSchema) {\n return {\n schema: options.toJSON({customKeys: true})\n };\n }\n\n return options;\n }\n\n protected mapErrors(errors: ErrorObject[], options: any) {\n const {type, collectionType, value} = options;\n\n const message = errors\n .map((error: AjvErrorObject) => {\n if (collectionType) {\n error.collectionName = nameOf(collectionType);\n }\n\n const dataPath = getPath(error);\n\n if (!error.data) {\n if (dataPath) {\n error.data = getValue(value, dataPath.replace(/^\\./, \"\"));\n } else if (error.schemaPath !== \"#/required\") {\n error.data = value;\n }\n }\n\n if (dataPath && dataPath.match(/pwd|password|mdp|secret/)) {\n error.data = \"[REDACTED]\";\n }\n\n if (type) {\n error.modelName = nameOf(type);\n error.message = this.mapClassError(error, type);\n }\n\n return this.errorFormatter.call(this, error, {});\n })\n .join(\"\\n\");\n\n return new AjvValidationError(message, errors);\n }\n\n protected mapClassError(error: AjvErrorObject, targetType: Type<any>) {\n const propertyKey = getValue(error, \"params.missingProperty\");\n\n if (propertyKey) {\n const store = JsonEntityStore.from<JsonEntityStore>(prototypeOf(targetType), propertyKey);\n\n if (store) {\n setValue(error, \"params.missingProperty\", store.name || propertyKey);\n\n return error.message!.replace(`'${propertyKey}'`, `'${store.name || propertyKey}'`);\n }\n }\n\n return error.message;\n }\n}\n"]}
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultErrorFormatter = void 0;
4
- const getPath_1 = require("./getPath");
5
- function defaultErrorFormatter(error) {
6
- const value = JSON.stringify(error.data === undefined ? "undefined" : error.data);
7
- const join = (list) => list.filter(Boolean).join("").trim();
8
- error.dataPath = getPath_1.getPath(error);
9
- const [, indexPath, ...paths] = error.dataPath.split(".");
10
- const deepPaths = paths.length ? "." + paths.join(".") : "";
11
- if (error.collectionName) {
12
- switch (error.collectionName) {
13
- case "Array":
14
- return join([`${error.modelName || ""}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
15
- case "Map":
16
- return join([`Map<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
17
- case "Set":
18
- return join([`Set<${indexPath}, ${error.modelName || ""}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);
19
- }
20
- }
21
- return join([!error.modelName && "Value", `${error.modelName || ""}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);
22
- }
23
- exports.defaultErrorFormatter = defaultErrorFormatter;
24
- //# sourceMappingURL=defaultErrorFormatter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"defaultErrorFormatter.js","sourceRoot":"","sources":["../../src/utils/defaultErrorFormatter.ts"],"names":[],"mappings":";;;AACA,uCAAkC;AAElC,SAAgB,qBAAqB,CAAC,KAA0C;IAC9E,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAClF,MAAM,IAAI,GAAG,CAAC,IAAW,EAAU,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAE3E,KAAK,CAAC,QAAQ,GAAG,iBAAO,CAAC,KAAK,CAAC,CAAC;IAEhC,MAAM,CAAC,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1D,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAE5D,IAAI,KAAK,CAAC,cAAc,EAAE;QACxB,QAAQ,KAAK,CAAC,cAAc,EAAE;YAC5B,KAAK,OAAO;gBACV,OAAO,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,SAAS,IAAI,EAAE,IAAI,SAAS,IAAI,SAAS,EAAE,EAAE,IAAI,KAAK,CAAC,OAAO,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC;YAClH,KAAK,KAAK;gBACR,OAAO,IAAI,CAAC,CAAC,OAAO,SAAS,KAAK,KAAK,CAAC,SAAS,IAAI,EAAE,IAAI,SAAS,EAAE,EAAE,IAAI,KAAK,CAAC,OAAO,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC;YACvH,KAAK,KAAK;gBACR,OAAO,IAAI,CAAC,CAAC,OAAO,SAAS,KAAK,KAAK,CAAC,SAAS,IAAI,EAAE,IAAI,SAAS,EAAE,EAAE,IAAI,KAAK,CAAC,OAAO,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC;SACxH;KACF;IAED,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,IAAI,OAAO,EAAE,GAAG,KAAK,CAAC,SAAS,IAAI,EAAE,EAAE,EAAE,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,OAAO,kBAAkB,KAAK,EAAE,CAAC,CAAC,CAAC;AACrI,CAAC;AArBD,sDAqBC","sourcesContent":["import {AjvErrorObject} from \"../interfaces/IAjvSettings\";\nimport {getPath} from \"./getPath\";\n\nexport function defaultErrorFormatter(error: AjvErrorObject & {dataPath: string}) {\n const value = JSON.stringify(error.data === undefined ? \"undefined\" : error.data);\n const join = (list: any[]): string => list.filter(Boolean).join(\"\").trim();\n\n error.dataPath = getPath(error);\n\n const [, indexPath, ...paths] = error.dataPath.split(\".\");\n const deepPaths = paths.length ? \".\" + paths.join(\".\") : \"\";\n\n if (error.collectionName) {\n switch (error.collectionName) {\n case \"Array\":\n return join([`${error.modelName || \"\"}[${indexPath}]${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Map\":\n return join([`Map<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n case \"Set\":\n return join([`Set<${indexPath}, ${error.modelName || \"\"}>${deepPaths}`, ` ${error.message}. Given value: ${value}`]);\n }\n }\n\n return join([!error.modelName && \"Value\", `${error.modelName || \"\"}`, error.dataPath, ` ${error.message}. Given value: ${value}`]);\n}\n"]}
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPath = void 0;
4
- const core_1 = require("@tsed/core");
5
- function getPath(error) {
6
- return core_1.getValue(error, "dataPath", core_1.getValue(error, "instancePath", "")).replace(/\//gi, ".");
7
- }
8
- exports.getPath = getPath;
9
- //# sourceMappingURL=getPath.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getPath.js","sourceRoot":"","sources":["../../src/utils/getPath.ts"],"names":[],"mappings":";;;AAAA,qCAAoC;AAEpC,SAAgB,OAAO,CAAC,KAAU;IAChC,OAAO,eAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,eAAQ,CAAC,KAAK,EAAE,cAAc,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC/F,CAAC;AAFD,0BAEC","sourcesContent":["import {getValue} from \"@tsed/core\";\n\nexport function getPath(error: any) {\n return getValue(error, \"dataPath\", getValue(error, \"instancePath\", \"\")).replace(/\\//gi, \".\");\n}\n"]}