@astratra/core 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -2
- package/THIRD-PARTY-NOTICES.md +56 -0
- package/package.json +12 -6
- package/src/googleServiceAccount.js +192 -0
- package/src/index.d.ts +187 -0
- package/src/index.js +25 -11
- package/src/upload.js +469 -0
- package/src/validateMiddleware.js +1 -1
- package/src/validation.js +518 -0
- package/src/validators.js +313 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/* global structuredClone */
|
|
2
|
+
const { validators: V, sanitizers: S } = require('./validators');
|
|
3
|
+
|
|
4
|
+
/*
|
|
5
|
+
* La validation des requêtes Express par chaînes — body('email').trim().isEmail().withMessage('…') — sans
|
|
6
|
+
* express-validator : mêmes chaînes, mêmes erreurs ({ type, value, msg, path, location }), mêmes nettoyages écrits dans
|
|
7
|
+
* la requête, même validationResult et même matchedData qu'express-validator 7.3 (licence MIT, Copyright (c) 2010
|
|
8
|
+
* Chris O'Hara ; voir THIRD-PARTY-NOTICES.md), vérifiés sur des réponses enregistrées.
|
|
9
|
+
*
|
|
10
|
+
* Différences voulues :
|
|
11
|
+
* - un chemin vers « __proto__ », « constructor » ou « prototype » n'est jamais lu ni écrit (pas de pollution de
|
|
12
|
+
* prototype par un nettoyage), et seules les propriétés propres sont lues (body('toString') ne lit pas une
|
|
13
|
+
* méthode héritée) ;
|
|
14
|
+
* - une valeur JSON qui ne se convertit pas en texte ({"toString":0}, [[{"toString":1}]]) est invalide au lieu de
|
|
15
|
+
* faire planter la requête ;
|
|
16
|
+
* - withMessage avant tout validateur lève une erreur claire au lieu d'une TypeError ;
|
|
17
|
+
* - oneOf, checkSchema, checkExact et les validateurs rares (isURL, isISO8601, isCreditCard…) ne sont pas repris :
|
|
18
|
+
* appeler une méthode absente échoue au démarrage, pas à la première requête.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const CONTEXTS = Symbol.for('astratra.validation.contexts');
|
|
22
|
+
const FORBIDDEN = new Set(['__proto__', 'constructor', 'prototype']);
|
|
23
|
+
|
|
24
|
+
class ValidationHalt extends Error {}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Le texte d'une valeur, comme express-validator le passe aux vérifications standard. Une valeur qui ne se convertit
|
|
28
|
+
* pas ({"toString":0}, [[{"toString":1}]] dans un corps JSON) donne « [object Object] » ou « [object Array] » :
|
|
29
|
+
* express-validator levait une TypeError (une erreur 500 pour n'importe quel corps de ce genre).
|
|
30
|
+
*/
|
|
31
|
+
function toText(value) {
|
|
32
|
+
try {
|
|
33
|
+
if (value instanceof Date) return value.toISOString();
|
|
34
|
+
if (value && typeof value === 'object' && value.toString) {
|
|
35
|
+
if (typeof value.toString !== 'function') return Object.getPrototypeOf(value).toString.call(value);
|
|
36
|
+
return String(value.toString());
|
|
37
|
+
}
|
|
38
|
+
if (value == null || (Number.isNaN(Number(value)) && !value.length)) return '';
|
|
39
|
+
return String(value);
|
|
40
|
+
} catch {
|
|
41
|
+
return Object.prototype.toString.call(value);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** « a.b[0]["c.d"] » en segments (comme _.toPath de lodash, pour ces formes). */
|
|
46
|
+
function toPath(path) {
|
|
47
|
+
const segments = [];
|
|
48
|
+
let current = '';
|
|
49
|
+
let i = 0;
|
|
50
|
+
const flush = () => {
|
|
51
|
+
if (current !== '') segments.push(current);
|
|
52
|
+
current = '';
|
|
53
|
+
};
|
|
54
|
+
while (i < path.length) {
|
|
55
|
+
const c = path[i];
|
|
56
|
+
if (c === '.') {
|
|
57
|
+
flush();
|
|
58
|
+
i++;
|
|
59
|
+
} else if (c === '[') {
|
|
60
|
+
flush();
|
|
61
|
+
const quote = path[i + 1] === '"' || path[i + 1] === "'" ? path[i + 1] : null;
|
|
62
|
+
if (quote) {
|
|
63
|
+
const end = path.indexOf(`${quote}]`, i + 2);
|
|
64
|
+
if (end < 0) {
|
|
65
|
+
current = path.slice(i);
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
segments.push(path.slice(i + 2, end));
|
|
69
|
+
i = end + 2;
|
|
70
|
+
} else {
|
|
71
|
+
const end = path.indexOf(']', i + 1);
|
|
72
|
+
if (end < 0) {
|
|
73
|
+
current = path.slice(i);
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
segments.push(path.slice(i + 1, end));
|
|
77
|
+
i = end + 1;
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
current += c;
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
flush();
|
|
85
|
+
return segments;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Le chemin affiché d'une suite de segments : « a.b[0] », « ["c.d"] ». */
|
|
89
|
+
function reconstructFieldPath(segments) {
|
|
90
|
+
return segments.reduce((prev, segment) => {
|
|
91
|
+
const s = segment === '\\*' ? '*' : segment;
|
|
92
|
+
if (s.includes('.')) return `${prev}["${s}"]`;
|
|
93
|
+
if (/^\d+$/.test(s)) return `${prev}[${s}]`;
|
|
94
|
+
return prev ? `${prev}.${s}` : s;
|
|
95
|
+
}, '');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const isObjectLike = (value) => value !== null && typeof value === 'object';
|
|
99
|
+
|
|
100
|
+
function getPath(object, path) {
|
|
101
|
+
if (path === '') return object;
|
|
102
|
+
let current = object;
|
|
103
|
+
for (const segment of toPath(path)) {
|
|
104
|
+
if (FORBIDDEN.has(segment) || (!isObjectLike(current) && typeof current !== 'function') || !Object.hasOwn(current, segment)) return undefined;
|
|
105
|
+
current = current[segment];
|
|
106
|
+
}
|
|
107
|
+
return current;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Écrit une valeur à un chemin, en créant les objets et tableaux manquants (comme _.set) ; jamais sur un prototype. */
|
|
111
|
+
function setPath(object, path, value) {
|
|
112
|
+
const parsed = toPath(path);
|
|
113
|
+
const segments = parsed.length ? parsed : [''];
|
|
114
|
+
if (!isObjectLike(object) || segments.some((s) => FORBIDDEN.has(s))) return;
|
|
115
|
+
let current = object;
|
|
116
|
+
for (let i = 0; i < segments.length - 1; i++) {
|
|
117
|
+
const segment = segments[i];
|
|
118
|
+
if (!isObjectLike(current[segment]) || !Object.hasOwn(current, segment)) current[segment] = /^\d+$/.test(segments[i + 1]) ? [] : {};
|
|
119
|
+
current = current[segment];
|
|
120
|
+
}
|
|
121
|
+
current[segments[segments.length - 1]] = value;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function expandPath(object, path, currPath, currValues = []) {
|
|
125
|
+
const segments = typeof path === 'string' ? toPath(path) : path;
|
|
126
|
+
if (!segments.length) return [{ path: reconstructFieldPath(currPath), values: currValues }];
|
|
127
|
+
const [key, ...rest] = segments;
|
|
128
|
+
if (object != null && !isObjectLike(object)) {
|
|
129
|
+
if (key === '**') return rest.length ? [] : [{ path: reconstructFieldPath(currPath), values: currValues }];
|
|
130
|
+
if (key === '*') return [];
|
|
131
|
+
return [{ path: reconstructFieldPath([...currPath, ...segments]), values: currValues }];
|
|
132
|
+
}
|
|
133
|
+
const obj = object || {};
|
|
134
|
+
const ownKeys = Object.keys(obj).filter((k) => !FORBIDDEN.has(k));
|
|
135
|
+
if (key === '*') return ownKeys.flatMap((k) => expandPath(obj[k], rest, currPath.concat(k), currValues.concat(k)));
|
|
136
|
+
if (key === '**') {
|
|
137
|
+
return ownKeys.flatMap((k) => {
|
|
138
|
+
const nextPath = currPath.concat(k);
|
|
139
|
+
const selected = expandPath(obj[k], segments, nextPath, [k]).concat(rest[0] === k ? expandPath(obj[k], rest.slice(1), nextPath, []) : []);
|
|
140
|
+
const seen = new Set();
|
|
141
|
+
return selected
|
|
142
|
+
.filter(({ path: p }) => !seen.has(p) && seen.add(p))
|
|
143
|
+
.map(({ path: p, values }) => ({ path: p, values: values.length ? [...currValues, values.flat()] : currValues }));
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
return expandPath(FORBIDDEN.has(key) || !Object.hasOwn(obj, key) ? undefined : obj[key], rest, currPath.concat(key), currValues);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function selectFields(req, fields, locations) {
|
|
150
|
+
const out = [];
|
|
151
|
+
const seen = new Set();
|
|
152
|
+
for (const field of fields) {
|
|
153
|
+
for (const location of locations) {
|
|
154
|
+
const pathToExpand = location === 'headers' ? field.toLowerCase() : field;
|
|
155
|
+
for (const { path, values } of expandPath(req[location], pathToExpand, [])) {
|
|
156
|
+
const id = `${location}:${path}`;
|
|
157
|
+
if (seen.has(id)) continue;
|
|
158
|
+
seen.add(id);
|
|
159
|
+
out.push({ location, path, originalPath: field, pathValues: values, value: path === '' ? req[location] : getPath(req[location], path) });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
class Context {
|
|
167
|
+
constructor({ fields, locations, stack, optional, bail, visibility, message }) {
|
|
168
|
+
Object.assign(this, { fields, locations, stack, optional, bail, visibility, message });
|
|
169
|
+
this.errors = [];
|
|
170
|
+
this.dataMap = new Map();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
getData({ requiredOnly = false } = {}) {
|
|
174
|
+
const { optional } = this;
|
|
175
|
+
const checks = requiredOnly && optional ? [(v) => v !== undefined, (v) => (optional === 'null' ? v != null : true), (v) => (optional === 'falsy' ? v : true)] : [];
|
|
176
|
+
const groups = new Map();
|
|
177
|
+
for (const instance of this.dataMap.values()) {
|
|
178
|
+
if (!groups.has(instance.originalPath)) groups.set(instance.originalPath, []);
|
|
179
|
+
groups.get(instance.originalPath).push(instance);
|
|
180
|
+
}
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const [group, instances] of groups) {
|
|
183
|
+
const locationCount = new Set(instances.map((i) => i.location)).size;
|
|
184
|
+
if (instances.length > 1 && locationCount > 1 && !group.includes('*')) {
|
|
185
|
+
const withValue = instances.filter((i) => i.value !== undefined);
|
|
186
|
+
out.push(...(withValue.length ? withValue : [instances[0]]));
|
|
187
|
+
} else out.push(...instances);
|
|
188
|
+
}
|
|
189
|
+
return out.filter((instance) => checks.every((check) => check(instance.value)));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
addFieldInstances(instances) {
|
|
193
|
+
for (const instance of instances) this.dataMap.set(`${instance.location}:${instance.path}`, { ...instance });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
setData(path, value, location) {
|
|
197
|
+
const instance = this.dataMap.get(`${location}:${path}`);
|
|
198
|
+
if (!instance) throw new Error('Attempt to write data that did not pre-exist in context');
|
|
199
|
+
instance.value = value;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
addError({ message, value, meta }) {
|
|
203
|
+
const msg = message || this.message || 'Invalid value';
|
|
204
|
+
let error = { type: 'field', value, msg: typeof msg === 'function' ? msg(value, meta) : msg, path: meta?.path, location: meta?.location };
|
|
205
|
+
if (this.visibility.type === 'hidden') {
|
|
206
|
+
error = { ...error };
|
|
207
|
+
delete error.value;
|
|
208
|
+
} else if (this.visibility.type === 'redacted') error = { ...error, value: this.visibility.value };
|
|
209
|
+
this.errors.push(error);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/* Les éléments d'une chaîne, comme dans express-validator. */
|
|
214
|
+
const standardValidation = (validator, negated, options) => ({
|
|
215
|
+
kind: 'validator',
|
|
216
|
+
async run(context, value, meta) {
|
|
217
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
218
|
+
const result = validator(toText(item), ...options);
|
|
219
|
+
if (negated ? result : !result) context.addError({ message: this.message, value: item, meta });
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
const customValidation = (validator, negated) => ({
|
|
225
|
+
kind: 'validator',
|
|
226
|
+
async run(context, value, meta) {
|
|
227
|
+
try {
|
|
228
|
+
const result = validator(value, meta);
|
|
229
|
+
const actual = await result;
|
|
230
|
+
const isPromise = result?.then;
|
|
231
|
+
const failed = negated ? actual : !actual;
|
|
232
|
+
if ((!isPromise && failed) || (isPromise && negated)) context.addError({ message: this.message, value, meta });
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (negated) return;
|
|
235
|
+
context.addError({ message: this.message || (err instanceof Error ? err.message : err), value, meta });
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
const sanitization = (sanitizer, custom, options = []) => ({
|
|
241
|
+
async run(context, value, meta) {
|
|
242
|
+
const { path, location } = meta;
|
|
243
|
+
if (custom) {
|
|
244
|
+
context.setData(path, await Promise.resolve(sanitizer(value, meta)), location);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const values = Array.isArray(value) ? value : [value];
|
|
248
|
+
const next = values.map((v) => sanitizer(toText(v), ...options));
|
|
249
|
+
context.setData(path, values !== value ? next[0] : next, location);
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
const bailItem = () => ({
|
|
254
|
+
async run(context) {
|
|
255
|
+
if (context.errors.length > 0) throw new ValidationHalt();
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
const customCondition = (condition) => ({
|
|
260
|
+
async run(_context, value, meta) {
|
|
261
|
+
try {
|
|
262
|
+
const result = condition(value, meta);
|
|
263
|
+
await result;
|
|
264
|
+
if (!result) throw new Error();
|
|
265
|
+
} catch {
|
|
266
|
+
throw new ValidationHalt();
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
const chainCondition = (chain) => ({
|
|
272
|
+
async run(_context, _value, meta) {
|
|
273
|
+
const result = await chain.run(meta.req, { dryRun: true });
|
|
274
|
+
if (!result.isEmpty()) throw new ValidationHalt();
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
class Result {
|
|
279
|
+
constructor(formatter, errors) {
|
|
280
|
+
this.formatter = formatter;
|
|
281
|
+
this.errors = errors;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
array(options) {
|
|
285
|
+
return options?.onlyFirstError ? Object.values(this.mapped()) : this.errors.map(this.formatter);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
mapped() {
|
|
289
|
+
return this.errors.reduce((mapping, error) => {
|
|
290
|
+
const key = error.type === 'field' ? error.path : `_${error.type}`;
|
|
291
|
+
if (!Object.hasOwn(mapping, key)) mapping[key] = this.formatter(error);
|
|
292
|
+
return mapping;
|
|
293
|
+
}, {});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
formatWith(formatter) {
|
|
297
|
+
return new Result(formatter, this.errors);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
isEmpty() {
|
|
301
|
+
return this.errors.length === 0;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
throw() {
|
|
305
|
+
if (!this.isEmpty()) {
|
|
306
|
+
const error = new Error();
|
|
307
|
+
for (const key of ['array', 'mapped', 'formatWith', 'isEmpty', 'throw']) error[key] = this[key].bind(this);
|
|
308
|
+
Object.assign(error, { formatter: this.formatter, errors: this.errors });
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Lance une chaîne sur une requête : nettoie la requête (sauf dryRun) et rend ses erreurs. */
|
|
315
|
+
async function runChain(builder, req, options = {}) {
|
|
316
|
+
const context = new Context(builder.build());
|
|
317
|
+
if (req[CONTEXTS]?.some((c) => c.bail && c.errors.length > 0)) return Object.assign(new Result((e) => e, context.errors), { context });
|
|
318
|
+
context.addFieldInstances(selectFields(req, context.fields, context.locations));
|
|
319
|
+
const halted = new Set();
|
|
320
|
+
for (const item of context.stack) {
|
|
321
|
+
await Promise.all(context.getData({ requiredOnly: true }).map(async (instance) => {
|
|
322
|
+
const { location, path } = instance;
|
|
323
|
+
const id = `${location}:${path}`;
|
|
324
|
+
if (halted.has(id)) return;
|
|
325
|
+
try {
|
|
326
|
+
await item.run(context, instance.value, { req, location, path, pathValues: instance.pathValues });
|
|
327
|
+
const current = path !== '' ? getPath(req[location], path) : req[location];
|
|
328
|
+
if (!options.dryRun && current !== instance.value) {
|
|
329
|
+
if (path !== '') setPath(req[location], path, instance.value);
|
|
330
|
+
else req[location] = instance.value;
|
|
331
|
+
}
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (error instanceof ValidationHalt) {
|
|
334
|
+
halted.add(id);
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
}));
|
|
340
|
+
}
|
|
341
|
+
if (!options.dryRun) {
|
|
342
|
+
Object.defineProperty(req, CONTEXTS, { value: (req[CONTEXTS] || []).concat(context), configurable: true, writable: true, enumerable: false });
|
|
343
|
+
}
|
|
344
|
+
return Object.assign(new Result((e) => e, context.errors), { context });
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const STANDARD = {
|
|
348
|
+
contains: V.contains,
|
|
349
|
+
equals: V.equals,
|
|
350
|
+
isByteLength: V.isByteLength,
|
|
351
|
+
isEmail: V.isEmail,
|
|
352
|
+
isEmpty: V.isEmpty,
|
|
353
|
+
isFQDN: V.isFQDN,
|
|
354
|
+
isFloat: V.isFloat,
|
|
355
|
+
isHexadecimal: V.isHexadecimal,
|
|
356
|
+
isIP: V.isIP,
|
|
357
|
+
isIn: V.isIn,
|
|
358
|
+
isInt: V.isInt,
|
|
359
|
+
isLength: V.isLength,
|
|
360
|
+
isMongoId: V.isMongoId,
|
|
361
|
+
isNumeric: V.isNumeric,
|
|
362
|
+
isUUID: V.isUUID,
|
|
363
|
+
matches: V.matches,
|
|
364
|
+
};
|
|
365
|
+
const STANDARD_SANITIZERS = ['blacklist', 'escape', 'unescape', 'ltrim', 'rtrim', 'trim', 'normalizeEmail', 'stripLow', 'toBoolean', 'toDate', 'toFloat', 'toInt', 'whitelist'];
|
|
366
|
+
|
|
367
|
+
/** Une chaîne : un middleware Express, avec ses méthodes de validation et de nettoyage. */
|
|
368
|
+
function createChain(fields, locations, message) {
|
|
369
|
+
const builder = { stack: [], fields, locations, optional: false, bail: false, visibility: { type: 'visible' }, message };
|
|
370
|
+
builder.build = () => ({ fields: builder.fields, locations: builder.locations, stack: builder.stack, optional: builder.optional, bail: builder.bail, visibility: builder.visibility, message: builder.message });
|
|
371
|
+
let negateNext = false;
|
|
372
|
+
let lastValidator = null;
|
|
373
|
+
|
|
374
|
+
const chain = async (req, _res, next) => {
|
|
375
|
+
try {
|
|
376
|
+
await chain.run(req);
|
|
377
|
+
next();
|
|
378
|
+
} catch (error) {
|
|
379
|
+
next(error);
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
const addValidator = (item) => {
|
|
383
|
+
builder.stack.push(item);
|
|
384
|
+
lastValidator = item;
|
|
385
|
+
negateNext = false;
|
|
386
|
+
return chain;
|
|
387
|
+
};
|
|
388
|
+
const addSanitizer = (item) => {
|
|
389
|
+
builder.stack.push(item);
|
|
390
|
+
return chain;
|
|
391
|
+
};
|
|
392
|
+
const custom = (validator) => {
|
|
393
|
+
if (typeof validator !== 'function') throw new TypeError('custom() needs a function');
|
|
394
|
+
return addValidator(customValidation(validator, negateNext));
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
Object.assign(chain, {
|
|
398
|
+
builder,
|
|
399
|
+
run: (req, options) => runChain(builder, req, options),
|
|
400
|
+
not() {
|
|
401
|
+
negateNext = true;
|
|
402
|
+
return chain;
|
|
403
|
+
},
|
|
404
|
+
withMessage(msg) {
|
|
405
|
+
if (!lastValidator) throw new Error('withMessage() must follow a validator (or pass the message to body(field, message))');
|
|
406
|
+
lastValidator.message = msg;
|
|
407
|
+
return chain;
|
|
408
|
+
},
|
|
409
|
+
custom,
|
|
410
|
+
exists(options = {}) {
|
|
411
|
+
if (options.checkFalsy || options.values === 'falsy') return custom((v) => !!v);
|
|
412
|
+
if (options.checkNull || options.values === 'null') return custom((v) => v != null);
|
|
413
|
+
return custom((v) => v !== undefined);
|
|
414
|
+
},
|
|
415
|
+
isArray(options = {}) {
|
|
416
|
+
return custom((v) => Array.isArray(v) && (typeof options.min === 'undefined' || v.length >= options.min) && (typeof options.max === 'undefined' || v.length <= options.max));
|
|
417
|
+
},
|
|
418
|
+
isObject(options = { strict: true }) {
|
|
419
|
+
return custom((v) => typeof v === 'object' && (options.strict == null || options.strict ? v !== null && !Array.isArray(v) : true));
|
|
420
|
+
},
|
|
421
|
+
isString() {
|
|
422
|
+
return custom((v) => typeof v === 'string');
|
|
423
|
+
},
|
|
424
|
+
isBoolean(options) {
|
|
425
|
+
if (options?.strict) return custom((v) => v === true || v === false);
|
|
426
|
+
return addValidator(standardValidation(V.isBoolean, negateNext, options === undefined ? [] : [options]));
|
|
427
|
+
},
|
|
428
|
+
notEmpty(options) {
|
|
429
|
+
negateNext = true;
|
|
430
|
+
return chain.isEmpty(options);
|
|
431
|
+
},
|
|
432
|
+
bail(options) {
|
|
433
|
+
if (options?.level === 'request') builder.bail = true;
|
|
434
|
+
builder.stack.push(bailItem());
|
|
435
|
+
return chain;
|
|
436
|
+
},
|
|
437
|
+
if(condition) {
|
|
438
|
+
if (condition && typeof condition.run === 'function') builder.stack.push(chainCondition(condition));
|
|
439
|
+
else if (typeof condition === 'function') builder.stack.push(customCondition(condition));
|
|
440
|
+
else throw new Error('condition is not a validation chain nor a function');
|
|
441
|
+
return chain;
|
|
442
|
+
},
|
|
443
|
+
optional(options = true) {
|
|
444
|
+
if (typeof options === 'boolean') builder.optional = options ? 'undefined' : false;
|
|
445
|
+
else builder.optional = options.values ? options.values : options.checkFalsy ? 'falsy' : options.nullable ? 'null' : 'undefined';
|
|
446
|
+
return chain;
|
|
447
|
+
},
|
|
448
|
+
hide(hiddenValue) {
|
|
449
|
+
builder.visibility = hiddenValue !== undefined ? { type: 'redacted', value: hiddenValue } : { type: 'hidden' };
|
|
450
|
+
return chain;
|
|
451
|
+
},
|
|
452
|
+
customSanitizer(sanitizer) {
|
|
453
|
+
if (typeof sanitizer !== 'function') throw new TypeError('customSanitizer() needs a function');
|
|
454
|
+
return addSanitizer(sanitization(sanitizer, true));
|
|
455
|
+
},
|
|
456
|
+
default(defaultValue) {
|
|
457
|
+
return chain.customSanitizer((v) => ([undefined, null, ''].includes(v) || Number.isNaN(v) ? structuredClone(defaultValue) : v));
|
|
458
|
+
},
|
|
459
|
+
replace(valuesToReplace, newValue) {
|
|
460
|
+
const list = Array.isArray(valuesToReplace) ? valuesToReplace : [valuesToReplace];
|
|
461
|
+
return chain.customSanitizer((v) => (list.includes(v) ? structuredClone(newValue) : v));
|
|
462
|
+
},
|
|
463
|
+
toArray() {
|
|
464
|
+
return chain.customSanitizer((v) => (v !== undefined && ((Array.isArray(v) && v) || [v])) || []);
|
|
465
|
+
},
|
|
466
|
+
toLowerCase() {
|
|
467
|
+
return chain.customSanitizer((v) => (typeof v === 'string' ? v.toLowerCase() : v));
|
|
468
|
+
},
|
|
469
|
+
toUpperCase() {
|
|
470
|
+
return chain.customSanitizer((v) => (typeof v === 'string' ? v.toUpperCase() : v));
|
|
471
|
+
},
|
|
472
|
+
});
|
|
473
|
+
for (const [name, fn] of Object.entries(STANDARD)) {
|
|
474
|
+
chain[name] = (...options) => addValidator(standardValidation(fn, negateNext, options));
|
|
475
|
+
}
|
|
476
|
+
for (const name of STANDARD_SANITIZERS) {
|
|
477
|
+
chain[name] = (...options) => addSanitizer(sanitization(S[name], false, options));
|
|
478
|
+
}
|
|
479
|
+
return chain;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const fieldsOf = (fields) => (fields === undefined ? [''] : Array.isArray(fields) ? fields : [fields]).map((f) => {
|
|
483
|
+
if (typeof f !== 'string') throw new TypeError('a field must be a string');
|
|
484
|
+
return f;
|
|
485
|
+
});
|
|
486
|
+
const forLocations = (locations) => (fields, message) => createChain(fieldsOf(fields), locations, message);
|
|
487
|
+
|
|
488
|
+
const body = forLocations(['body']);
|
|
489
|
+
const cookie = forLocations(['cookies']);
|
|
490
|
+
const header = forLocations(['headers']);
|
|
491
|
+
const param = forLocations(['params']);
|
|
492
|
+
const query = forLocations(['query']);
|
|
493
|
+
const check = forLocations(['body', 'cookies', 'headers', 'params', 'query']);
|
|
494
|
+
|
|
495
|
+
function withDefaults(options = {}) {
|
|
496
|
+
const formatter = options.formatter || ((error) => error);
|
|
497
|
+
return (req) => new Result(formatter, (req[CONTEXTS] || []).flatMap((context) => context.errors));
|
|
498
|
+
}
|
|
499
|
+
/** Les erreurs de toutes les chaînes déjà lancées sur cette requête. */
|
|
500
|
+
const validationResult = Object.assign(withDefaults(), { withDefaults });
|
|
501
|
+
|
|
502
|
+
/** Les données validées (ou nettoyées) de la requête, en un objet. */
|
|
503
|
+
function matchedData(req, options = {}) {
|
|
504
|
+
const removeOptionals = options.includeOptionals !== true;
|
|
505
|
+
const onlyValid = options.onlyValidData !== false;
|
|
506
|
+
const locations = options.locations || [];
|
|
507
|
+
const out = {};
|
|
508
|
+
for (const context of req[CONTEXTS] || []) {
|
|
509
|
+
for (const instance of context.getData({ requiredOnly: removeOptionals })) {
|
|
510
|
+
if (onlyValid && context.errors.some((e) => e.type === 'field' && e.location === instance.location && e.path === instance.path)) continue;
|
|
511
|
+
if (locations.length && !locations.includes(instance.location)) continue;
|
|
512
|
+
setPath(out, instance.path, instance.value);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
module.exports = { body, cookie, header, param, query, check, validationResult, matchedData, Result };
|