forked from jashkenas/backbone
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathschema.js
More file actions
516 lines (445 loc) · 12.8 KB
/
schema.js
File metadata and controls
516 lines (445 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import { isString, isArray, isObject, isPlainObject, each, keys } from 'lodash-es';
/**
* @import { Model } from './nextbone.js'
* @import { z } from 'zod'
*/
/**
* @template T
* @typedef {new (...args: any[]) => T} Ctor
*/
/**
* @typedef {z.ZodObject<any>} ZodSchema
*/
/**
* @typedef {Record<string, any>} AttributesMap
*/
/**
* @typedef {string[]} PathList
*/
/**
* @typedef {Record<string, z.ZodTypeAny>} SchemaShape
*/
/**
* @typedef {Record<string, string>} ValidationErrorMap
*/
/**
* @callback ValidCallback
* @param {string} attr
* @param {Model} model
* @returns {void}
*/
/**
* @callback InvalidCallback
* @param {string} attr
* @param {string} message
* @param {Model} model
* @returns {void}
*/
/**
* @typedef {object} ValidationOptions
* @property {boolean} [validate]
* @property {PathList} [attributes]
* @property {ValidCallback} [valid]
* @property {InvalidCallback} [invalid]
*/
// Helper functions
// ----------------
// Flattens an object into dot-separated paths
// eg:
//
// var o = {
// owner: {
// name: 'Backbone',
// address: {
// street: 'Street',
// zip: 1234
// }
// }
// };
//
// becomes:
//
// var paths = [
// 'owner.name',
// 'owner.address.street',
// 'owner.address.zip',
// 'owner.address',
// 'owner'
// ];
/**
* @param {AttributesMap} obj
* @param {PathList} [into]
* @param {string} [prefix]
* @returns {PathList}
*/
var flattenObjectPaths = function (obj, into, prefix) {
into = into || [];
prefix = prefix || '';
each(obj, function (val, key) {
if (obj.hasOwnProperty(key)) {
if (isPlainObject(val)) {
flattenObjectPaths(val, into, prefix + key + '.');
}
into.push(prefix + key);
}
});
return into;
};
/**
* @param {z.ZodTypeAny} schema
* @returns {z.ZodTypeAny}
*/
var unwrapSchema = function (schema) {
var currentSchema = schema;
while (currentSchema && typeof currentSchema.unwrap === 'function') {
currentSchema = currentSchema.unwrap();
}
return currentSchema;
};
/**
* @param {z.ZodTypeAny} schema
* @returns {SchemaShape|undefined}
*/
var getSchemaShape = function (schema) {
return unwrapSchema(schema)?.shape;
};
/**
* @param {z.ZodTypeAny} schema
* @param {string} [prefix]
* @param {PathList} [into]
* @returns {PathList}
*/
var getSchemaLeafPaths = function (schema, prefix, into) {
prefix = prefix || '';
into = into || [];
var shape = getSchemaShape(schema);
if (!shape) {
prefix && into.push(prefix);
return into;
}
each(shape, function (fieldSchema, key) {
var path = prefix ? prefix + '.' + key : key;
getSchemaLeafPaths(fieldSchema, path, into);
});
return into;
};
/**
* @param {string} path
* @param {string} candidate
* @returns {boolean}
*/
var matchesPath = function (path, candidate) {
return path === candidate || path.startsWith(candidate + '.') || candidate.startsWith(path + '.');
};
/**
* @param {PathList} paths
* @param {string} path
* @returns {boolean}
*/
var hasMatchingPath = function (paths, path) {
for (var index = 0; index < paths.length; index++) {
if (matchesPath(path, paths[index])) {
return true;
}
}
return false;
};
/**
* @param {PathList} paths1
* @param {PathList} paths2
* @returns {boolean}
*/
var hasCommonPaths = function (paths1, paths2) {
for (var index = 0; index < paths1.length; index++) {
if (hasMatchingPath(paths2, paths1[index])) {
return true;
}
}
return false;
};
/**
* @param {z.ZodTypeAny} schema
* @param {PathList} paths
* @returns {PathList}
*/
var getAffectedSchemaPaths = function (schema, paths) {
var leafPaths = getSchemaLeafPaths(schema);
return leafPaths.filter(function (leafPath) {
return hasMatchingPath(paths, leafPath);
});
};
/**
* @param {AttributesMap} obj
* @param {string} path
* @param {*} value
* @returns {AttributesMap}
*/
var setPathValue = function (obj, path, value) {
var parts = path.split('.');
var current = obj;
for (var index = 0; index < parts.length - 1; index++) {
var part = parts[index];
if (!isPlainObject(current[part])) {
current[part] = {};
}
current = current[part];
}
current[parts[parts.length - 1]] = value;
return obj;
};
/**
* @param {AttributesMap} target
* @param {AttributesMap|undefined|null} source
* @returns {AttributesMap}
*/
var mergeNestedAttrs = function (target, source) {
if (!isPlainObject(source)) {
return target;
}
each(source, function (value, key) {
if (isPlainObject(value)) {
var base = isPlainObject(target[key]) ? target[key] : {};
target[key] = mergeNestedAttrs(base, value);
return;
}
target[key] = value;
});
return target;
};
/**
* @param {AttributesMap} currentAttrs
* @param {AttributesMap|undefined} attrs
* @returns {AttributesMap}
*/
var buildValidationAttrs = function (currentAttrs, attrs) {
var allAttrs = mergeNestedAttrs({}, currentAttrs);
mergeNestedAttrs(allAttrs, attrs);
return allAttrs;
};
// Returns the attributes that have defined schema validation.
/**
* @param {PathList|undefined} attrs
* @param {ZodSchema} schema
* @returns {PathList}
*/
var getValidatedPaths = function (attrs, schema) {
return attrs ? getAffectedSchemaPaths(schema, attrs) : keys(getSchemaShape(schema) || {});
};
/**
* @param {z.ZodError} zodError
* @returns {ValidationErrorMap|undefined}
*/
// Formats Zod error messages into a flat object keyed by attribute name
var formatZodErrors = function (zodError) {
if (zodError.issues.length === 0) return;
var errors = {};
zodError.issues.forEach(function (issue) {
// Get the path to the error (e.g., ['name'] or ['address', 'street'])
var path = issue.path.length > 0 ? issue.path.join('.') : '_root';
// Only store the first error for each path
if (!errors[path]) {
errors[path] = issue.message;
}
});
return errors;
};
/**
* @param {ValidationErrorMap|undefined} errors
* @param {PathList} paths
* @returns {ValidationErrorMap|undefined}
*/
var collectRequestedErrors = function (errors, paths) {
if (!errors) return;
var errorPaths = keys(errors);
var invalidAttrs;
paths.forEach(function (path) {
var matchingPath = errorPaths.find(function (errorPath) {
return matchesPath(path, errorPath);
});
if (matchingPath) {
invalidAttrs = invalidAttrs || {};
invalidAttrs[path] = errors[matchingPath];
}
});
return invalidAttrs;
};
// Validates attributes using the Zod schema
/**
* @param {AttributesMap} attrs
* @param {ZodSchema} schema
* @returns {ValidationErrorMap|undefined}
*/
var validateWithSchema = function (attrs, schema) {
const result = schema.safeParse(attrs);
if (result.success) {
return;
}
return formatZodErrors(result.error);
};
/**
* @param {{ __schemaInstance?: ZodSchema, schema?: ZodSchema }} ctor
* @returns {ZodSchema|undefined}
*/
const getSchema = (ctor) => {
if (ctor.hasOwnProperty('__schemaInstance')) {
return ctor.__schemaInstance;
}
return (ctor.__schemaInstance = ctor.schema);
};
/**
* @template {typeof Model} ModelClass
* @param {ModelClass} ModelClass
* @returns {ModelClass}
*/
function createClass(ModelClass) {
return class extends ModelClass {
/**
* @description Check whether or not a value, or a hash of values passes validation without updating the model
* @param {string|AttributesMap} attr - Attribute name or object with attributes
* @param {*} [value] - Value to validate (if attr is a string)
* @returns {string|ValidationErrorMap|undefined} - Error message(s) if invalid, undefined if valid
*/
preValidate(attr, value) {
var schema = getSchema(this.constructor);
if (!schema) return;
if (isObject(attr)) {
var validatedPaths = getAffectedSchemaPaths(schema, flattenObjectPaths(attr));
if (!validatedPaths.length) {
return;
}
var allAttrs = buildValidationAttrs(this.attributes, attr);
var errors = validateWithSchema(allAttrs, schema);
return collectRequestedErrors(errors, validatedPaths);
}
// todo: verify if checking for affected paths is necessary here.
// commenting do not break tests, but may be a lack of coverage for this code path.
var requestedPaths = getAffectedSchemaPaths(schema, [attr]);
if (!requestedPaths.length) {
return '';
}
var validationAttrs = buildValidationAttrs(this.attributes);
setPathValue(validationAttrs, attr, value);
return (
collectRequestedErrors(validateWithSchema(validationAttrs, schema), [attr])?.[attr] || ''
);
}
/**
* Check to see if an attribute, an array of attributes or the
* entire model is valid.
* @param {string|PathList|ValidationOptions} [opts] - Attribute name, array of names, or options
* @returns {boolean}
*/
isValid(opts) {
var attributes;
if (isString(opts)) {
attributes = [opts];
} else if (isArray(opts)) {
attributes = opts;
}
var error = (this.validationError =
this.validate(null, { validate: true, attributes }) || null);
if (!error) return true;
this.trigger('invalid', this, error, opts);
return false;
}
/**
* This is called by Nextbone when it needs to perform validation.
* You can call it manually without any parameters to validate the
* entire model.
* @param {AttributesMap|null} [attrs] - Attributes to validate
* @param {ValidationOptions} [options] - Options
* @returns {ValidationErrorMap|undefined} - Validation errors if invalid, undefined if valid
*/
validate(attrs, options = {}) {
var schema = getSchema(this.constructor);
if (!schema) return;
var model = this,
validatedPaths = options.attributes
? getValidatedPaths(options.attributes, schema)
: attrs
? getAffectedSchemaPaths(schema, flattenObjectPaths(attrs))
: getValidatedPaths(undefined, schema),
allAttrs = buildValidationAttrs(model.attributes, attrs),
changedPaths = attrs ? flattenObjectPaths(attrs) : flattenObjectPaths(allAttrs),
invalidAttrs = collectRequestedErrors(validateWithSchema(allAttrs, schema), validatedPaths);
// After validation is performed, loop through all validated and changed attributes
// and call the valid and invalid callbacks so the view is updated.
if (options.valid || options.invalid) {
each(validatedPaths, function (attr) {
var invalid = invalidAttrs && attr in invalidAttrs,
changed = hasMatchingPath(changedPaths, attr);
if (!invalid) {
options.valid?.(attr, model);
}
if (invalid && (changed || !attrs)) {
options.invalid?.(attr, invalidAttrs[attr], model);
}
});
}
// Trigger validated events.
model.trigger('validated', model, invalidAttrs, options);
// Return any error messages to Nextbone.
if (invalidAttrs && hasCommonPaths(keys(invalidAttrs), validatedPaths)) {
return invalidAttrs;
}
}
};
}
// decorator
/**
* @typedef {object} SchemaInstanceMixin
* @property {(attr: string|AttributesMap, value?: any) => string|ValidationErrorMap|undefined} preValidate
* @property {(opts?: string|PathList|ValidationOptions) => boolean} isValid
* @property {(attrs?: AttributesMap|null, options?: ValidationOptions) => ValidationErrorMap|undefined} validate
*/
/**
* @typedef SchemaStaticMixin
* @property {ZodSchema} schema
*/
/**
* @template {Ctor<Model<any, any, any>>} BaseClass
* @typedef {(new (...args: ConstructorParameters<BaseClass>) => InstanceType<BaseClass> & SchemaInstanceMixin) &
* SchemaStaticMixin} SchemaMixinClass
*/
/**
* A mixin/decorator that adds Zod schema-based validation to a Model class.
* The schema should be defined as a static `schema` property on the Model class.
*
* @example
* // Function style
* class UserModel extends withSchema(Model) {
* static schema = z.object({
* name: z.string().min(1, 'Name is required'),
* email: z.string().email('Invalid email'),
* age: z.number().min(0).optional(),
* });
* }
*
* @example
* // Decorator style
* @withSchema
* class UserModel extends Model {
* static schema = z.object({
* name: z.string().min(1, 'Name is required'),
* email: z.string().email('Invalid email'),
* });
* }
*
* @template {Ctor<Model<any, any, any>>} BaseClass
* @param {BaseClass} ctorOrDescriptor - Base model class
* @returns {SchemaMixinClass<BaseClass>}
*/
const withSchema = (ctorOrDescriptor) => {
if (typeof ctorOrDescriptor === 'function') {
return createClass(ctorOrDescriptor);
}
const { kind, elements } = ctorOrDescriptor;
return {
kind,
elements,
finisher(ctor) {
return createClass(ctor);
},
};
};
export { withSchema };