-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.ts
More file actions
415 lines (358 loc) · 17.5 KB
/
Copy pathbase.ts
File metadata and controls
415 lines (358 loc) · 17.5 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
export interface FieldConfig {
type: any;
immutable?: boolean;
optional?: boolean;
required?: boolean; // Alias for optional: false, included for clarity and flexibility in schema definitions
default?: any;
enum?: any[];
max?: number;
min?: number;
beforeChecks?: (value: any) => any;
afterChecks?: (value: any) => any;
validate?: (value: any) => void;
keys?: Record<string, FieldConfig | Function>;
properties?: Record<string, FieldConfig | Function>;
values?: FieldConfig | Function;
coerce?: boolean;
}
export interface SchemaDefinition {
[key: string]: Function | FieldConfig;
}
export interface parserConfig {
safe?: boolean;
}
export interface BaseConstructor {
schema: SchemaDefinition;
immutable?: boolean;
version?: number;
}
export interface errorObject {
message: string;
source?: string | Function;
path?: string;
expected?: any;
received?: any;
code?: string;
}
// ==================== ERROR CLASSES ====================
export class ModelCoreError extends Error {
declare source: string | Function | undefined;
declare path: Array<string | number>;
declare expected: any;
declare received: any;
declare code: string | undefined;
static errorName: string = "ModelCoreError";
constructor(errObj: errorObject) {
super(errObj.message);
const ctor = this.constructor as typeof ModelCoreError;
this.name = ctor.errorName;
this.source = errObj.source;
this.path = parsePath(errObj.path);
this.expected = errObj.expected;
this.received = errObj.received;
this.code = errObj.code;
}
}
export class ImmutableObjectError extends ModelCoreError { static errorName: string = "ImmutableObjectError" }
export class ImmutablePropertyError extends ModelCoreError { static errorName: string = "ImmutablePropertyError" }
export class ValidationError extends ModelCoreError { static errorName: string = "ValidationError" }
export class EnumValueError extends ModelCoreError { static errorName: string = "EnumValueError" }
export class RangeError extends ModelCoreError { static errorName: string = "RangeError" }
export class TypeValidationError extends ModelCoreError { static errorName: string = "TypeValidationError" }
export class MissingPropertyError extends ModelCoreError { static errorName: string = "MissingPropertyError" }
export class SchemaDefinitionError extends ModelCoreError { static errorName: string = "SchemaDefinitionError" }
export class RequiredError extends ModelCoreError { static errorName: string = "RequiredError" }
export class ValueError extends ModelCoreError { static errorName: string = "ValueError" }
// ==================== TYPE INFERENCE ====================
export function Union<
T extends readonly (abstract new (...args: any) => any)[]
>(...args: T) {
if (args.length === 0) throw new Error("Union must have at least one type");
return class union extends ModelCoreUnion {
static unionTypes: T = args
constructor() {
super(...args)
return this as InstanceType<T[number]>;
}
};
}
class ModelCoreUnion extends Array<any> {
static unionTypes: readonly any[] = []
}
type UnwrapTypeConstructor<T> =
T extends StringConstructor ? string :
T extends NumberConstructor ? number :
T extends BooleanConstructor ? boolean :
T extends DateConstructor ? Date :
T extends ArrayConstructor ? any[] :
T extends ObjectConstructor ? Record<string, any> :
T extends new (...args: any[]) => infer R ? R :
unknown;
// 2. Normalize a field: detect if it's a shorthand constructor or a config object
type NormalizeField<T> = T extends FieldConfig ? T : { type: T }
// 3. Extract types for nested structures or simple primitives (using normalized fields)
type InferFieldRaw<T> =
NormalizeField<T> extends infer F extends FieldConfig ?
F['type'] extends { unionTypes: readonly any[] } ? InstanceType<F['type']['unionTypes'][number]> :
F['type'] extends ObjectConstructor ? InferObject<F> :
F['type'] extends ArrayConstructor ? InferArray<F> :
UnwrapTypeConstructor<F['type']>
: any;
// 4. Helper to cleanly separate required vs optional keys
type OptionalKeys<T extends Record<string, any>> = {
[K in keyof T]: NormalizeField<T[K]>['optional'] extends true ? K : NormalizeField<T[K]>['required'] extends false ? K : never
}[keyof T];
type RequiredKeys<T extends Record<string, any>> = {
[K in keyof T]: NormalizeField<T[K]>['optional'] extends true ? never : NormalizeField<T[K]>['required'] extends false ? never : K
}[keyof T];
// 5. Remap objects cleanly, handling both shorthand and verbose nested keys
type InferObject<T extends FieldConfig> =
T['keys'] extends Record<string, any>
? { [K in RequiredKeys<T['keys']>]: InferFieldRaw<T['keys'][K]> } &
{ [K in OptionalKeys<T['keys']>]?: InferFieldRaw<T['keys'][K]> }
: Record<string, any>;
type InferArray<T extends FieldConfig> = T['type'] extends ArrayConstructor ? Array<InferFieldRaw<T['values']>> : any[];
// 6. Map over the entire schema definition (handles mix of shorthand and verbose keys)
export type SchemaToType<S extends Record<string, any>> =
{ [K in RequiredKeys<S>]: InferFieldRaw<S[K]> } &
{ [K in OptionalKeys<S>]?: InferFieldRaw<S[K]> };
// ==================== HELPER FUNCTIONS ====================
function isNone(that: any): boolean { return that === undefined || that === null; }
function parsePath(path: string | undefined): Array<string | number> {
const parts: Array<string | number> = [];
path?.replace(/[^.[\]]+/g, (match) => {
if (/^\d+$/.test(match)) parts.push(Number(match));
else parts.push(match);
return "";
});
return parts;
}
function buildError(
errorType: new (errObj: errorObject) => ModelCoreError,
message: string,
source?: string | Function,
path?: string,
expected?: any,
received?: any,
code?: string
): ModelCoreError {
return new errorType({ message, source, path, expected, received, code });
}
function normalizeConf(conf: FieldConfig | any, path: string): FieldConfig {
if (typeof conf === "function") return { type: conf } as FieldConfig;
if (conf && typeof conf === "object" && 'type' in conf) return conf as FieldConfig;
throw buildError(SchemaDefinitionError, `Invalid schema definition for '${path}'`, undefined, path, null, undefined, "SCHEMA_DEFINITION_ERROR");
}
// ==================== BASE CLASS ====================
export default class Base {
declare static schema: SchemaDefinition;
declare static version?: number;
declare static immutable?: boolean;
declare version?: number | undefined;
[key: string]: any;
constructor(obj: Record<string, any>, parseConfig?: parserConfig) {
this.update(obj, parseConfig, true);
}
static createFrom<T extends typeof Base>(
this: T,
obj: SchemaToType<T['schema']>,
parseConfig?: parserConfig
): SchemaToType<T['schema']> {
return new this(obj, parseConfig) as any;
}
update(obj: Record<string, any>, parseConfig?: parserConfig, isNew: boolean = false): void {
const ctor = this.constructor as typeof Base & BaseConstructor;
try {
if (!obj || typeof obj !== "object") throw TypeError("Input must be an object");
this.setProperties(ctor.schema, obj as Record<string, any>, isNew);
if (ctor.version) this["version"] = ctor.version;
} catch (e) {
for (const key in this) {
// This will make all properties of the object return the error when accessed,
// signaling that the object is in an invalid state due to failed validation
delete this[key];
Object.defineProperty(this, key, {
value: e,
writable: false,
enumerable: true,
configurable: true,
});
}
if (!parseConfig?.safe) throw e;
}
}
toObject(): Record<string, any> {
const obj: Record<string, any> = {};
for (const key in this) obj[key] = this[key];
return obj;
}
json(): string { return JSON.stringify(this.toObject()); }
private setProperties(schema: SchemaDefinition, data: Record<string, any>, isNew: boolean = false): void {
const ctor = this.constructor as typeof Base & BaseConstructor;
if (ctor.immutable && !isNew)
throw buildError(
ImmutableObjectError, `Cannot update immutable object of type ${ctor.name}`,
ctor.name, "", null, data, "IMMUTABLE_CLASS_UPDATE"
);
if (!isNew) data = { ...this, ...data };
for (const key in schema) {
const conf = schema[key];
let value = data[key];
this.runValidate(conf, value, key, isNew, this, key);
}
}
private runValidate(confPassed: FieldConfig | Function, valuePassed: any, path: string, isNew: boolean, container: Record<string, any> = this, propertyName?: string): any {
const { conf, value } = this.validateType(confPassed, valuePassed, path);
let toReturn: typeof conf.type;
const unionTypes = conf.type === ModelCoreUnion ? new conf.type() : conf.type.prototype instanceof ModelCoreUnion ? new conf.type() : null;
if (
conf.type === Array ||
(unionTypes && unionTypes.some((t: any) => t === Array || t.prototype instanceof Array))
|| (!unionTypes && conf.type.prototype instanceof Array)
) {
if (!conf.values) throw buildError(
SchemaDefinitionError, `Missing array value configuration at ${path}`,
this.runValidate, path, null, value, "SCHEMA_DEFINITION_ERROR"
);
toReturn = new conf.type();
// define non-writable indexed properties to prevent direct overwrites
for (let i = 0; i < value.length; i++) {
const validated = this.runValidate(conf.values!, value[i], `${path}[${i}]`, isNew);
Object.defineProperty(toReturn, i, {
value: validated,
writable: false,
enumerable: true,
configurable: true,
});
}
// Monkey-patch Array dangerous methods
const vd = this;
Object.defineProperty(toReturn, 'push', {
value: function (...items: any[]) {
const validatedItems = items.map((item, i) => vd.runValidate(conf.values!, item, `${path}[${this.length + i}]`, false));
for (let i = 0; i < validatedItems.length; i++) Object.defineProperty(this, this.length + i, { value: validatedItems[i], writable: false, enumerable: true, configurable: true });
return this.length += validatedItems.length;
},
enumerable: false
});
Object.defineProperty(toReturn, 'fill', {
value: function () {
throw buildError(ValueError, `Array.fill() is not allowed on validated arrays. Use Array.splice() instead for controlled modifications.`, this.validateType, path, null, value, "INVALID_ARRAY_METHOD");
},
enumerable: false
});
Object.defineProperty(toReturn, 'unshift', {
value: function (...items: any[]) {
const validatedItems = items.map((item, i) => vd.runValidate(conf.values!, item, `${path}[${i}]`, false));
for (let i = this.length - 1; i >= 0; i--) {
const currVal = this[i];
Object.defineProperty(this, i + validatedItems.length, { value: currVal, writable: false, enumerable: true, configurable: true });
}
for (let i = 0; i < validatedItems.length; i++) Object.defineProperty(this, i, { value: validatedItems[i], writable: false, enumerable: true, configurable: true });
return this.length += validatedItems.length;
},
enumerable: false
});
Object.defineProperty(toReturn, 'splice', {
value: function (start: number, deleteCount?: number, ...items: any[]) {
const curr = Array.prototype.slice.call(this) as any[];
const len = curr.length;
const s = start < 0 ? Math.max(len + start, 0) : Math.min(start || 0, len);
const dc = deleteCount === undefined ? len - s : Math.max(0, Math.min(deleteCount, len - s));
const validatedItems = items.map((item, i) => vd.runValidate(conf.values!, item, `${path}[${s + i}]`, false));
const result = curr.slice(0, s).concat(validatedItems).concat(curr.slice(s + dc));
const deleted = curr.slice(s, s + dc);
for (let i = 0; i < (this as any).length; i++) delete (this as any)[i];
for (let i = 0; i < result.length; i++) Object.defineProperty(this, i, { value: result[i], writable: false, enumerable: true, configurable: true });
(this as any).length = result.length;
return deleted;
},
enumerable: false
});
Object.defineProperty(toReturn, 'concat', {
value: function (...arrays: any[]) {
const curr = Array.prototype.slice.call(this) as any[];
let result = curr;
for (const arr of arrays) {
if (!Array.isArray(arr)) throw buildError(ValueError, 'Can only concat arrays to validated array properties.', this.validateType, path, null, value, "INVALID_CONCAT_VALUE");
const validatedItems = arr.map((item, i) => vd.runValidate(conf.values!, item, `${path}[${result.length + i}]`, false));
result = result.concat(validatedItems);
}
return result;
},
enumerable: false
});
}
else if (conf.type === Object || (unionTypes && unionTypes.some((t: any) => t === Object))) {
if (!conf.keys && !conf.properties)
throw buildError(SchemaDefinitionError, `Object properties schema definition missing for '${path}'`, this.runValidate, path, value.constructor, conf, 'SCHEMA_DEFINITION_ERROR')
const obj: Record<string, any> = {};
for (const childKey in conf.keys)
this.runValidate(conf.keys[childKey], value[childKey], `${path}.${childKey}`, isNew, obj, childKey);
toReturn = obj;
}
else toReturn = value;
if (conf.immutable && !isNew) {
const p = path.match(/[^.[\]]+/g)?.reduce((o, key) => o?.[key], this);
if (!isNone(p) && p !== toReturn)
throw buildError(ImmutablePropertyError, `Cannot update immutable property '${path}'`, this.constructor.name, path, null, value, "IMMUTABLE_PROPERTY_UPDATE");
}
if (conf.validate && typeof conf.validate === "function") conf.validate(toReturn);
if (propertyName !== undefined) {
let currentValue = toReturn;
Object.defineProperty(container, propertyName, {
get: () => currentValue,
set: (newVal) => {
const ctor = this.constructor as typeof Base & BaseConstructor;
if (ctor.immutable) throw buildError(ImmutableObjectError, `Cannot update immutable object of type ${ctor.name}`, ctor.name, path, null, value, "IMMUTABLE_PROPERTY_UPDATE");
this.runValidate(conf, newVal, path, false, container, propertyName);
},
enumerable: true,
configurable: true,
});
}
return toReturn;
}
private validateType(cnf: any, value: any, path: string): { conf: FieldConfig; value: any } {
const conf: FieldConfig = normalizeConf(cnf, path);
const unionTypes = conf.type === ModelCoreUnion ? new conf.type() : conf.type.prototype instanceof ModelCoreUnion ? new conf.type() : null;
if (conf.beforeChecks && typeof conf.beforeChecks === "function") {
const newVal = conf.beforeChecks(value);
if (!isNone(newVal) || conf.optional) value = newVal;
}
if (isNone(value)) {
if (!isNone(conf.default)) value = typeof conf.default === 'function' ? conf.default() : conf.default;
if (isNone(value)) {
if (conf.optional) return { conf, value };
if (!conf.optional) throw buildError(RequiredError, `Missing required property at '${path}'`, this.validateType, path, null, value, "REQUIRED_PROPERTY_MISSING");
}
}
const isOfType = () => {
return (unionTypes && unionTypes.some((t: any) => value.constructor === t)) || value.constructor === conf.type
};
if (!isOfType()) {
// Attempt to coerce the value to the correct type if possible. Valuable for date strings from a json for example
if (conf.coerce) value = !unionTypes ? new conf.type(value) : (() => {
// dangerous but necessary! Javascript will most probably coerce in an invalid away
// like new Array({}) = [{}] instead of throwing so we can check the next type.
// We have to accept the language's downsides here.
// Avoid coercion on Unions unless you're sure about the input, as it can lead to unexpected results.
// You can instead use beforeChecks() hook to preprocess the value for safety and control.
for (const t of unionTypes) {
const coerced = new t(value);
if (coerced.constructor === t) return coerced;
}
})();
if (!isOfType() || isNaN(value))
throw buildError(TypeValidationError, `Invalid type at '${path}', expected ${conf.type.name}, got ${value.constructor.name}`, this.constructor.name, path, null, value, "INVALID_TYPE");
}
if ((conf.max !== undefined) && (value.length ? value.length > conf.max : value > conf.max)) throw buildError(RangeError, `Value too large for '${path}', maximum: ${conf.max}`, this.validateType, path, null, value, "VALUE_TOO_LARGE");
if ((conf.min !== undefined) && (value.length ? value.length < conf.min : value < conf.min)) throw buildError(RangeError, `Value too small for '${path}', minimum: ${conf.min}`, this.validateType, path, null, value, "VALUE_TOO_SMALL");
if (conf.enum && !conf.enum.includes(value)) throw buildError(EnumValueError, `Invalid value for '${path}', expected one of: ${conf.enum.join(", ")}`, this.validateType, path, null, value, "INVALID_ENUM_VALUE");
if (conf.afterChecks && typeof conf.afterChecks === "function") {
const newVal = conf.afterChecks(value);
if (!isNone(newVal) || conf.optional) value = newVal;
}
return { conf, value };
}
}